Keren Keren - 5 months ago 33
JSON Question

JSONP callback is returning error

I'm trying to learn JSONP. From my research online, I understood that it's invoke function with callback.Apart from that everything else (the way data is handled/data format) similar to JSON?

I'm just playing with JSONP as below. But It's returning error, please explain in detail about it, please..

Script.js

function test(){
jQuery.ajax({
url: "/plugins/system/chat/jsonstr.php",
dataType: "jsonp",
jsonpCallback: "logResults"
});


jsonstr.php

logResults(){
$arr = '[{
"title": "keren",
"picture": "http://something.png",
"id":1
}, {
"title": "diana",
"picture": "/plugins/system/conversekit/conversekit/images/avatar.png",
"id": 2
}]';
echo $arr;
}


I expect this call to return json object so that I can manipulate it in success function of test. But error as below is thrown:

<br />
<b>Parse error</b>: syntax error, unexpected '{' in <b>C:\projects\easysocial.com\plugins\system\conversekit
\jsonstr.php</b> on line <b>14</b><br />


The url in console is as this:

GET http://mysite.localhost.com/plugins/system/chat/jsonstr.php?callback=logResults

Answer

logResults() is JavaScript callback, not PHP function. jsonstr.php should only return valid JSON.

So jsonstr.php should look like this

<?php

 $arr = [
            [
                'title' => "keren",
                'picture' => "http://something.png",
                'id' => 1,
            ],
            [
                'title' => "diana",
                'picture' => "/plugins/system/conversekit/conversekit/images/avatar.png",
                'id' => 2,
            ],
        ];

echo(json_encode($arr));

And Script.js

function test(){
    jQuery.ajax({
      url: "/plugins/system/chat/jsonstr.php",
      dataType: "jsonp",
      jsonpCallback: "logResults"
    });
}
function logResults() {
    console.log('ajax done');
}