I'm setting up a plugin that requires passing of a variable from a stand alone jQuery file to options.php. I have (I think) set up the scripts to be used in my plugin file like so:
function ndw_js_init(){
wp_enqueue_script('jquery');
wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );
wp_enqueue_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array(), '1.0.0', true);
$scriptdata = array('admin_ajax' => admin_url( 'admin-ajax.php' ));
wp_localize_script( 'ndw_js', 'toremove', $scriptdata);
}
add_action('admin_init', 'ndw_js_init');
Where I am coming unstuck is in the jQuery file. The variable is passed onclick. So far I have this which works fine (tested using an alert()):
$('tr td .widget-remove a').click(function(){
var toremove = $(this).attr('rel');
var url = 'options.php'; // EDIT: Actualy, is this right? Or should the data be passed to the name of my plugin main page I wonder
// Out of ideas
});
So what I need is help to use the correct AJAX syntax to pass the value of var 'toremove' to 'options.php' and then do something in 'options.php' using the value of 'toremove'.
Hope that makes sense!
EDIT No.1:
OK, so after playing with different settings provided by all of you I have a (semi) functional script:
function ndw_js_init(){
wp_register_script( 'ndw_js', plugin_dir_url( __FILE__ ) . '/ndw_js.js', array( 'jquery' ), '', true );
wp_enqueue_script( 'ndw_js' ); // not working without this
wp_localize_script( 'ndw_js', 'toremove', array('ajaxurl' => admin_url( 'admin-ajax.php' )));
}
add_action('admin_init', 'ndw_js_init');
Without these settings as they are nothing works. In my external js file I now have:
$('tr td .widget-remove a').click(function(){
var toremove = $(this).attr('rel');
$.ajax({
type: 'POST',
dataType: 'json',
url: ajaxurl,
data: {
nonce : toremove.nonce,
toremove : toremove
},
complete: function( data ){
alert(toremove + " ding!");
}
});
});
This works - but only the jQuery code. In the Admin area on my plugin settings page the alert fires on click with the correct id no and the word 'ding!'.
Back to my plugin settings page and I add this (thanks @MMK):
function ndw_ajax_function(){
$toremove = $_POST['toremove'];
echo "To remove: " . $toremove;
}
add_action('wp_ajax_my_ajax_action', 'ndw_ajax_function' );
This does not work, I view the generated source and the echoed line does not appear. However, I am not sure in that last add action what wp_ajax_my_ajax_action refers to.
admin_inithook you might want to skip theadmin_ajaxkey and value as its already populated by Wordpress and available in the backend. Just use theajaxurlvariable to get the ajax url.