I added the following to my functions.php file:
add_action('wp_ajax_send_email', 'send_email_callback');
add_action('wp_ajax_nopriv_send_email', 'send_email_callback');
So i added the following callback function:
send_email_callback()
{
//do some processing
echo json_encode(array('response'=>'Ya man it worked.'));
//return control back to *-ajax.php
}
This is what is returned to my javascript :
{"response":"Ya man it worked."}0
So ofcourse when it reaches the $.parseJSON( msg ) line I get Uncaught SyntaxError: Unexpected number.
var request = $.ajax({
url: "/wp-admin/admin-ajax.php",
method: "POST",
data: { action : 'send_email', P : container },
dataType: "html"
});
request.done(function( msg ) {
var obj = $.parseJSON( msg );
console.log(obj.response);
});
request.fail(function( jqXHR, textStatus ) {
alert( "Request failed: " + textStatus );
});
});
So where does this 0 come from? admin-ajax.php
it says on line 97:
// Default status
die( '0' );
Why is this here, why am I reaching the die(‘0’) line? Shouldnt it be just die() so it doesnt mess up my response?
Seems the only way to fix this is either modify admin-ajax.php or simply die() at the end of my send_email_callback() function.
In WordPress AJAX actions, you aren’t supposed to
return
the response, butecho
the response and calldie
yourself. 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 of0
.Example from WordPress Codec AJAX in Plugins