Take the 2-minute tour ×
WordPress Development Stack Exchange is a question and answer site for WordPress developers and administrators. It's 100% free, no registration required.

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

share|improve this question

1 Answer 1

up vote 4 down vote accepted

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

share|improve this answer
    
Thanks! I should have read the codex more carefully... I've been looking at that page for days now. –  jjeaton Oct 4 '10 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 Oct 4 '10 at 2:04

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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