I have created a wordpress plugin that uses ajax to update a div every 10 seconds.
It seems to work and is running the AJAX GET request, and outputs test
as it should, how ever also adds a 0
to the div output. (response)
I cant work out why it is doing it? Any suggestions?
PHP
<?php
add_action( 'wp_enqueue_scripts', 'aj_enqueue_scripts' );
function aj_enqueue_scripts() {
wp_enqueue_script( 'aj-demo', plugin_dir_url( __FILE__ ). 'aj-demo-ajax-code.js?v=2', array('jquery') );
// The second parameter ('aj_ajax_url') will be used in the javascript code.
wp_localize_script( 'aj-demo', 'aj_ajax_demo', array(
'ajax_url' => admin_url( 'admin-ajax.php' ),
'aj_demo_nonce' => wp_create_nonce('aj-demo-nonce')
));
}
add_action( 'wp_ajax_nopriv_aj_ajax_demo_get_count', 'aj_ajax_demo_process' );
add_action( 'wp_ajax_aj_ajax_demo_get_count', 'aj_ajax_demo_process' ); // For
function aj_ajax_demo_process() {
echo "test";
}
?>
Jquery / JS
jQuery(document).ready( function(){
setInterval(function(){
jQuery.ajax({
url : aj_ajax_demo.ajax_url,
type : 'get',
data : {
action : 'aj_ajax_demo_get_count',
nonce : aj_ajax_demo.aj_demo_nonce,
},
success : function( response ) {
jQuery('.now_playing_info').html(response);
},
error : function( response ) {
}
});
}, 10000);
});
2
Answers
Try to add an
exit;
at the end of function.WordPress will continue to call all of the AJAX registered callbacks until one of the callbacks kills the execution, with the final one dieing with the response of 0.
So just use
wp_die()
at the end of your code