parsererror after jQuery.ajax request with jsonp content type
Asked Answered
N

9

60

I am using jQuery Version 1.5.1 to do the following ajax call:

$.ajax({
    dataType: 'jsonp',
    data: { api_key : apiKey },
    url: "http://de.dawanda.com/api/v1/" + resource + ".json",
    success: function(data) { console.log(data); },
    error: function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); console.log(textStatus); }
});

The server responds with a valid json object:

{
  "response": {
    "type":"category",
    "entries":1,
    "params":{
      "format":"json",
      "api_key":"c9f11509529b219766a3d301d9c988ae9f6f67fb",
      "id":"406",
      "callback":"jQuery15109935275333671539_1300495251986",
      "_":"1300495252693"
    },
    "pages":1,
    "result":{
      "category":{
        "product_count":0,
        "id":406,
        "restful_path":"/categories/406",
        "parent_id":null,
        "name":"Oberteile"
       }
     }
   }
 }

But the success callback is never called, instead the error callback produces this output:

jQuery15109935275333671539_1300495251986 was not called
parsererror

Why does this happen?

I am using no additional libraries to jQuery.

EDIT:

If I try to make the ajax call with "json" as dataType instead of "jsonp", the server responds with an empty string.

Ng answered 19/3, 2011 at 0:47 Comment(0)
A
61

JSONP requires that the response be wrapped in some kind of callback function, because it works by injecting a script tag into the document as a mechanism to load data from another domain.

Essentially, what happens is a script tag gets dynamically inserted into the document like so:

<script src="http://the.other.server.com/foo?callback=someFn"></script>

callback is dependent on the resource you're calling, it's common for the parameter to be callback though.

someFn is then used to process the returned data from the server, so the server should respond with:

someFn({theData: 'here'});

The someFn is passed as part of the request, so the server needs to read it and wrap the data appropriately.

This is all assuming you're grabbing the content from another domain. If so, you're limited by the same origin policy: http://en.wikipedia.org/wiki/Same_origin_policy

Atthia answered 19/3, 2011 at 0:52 Comment(6)
The API in the question is a public API by a vendor. It just restricts the calls to be jsonp only. Jsonp calls are answered, but as a normal Json object.Ng
In this example, someFn is the callback, and the server should respond with: jQuery15109935275333671539_1300495251986({...});Aceydeucy
Thank god, wish they'd add some f--ing documentationNonpros
I can't understand this one. You mean i need to wrap the response from the server with, eg: $callBack({$myJsonResult}); I'll do that one at the server side?Trauma
@AdamMorris How is the server suppose to know the function ? I meand that long number in jQuery15109935275333671539_1300495251986 ? How do you pass that information to the server ?Patsis
This method completely solved my parse error problem.Glycerinate
F
10

After upgrading to Jquery 1.5 and attempting to make a call across domains I had the same problem. Eventually I found the $.getJSON worked. Specifically,

$.getJSON(url,
    function(data){
        yourFunction(data);
       return false;
    });

The URL I used was like this:

var url = WEB_SERVER_URL;
url = url + "&a=" + lat;
url = url + "&b=" + lng; ....
url = url + "&jsoncallback=?";

In the server, which is running on another server and I have control of this code was added:

PrintWriter writer = response.getWriter();
String jsonString = json.toString(JSON_SPACING);
String callback = request.getParameter("jsoncallback");
// if callback in URL and is not just the "?" (e.g. from localhost)
if (callback != null && callback.length() > 1)
{
    writer.write(callback + "(" + jsonString + ");");
}
else
{
    writer.write(jsonString);
}

(The json object is an instance of JSONObject, the code can be found here http://www.json.org/java/)

Fourposter answered 26/4, 2011 at 4:25 Comment(0)
P
6

when you are using jsonp as datatype (making cross domain request) Jquery generate random function and append is to requested url as a querystring named callback (callback=?), you need to append response json data as a parameter of this function as given below -

url : http://www.dotnetbull.com/cross-domain-call.ashx?ref=jquery-jsonp-request
url call by ajax :
http://www.dotnetbull.com/cross-domain-call.ashx?ref=jquery-jsonp-request&callback=jQuery1510993527567155793_137593181353

Response data should look like this :

 string callback = context.Request.QueryString["callback"];

 if (!string.IsNullOrEmpty(callback))
   context.Response.Write(string.Format("{0}({1});", callback, jc.Serialize(outputData)));
else
   context.Response.Write(jc.Serialize(outputData));

Read more about : parsererror after jquery.ajax request with jsonp content type

enter image description here

Phenomenal answered 5/8, 2013 at 18:44 Comment(0)
F
3

there is one little mistake :) You have to request .js and not .json.

$.ajax({
    dataType: 'jsonp',
    data: { api_key : apiKey },
    url: "http://de.dawanda.com/api/v1/" + resource + ".js",
    success: function(data) { console.log(data); },
    error: function(jqXHR, textStatus, errorThrown) { console.log(errorThrown); console.log(textStatus); }
});

Ah and did you notice, that there is a client for the api ? https://github.com/dawanda/dawanda-api-client-js

Footloose answered 21/3, 2011 at 8:14 Comment(2)
Thank you very much for your answer! The API works like a charm now :) I used the api client at first, but i want to stick with a jquery only approach.Ng
You can use the client with jQuery as well. It will automatically detect Prototype or jQuery and use the given methods. (Y)Footloose
F
1

You really shouldn't specify jsonp here. Just use json because you're just receiving a JSON string. json (json with padding) expects a javascript function execute. In that case you need to specify a "callback=" within your querystring. I guess that is.the reason why jQuery can't handle this aswell, there is a property with the name callback.

Feeder answered 19/3, 2011 at 0:55 Comment(2)
I get an empty string as an answer if I just use json for the request. Could it be the api is broken? And if so, is there a way to hack this in js?Ng
you mean "jsonp (json with padding)", not "json (json with padding)"Kirkuk
S
1

Try reading the response into an object using $.parseJSON:

success: function(data) {
    var json = $.parseJSON(data);
}
Sungod answered 19/3, 2011 at 1:0 Comment(1)
No that will not fix the parsererror after jQuery.ajax request with jsonp content typeEgin
M
1

Ensure that the service you are calling has the ability to return data in JsonP format.

If you are using asp.net webapi, you can use WebApiContrib.Formatting.Jsonp, it's open source.

Ensure that you have a line like below in WebApiConfig.Register.

config.Formatters.Insert(0, new JsonpMediaTypeFormatter(new JsonMediaTypeFormatter(), "callback"));

I was pulling my hair over this. Hope this helps someone.

Magbie answered 5/6, 2014 at 16:0 Comment(0)
T
0

Not all servers support jsonp. It requires the server to set the callback function in it's results. I use this to get json responses from sites that return pure json but don't support jsonp (But might in the future):

function AjaxFeed(){

    return $.ajax({
        url:            'http://somesite.com/somejsonfile.php',
        data:           {something: true},
        dataType:       'jsonp',

        /* Very important */
        contentType:    'application/json',
    });
}

function GetData()
    AjaxFeed()

    /* Everything worked okay. Hooray */
    .done(function(data){
        return data;
    })

    /* Okay jQuery is stupid manually fix things */
    .fail(function(jqXHR) {

        /* Build HTML and update */
        var data = jQuery.parseJSON(jqXHR.responseText);

        return data;
    });
}
Tutelage answered 19/10, 2013 at 14:3 Comment(1)
I really hoped this would work as it looked quite clever but jqXHR.responseText is always undefined...Photoreceptor
I
0

The same problem I was getting until I have not appended parameter "callback=?" or "c=?" in url.

Like : "http://de.dawanda.com/api/v1/" + resource + ".json&c=?"

May solve your problem. It worked for me.

Interbrain answered 21/5, 2016 at 12:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.