Using wp_localize_script with AJAX to pass variable from jQuery to PHP
-
I’m setting up a plugin that requires passing of a variable from a stand alone jQuery file to options.php. I have set up the scripts to be used in my plugin settings file file like so:
`function ndw_js_init(){
wp_register_script( ‘ndw_js’, plugin_dir_url( __FILE__ ) . ‘/ndw_js.js’, array( ‘jquery’ ), ”, true );
wp_enqueue_script( ‘ndw_js’ );
wp_localize_script( ‘ndw_js’, ‘toremove’, array(‘ajaxurl’ => admin_url( ‘admin-ajax.php’ )));
}
add_action(‘admin_init’, ‘ndw_js_init’);`In my external js file I have:
`$(‘tr td .widget-remove a’).click(function(){
var toremove = $(this).attr(‘rel’);
$.ajax({
type: ‘POST’,
dataType: ‘json’,
url: ndw.ajaxurl,
data: {
toremove : toremove
},
complete: function( data ){
alert(toremove + ” ding!”);
}
});
});`This half works – 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:
`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.
Any help gratefully received!
The topic ‘Using wp_localize_script with AJAX to pass variable from jQuery to PHP’ is closed to new replies.