Disclaimer: not sure this is WordPress related or not.
I’m following a simple tutorial to check if AJAX works in my WordPress localhost.
My ajax-test.js :
jQuery(document).ready( function($){
$(".ajax-link").click( function(){
var data = {
action: 'test_response',
post_var: 'this will be echoed back'
};
$.post(the_ajax_script.ajaxurl, data, function(response) {
alert(response);
});
return false;
});
});
In my plugin, I add the script to the wp_print_scripts() and add the processing function:
function test_ajax_load_scripts(){
wp_enqueue_script("ajax-test", plugin_dir_url( __FILE__ ) . 'ajax-test.js', array( 'jquery' ) );
wp_localize_script('ajax-test', 'the_ajax_script', array( 'ajaxurl' => admin_url('admin-ajax.php') ) );
}
add_action('wp_print_scripts', 'test_ajax_load_scripts');
function text_ajax_process_request(){
if(isset($_POST["post_var"])){
$response = $_POST["post_var"];
echo $response;
die();
}
}
add_action('wp_ajax_test_response', 'test_ajax_process_request');
I get the link output with the href=”#” and I click it and it brings me to the top of the page. I check Firebug and I can confirm that the ajax-test.js is loaded in the header. There is nothing in the console.
How else can I debug why the alert is not happening?
Your event wire-up function needs an
e.preventDefault()in it: