42

I am making a cross domain JSONP call using this code:

jQuery.ajax({
        async: true,
        url: 'http://mnews.hostoi.com/test.json',
        dataType: 'jsonp',
        method: "GET",
        error: function (jqXHR, textStatus, errorThrown) {
            console.log(textStatus + ': ' + errorThrown);
        },
        success: function (data, textStatus, jqXHR) {
            if (data.Error || data.Response) {
                exists = 0;
            }
        }
    });

When debugging in Firebug, I get the following error:

enter image description here

SyntaxError: missing ; before statement

However, when I pass my json object (available through the link in the JQ code) through a tool like jsonlint.com, it says it is valid JSON. And I don't find any anomalies either. How could it be returning a syntax error? Is it some JSONP detail I am not getting or what?

JSON Sample

{"news":[ {
  "sentences": [
    "Neuroscientists have discovered abnormal neural activity...", 
    "The researchers found that these mice showed many symptoms...", 
    "\"Therefore,\" the study authors say, \"our findings provide a novel.."
  ], 
  "summaryId": "ZJEmY5", 
  "title": "Abnormal neural activity linked to schizophrenia"
}]}

Thanks in advance.

Community
  • 1
  • 1
JZweige
  • 721
  • 2
  • 9
  • 15
  • May we see a sample of the `json` string? Just in case =) – MackieeE Oct 18 '13 at 18:00
  • Sure, it's here: http://mnews.hostoi.com/test.json – JZweige Oct 18 '13 at 18:01
  • 12
    Looks like you're returning JSON rather than JSONP. JSON != JSONP – Kevin B Oct 18 '13 at 18:01
  • @KevinB has the correct answer – BLSully Oct 18 '13 at 18:03
  • 1
    Just 1 more question, how should I change the JSON to JSONP? Should I add something in the beginning? The info on the web is kind of confusing. – JZweige Oct 18 '13 at 18:56
  • I have the exact same problem but I'm not using JSONP (same server), the ajax call is in json datatype and the json object is a valid multidimensional array coming from php. The array has 2 array inside with a string as a key. The problem is the string. If I use the normal int numeration for array keys all works fine. There is a way to fix this? It's much more readable with the string and not the decimal. thanks – Kreker Feb 05 '14 at 11:06

6 Answers6

28

JSONP is not JSON. A JSONP response would consist of a JavaScript script containing only a function call (to a pre-defined function) with one argument (which is a JavaScript object literal conforming to JSON syntax).

The response you are getting is JSON, not JSONP so your efforts to handle it as JSONP fail.

Change dataType: 'jsonp' to dataType: 'json' (or remove the line entirely, the server issues the correct content-type so you don't need to override it).

Since your script is running on a different origin to the JSON then you will also need to take steps (most, but not all, of which require that you control the host serving the JSON) to work around the same origin policy.

Community
  • 1
  • 1
Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • My script is running on a different origin, yes. I will try to implement CORS, using the link your provided. Thanks. – JZweige Oct 18 '13 at 18:10
7

The error is because it is returning JSON not JSONP.

JSONP is supposed to look like

someCallBackString({ The Object });
epascarello
  • 204,599
  • 20
  • 195
  • 236
4

Here is the working example

$.ajax({
 type: 'GET',
 url: 'http://xxx.amazonaws.com/file.json',
 dataType: 'jsonp',
 jsonpCallback: 'callback',
 success: function(json){
   console.log(json);
 }
});

And you should put callback in the beginning of your file.json like :

callback({"item":{".......

whitesiroi
  • 2,725
  • 4
  • 30
  • 64
2

As epascarello pointed out, the JSONP response must be sent like:

callBackFunction({ JSON Object })

And the caller function can then be setup like:

var url =  "http://someremoteurl.com/json";
    $.getJSON(url + "?callback=?", null, function(data) {
    callBackFunction(data);
});

Then you can loop over the response data as:

function callBackFunction(data)
{
   console.log(data);
}
Community
  • 1
  • 1
shasi kanth
  • 6,987
  • 24
  • 106
  • 158
1

If you're using "callback=?" parameter, your response on the server side should look like this:

$_callback = $_GET['callback'];    
echo $_callback . '(' . json_encode(YOUR_VARIABLE) . ');';

If "callback=?" parameter is not defined, your response should look like this:

echo '[' . json_encode($_return_array) . ']';
0

If the question is related to Ruby then in your controller make sure that you render the format correctly. example:

def view_product
   data = Product.find params[:id]
   render :json =>  data, :callback => params[:callback]
end

In your render method, you should have the :callback parameter otherwise it will render in json instead of jsonp.

Arman Ortega
  • 3,003
  • 1
  • 30
  • 28