Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Wordpress ajax die('0')

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.

like image 245
Edward Avatar asked Oct 19 '22 11:10

Edward


1 Answers

In WordPress AJAX actions, you aren't supposed to return the response, but echo the response and call die 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 of 0.

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
}
like image 94
Alexander O'Mara Avatar answered Oct 24 '22 08:10

Alexander O'Mara