ajax/json call in WordPress ends up in malformed JSON

I’m making an ajax call in a meta box and returning some very simple data. However, it keeps throwing an error:

parsererror
SyntaxError: JSON.parse: unexpected non-whitespace character after JSON data

Here’s the ajax call:

Read More
uid = new Date().getTime();
appReq = jQuery.ajax({
    type : 'post',
    dataType : 'json',
    url : 'admin-ajax.php',
    data : { action : 'get_app_sidebars', post_id : currentApp, uid : uid }
});
appReq.done(function(data){
    if(data.widgetNum > 0 && data.widgetName != '' && data.widgetBase != '') {
        alert(data);
    }
    else {
        // do something here
    }
});
appReq.fail(function(jqXHR, textStatus, errorThrown){
    alert(textStatus + 'n' + errorThrown);
});

And here’s the php:

function get_app_sidebars(){
    // get the meta for a custom post type
    $meta = $this->get_app_meta($_REQUEST['post_id']);
    $result['widgetNum'] = $meta['num_widgets'];
    $result['widgetName'] = $meta['widget_name'];
    $result['widgetBase'] = $meta['widget_base'];
    $result = json_encode($result);
    echo $result;
}

The problem comes in when I get the data back:

{"widgetNum":"6","widgetName":"Custom Sidebars","widgetBase":"my-custom-sidebars"}0

Ok, that “0” at the end is in the response when I look at this in firebug. This is driving me nuts, and I can’t figure out WTF is going on with the JSON as it’s being sent to the browser. If I trim the 0 and run it through jsonlint, it passes.

Related posts

Leave a Reply

3 comments

  1. I’d suggest using wp_send_json_success, as it takes care of everything (json encoding, echo and die()):

    function get_app_sidebars()
    {
        $meta = $this->get_app_meta($_REQUEST['post_id']);
        if( $meta )
        {
            $result['widgetNum'] = $meta['num_widgets'];
            $result['widgetName'] = $meta['widget_name'];
            $result['widgetBase'] = $meta['widget_base'];
            wp_send_json_success( $result );
        } 
        else
        }
            wp_send_json_error( array(
                'error' => 'Custom error message'
            ));
        }
    }
    

    Also, make the necessary security checks with check_ajax_referer.

  2. Somewhere in your code, a 0 is being printed. It’s not in the function you gave, but that function is obviously getting called somewhere. You can confirm this by changing echo $result to die($result), although this doesn’t fix the root problem, which is that somewhere you have a print statement that shouldn’t be there.