helgatheviking
helgatheviking

Reputation: 26319

JSON.parse in Wordpress Backend returns error

i have a dropdown list of WordPress pages with the class of 'page_id' (they repeat and can be added.. hence the livequery). on the change event i want to send an ajax request to pull out the title, excerpt and thumbnail for the page selected. at the moment I am just trying to get ANY kind of valid json response. i am using json_encode in my callback to return a json object back to my .ajax function. and then in the .ajax success function I am trying to parse this json object into something usable, but get an error every time instead.

the error seems to be a problem with JSON.parse:

JSON.parse
success(response="{"title":"bacon title","message":"bacon text"}0")   
handleError(a=Object { url="http://localhost/single/wp-admin/admin-ajax.php", global=true, more...}, b=XMLHttpRequest { onreadystatechange=[xpconnect wrapped nsIDOMEventListener], readyState=4, more...}, d="success", e="{"title":"bacon title","message":"bacon text"}0")    onreadystatechange(m=readystatechange )
[Break On This Error] var json = JSON.parse(response); 

firebug console says the response looks like:

{"title":"bacon title","message":"bacon text"}0

i don't know if that extra 0 is the trouble-maker, but i also don't know how it is getting there. chrome reports the error as:

Uncaught SyntaxError: Unexpected number
$.livequery.$.change.$.ajax.success/single/wp-admin/post.php?post=2&action=edit&message=1:917

here is my jquery function:

<script type="text/javascript">
//<![CDATA[
jQuery(function($) {

    $('.page_id').livequery(function(){ 

        var loading = $(this).next('img.ajax-loader');


        $(this).change( function() {

          var value = $(this).val();
          if (value.length) {

            $(loading).fadeIn();

            var data = {
            action: 'featured_meta_action',
            data: value,
            security: '<?php echo wp_create_nonce('featured-ajax-nonce'); ?>',
            };

            $.ajax({
                type: "POST",
                data: data,
                url: ajaxurl, 
                complete: function(){
                    $(loading).fadeOut();
                    },
                success: function(response){
                    var str = '{ "title": "bar" }';
                    var json = JSON.parse(response); 

                    alert(json['title']);
                },
                error: function(){
                    alert('fail');
                }
            });
          }//end if
        }); //end change

    }); //end livequery


}); //end ready
/* ]]> */
</script>               

my php callback looks like:

function featured_meta_action_callback(){

    $responseVar = array(
                    'title'=>'bacon title',
                    'message'=>'bacon text',
                    );

    echo json_encode($responseVar); 

}
add_action('wp_ajax_featured_meta_action', 'featured_meta_action_callback');

this has turned out to be way harder than it seems like it ought to be. i just need to get the data back from the PHP function so I can use it in the jquery. where am i going wrong?

Upvotes: 0

Views: 3776

Answers (1)

Jared Farrish
Jared Farrish

Reputation: 49208

I think it could be this:

function featured_meta_action_callback(){

    $responseVar = array(
                    'title'=>'bacon title',
                    'message'=>'bacon text' // <<< Here you do not need another comma
                    );

    echo json_encode($responseVar); 

}

See the comment within the array.

EDIT: Although unnecessary, in a test it doesn't output a 0 at the end of the JSON object if I leave it in there. So it's probable that it is coming from somewhere else (in other words, the WordPress code).

EDIT v2: Run these through Firebug's console. The second throws an error, but if you don't include the 0, it works just fine.

console.log(JSON.parse('{"title":"bacon title","message":"bacon text"}'));
console.log(JSON.parse('{"title":"bacon title","message":"bacon text"}0'));

EDIT v3: Ok, you apparently need to short circuit the rest of the WP process by calling exit/die at the end of the function, like so:

function featured_meta_action_callback(){

    $responseVar = array(
                    'title'=>'bacon title',
                    'message'=>'bacon text' // <<< Here you do not need another comma
                    );

    echo json_encode($responseVar); 

    exit;
}

Suggested here:

http://codex.wordpress.org/AJAX_in_Plugins#Ajax_on_the_Administration_Side

And here:

http://amiworks.co.in/talk/simplified-ajax-for-wordpress-plugin-developers-using-jquery/

Upvotes: 1

Related Questions