Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stray character in Ajax response?

I'm using wordpress. I make a ajax call with jQuery, PHP echos out a JSON object, but the response I get in javascript has a "0" added to the end which makes decoding the json object fail.

PHP:

function newspaper_getpost() {
    $d = array('foo' => 'bar', 'baz' => 'long');
    echo json_encode($d);
}
add_action('wp_ajax_newspaper_getpost', 'newspaper_getpost');

JS:

  $.post(MyAjax.ajaxurl,{
        action : 'newspaper_getpost',
        postID : $(this).val()
        }, function(response) {
              console.log(response);
  });

Output:

{"foo":"bar","baz":"long"}0

I tried

echo substr( json_encode($d), 0, -1);

and got

{"foo":"bar","baz":"long"0

so I'm sure its not the PHP side. I could just drop the "0" off the end of the response, but I feel like something bigger is going on nd I don't want to do a cheap hack to make it work. JQuery 1.6.1 btw. Thanks!

like image 934
beardedlinuxgeek Avatar asked Oct 11 '22 22:10

beardedlinuxgeek


1 Answers

It's obvious there is a 0 completely unrelated to this javascript piece. You can see that you chopped the last character off of the response and it removed the } but the 0 remains. You need to look at the rest of your PHP/HTML as there is a stray character somewhere being output.

If you were to add exit(); right after the echo, you'd see the 0 go away.

like image 120
Fosco Avatar answered Oct 14 '22 02:10

Fosco