Why Wordpress ajax die ('0')

I added the following to the 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 returns to my javascript:

 {"response":"Ya man it worked."}0 

So, when it reaches the line $ .parseJSON (msg), 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 come from? admin-ajax.php it says on line 97:

 // Default status die( '0' ); 

Why is it here, why do I reach the line die ('0')? Should he just die () so that he doesn't ruin my answer?

It seems the only way to fix this is to either modify admin-ajax.php, or simply die () at the end of my send_email_callback () function.

+5
source share
1 answer

In WordPress AJAX actions, you do not have to answer return to the answer, but echo answer and call die yourself. WordPress will continue to call all registered AJAX callbacks until one of the callbacks kills the execution, and the last of them dies with a 0 response.

Example from WordPress Codec AJAX in plugins

 <?php add_action( 'wp_ajax_my_action', 'my_action_callback' ); function my_action_callback() { global $wpdb; // this is how you get access to the database $whatever = intval( $_POST['whatever'] ); $whatever += 10; echo $whatever; wp_die(); // this is required to terminate immediately and return a proper response } 
+2
source

All Articles