2

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.

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...

1 Answer 1

4

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

2
  • Thanks! I should have read the codex more carefully... I've been looking at that page for days now.
    – jjeaton
    Commented Oct 4, 2010 at 1:57
  • You are welcome!... When you keep visiting the codex every day, you will eventually memorize plenty of pages urls like this one. :)
    – sorich87
    Commented Oct 4, 2010 at 2:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.