Admin-ajax.php appending a status code to ajax response

I’m writing a plugin that uses Ajax (jQuery with form plugin) via a form submission and the php function returns a JSON response.

add_action( 'wp_ajax_bubbly-upload', 'bubbly_upload_submit' );

function bubbly_upload_submit() {
    // generate the response
    $response = json_encode( array( 'success' => true ) );

    // response output
    header( "Content-Type: application/json" );
    echo $response;
}

In Firefox, none of the jQuery response handlers were firing and the save file dialog was opening with the JSON response. I wouldn’t have the issue if I returned HTML. However, in either case, a ‘0’ was appended on to the end of my response. After some digging, it looks like jQuery will not trigger a handler if the JSON reponse is invalid. This ‘0’ being added onto the end is causing the JSON to be invalid.

Read More

If I look into the admin-ajax.php code, I see this:

default :
    do_action( 'wp_ajax_' . $_POST['action'] );
    die('0');
    break;
endswitch;

The php docs for die say that if the parameter passed is a string, then it will be printed just before exiting, if it is an integer, it will not be printed.

Without hacking the core, is there a way I can avoid this issue and still use JSON? Also, is this a bug, because I don’t see how adding a zero to the end of every AJAX response would be desired…

Related posts

Leave a Reply

1 comment

  1. Put the die(); in your function:

    add_action( 'wp_ajax_bubbly-upload', 'bubbly_upload_submit' );
    
    function bubbly_upload_submit() {
        // generate the response
        $response = json_encode( array( 'success' => true ) );
    
        // response output
        header( "Content-Type: application/json" );
        echo $response;
        die();
    }
    

    Reference: WordPress Codex, AJAX in Plugins