69

Trying to make a call and retrieve a very simple, one line, JSON file.

$(document).ready(function() {

    jQuery.ajax({ 
        type: 'GET',
        url: 'http://wncrunners.com/admin/colors.json' ,
        dataType: 'jsonp', 
        success: function(data) { 
            alert('success');
        }
    });


  });//end document.ready

Here's the RAW Request:

GET http://wncrunners.com/admin/colors.json?callback=jQuery16406345664265099913_1319854793396&_=1319854793399 HTTP/1.1
Host: wncrunners.com
Connection: keep-alive
Cache-Control: max-age=0
User-Agent: Mozilla/5.0 (Windows NT 6.1) AppleWebKit/535.2 (KHTML, like Gecko) Chrome/15.0.874.106 Safari/535.2
Accept: */*
Referer: http://localhost:8888/jquery/Test.html
Accept-Encoding: gzip,deflate,sdch
Accept-Language: en-US,en;q=0.8
Accept-Charset: ISO-8859-1,utf-8;q=0.7,*;q=0.3

Here's the RAW Response:

HTTP/1.1 200 OK
Date: Sat, 29 Oct 2011 02:21:24 GMT
Server: Apache/1.3.33 (Unix) mod_ssl/2.8.22 OpenSSL/0.9.7d SE/0.5.3
Last-Modified: Fri, 28 Oct 2011 17:48:47 GMT
ETag: "166a2402-10-4eaaeaff"
Accept-Ranges: bytes
Content-Length: 16
Content-Type: text/plain
Connection: close

{"red" : "#f00"}

The JSON is coming back in the response (red : #f00), but Chrome reports Uncaught SyntaxError: Unexpected token : colors.json:1

If I navigate directly to url itself, the JSON is returned and is displayed in the browser.

If I paste the contents of colors.json into JSLINT, the json validates.

Any ideas why I can't get this error and I never make it to the success callback?

EDIT - the jQuery.ajax() call above runs perfect at jsfiddle.net, and returns the alert 'success' as expected.

EDIT 2 - this URL works fine 'http://api.wunderground.com/api/8ac447ee36aa2505/geolookup/conditions/q/IA/Cedar_Rapids.json' I noticed that it returned as TYPE: text/javascript and Chrome did not throw the Unexpected Token. I've tested several other url's and the ONLY one that does not throw the Unexptected Token is the wunderground that is returned as TYPE: text/javascript.

Streams returned as text/plain and application/json are not being parsed correctly.

paparush
  • 1,340
  • 1
  • 17
  • 25
  • A side note, I realized when hitting the url in a browser the "#" doesn't actually show up in the json. http://wncrunners.com/admin/colors.json – nheinrich Oct 29 '11 at 02:40
  • Thanks for the input. I removed the # to test Keith's theory. Removing it did not affect the error. I've also removed the .json extension from the file. Same error. – paparush Oct 29 '11 at 20:30

4 Answers4

130

You've told jQuery to expect a JSONP response, which is why jQuery has added the callback=jQuery16406345664265099913_1319854793396&_=1319854793399 part to the URL (you can see this in your dump of the request).

What you're returning is JSON, not JSONP. Your response looks like

{"red" : "#f00"}

and jQuery is expecting something like this:

jQuery16406345664265099913_1319854793396({"red" : "#f00"})

If you actually need to use JSONP to get around the same origin policy, then the server serving colors.json needs to be able to actually return a JSONP response.

If the same origin policy isn't an issue for your application, then you just need to fix the dataType in your jQuery.ajax call to be json instead of jsonp.

John Flatness
  • 32,469
  • 5
  • 79
  • 81
  • 3
    Thanks John. If I take the same code and point it to **http://api.wunderground.com/api/8ac447ee36aa2505/geolookup/conditions/q/IA/Cedar_Rapids.json'** then the response does have the jQueryxxxx() wrapped around the json data, the code runs fine, and I get the 'Success' alert. I can't change the way the remote server serves up the JSON file. If I use dataType: 'json' then I get **XMLHttpRequest cannot load http://isohunt.com/js/json.php?ihq=test. Origin http://localhost:8888 is not allowed by Access-Control-Allow-Origin.** – paparush Oct 29 '11 at 22:23
  • Okay. The Weather Underground URL you gave *does* respond to JSONP requests. (You'll see this if you add `?callback=something` to that URL. The error you're getting when you use `dataType: json` is because of the same origin policy. Let me add to my answer. – John Flatness Oct 29 '11 at 22:29
  • The issue really seems to be if the server responds with Type: text/javascript, then Chrome doesn't bark about Uncaught SyntaxError. If the remote server returns as type: text/plain or application/json then Chrome reports the Uncaught SyntaxError. – paparush Oct 29 '11 at 22:29
  • @JohnFlatness thanks for explanation , i have same issue but i can't change my server code , i must have to do it on my client side call any suggestions or js that helps to solve this problem, without jsonp cross domain error comes so need to use jsonp here is fiddle for my problem http://jsfiddle.net/waamit14/wZSeB/ – Amit Rana Jul 27 '13 at 08:34
4

I have spent the last few days trying to figure this out myself. Using the old json dataType gives you cross origin problems, while setting the dataType to jsonp makes the data "unreadable" as explained above. So there are apparently two ways out, the first hasn't worked for me but seems like a potential solution and that I might be doing something wrong. This is explained here [ https://learn.jquery.com/ajax/working-with-jsonp/ ].

The one that worked for me is as follows: 1- download the ajax cross origin plug in [ http://www.ajax-cross-origin.com/ ]. 2- add a script link to it just below the normal jQuery link. 3- add the line "crossOrigin: true," to your ajax function.

Good to go! here is my working code for this:

  $.ajax({
      crossOrigin: true,
      url : "https://maps.googleapis.com/maps/api/place/nearbysearch/json?location=-33.86,151.195&radius=5000&type=ATM&keyword=ATM&key=MyKey",
      type : "GET",
      success:function(data){
         console.log(data);
      }
    })
S. Rehan
  • 69
  • 2
  • 1
    A quick heads up: that ajax cross origin plugin uses a google proxy. So all you're doing is shuffling your data to a proxy that someone else wrote for you. – user4593252 Mar 20 '18 at 15:08
2

I had the same problem and the solution was to encapsulate the json inside this function

jsonp(

.... your json ...

)

user1510230
  • 220
  • 1
  • 3
  • 13
  • 6
    Do you encapsulate on the server-side? Or is there a way to accomplish this on the client side? – Fydo Jan 28 '14 at 12:35
1

That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character

Keith.Abramo
  • 6,952
  • 2
  • 32
  • 46
  • Keith, thanks for your reply. To test, I removed the # sign from the file such that the contents are now {"red" : "f00"}, but the same error persists. One thing I notice is that the Response Content-Type is text/plain rather than application/json. – paparush Oct 29 '11 at 02:37
  • As another test, I renamed the file to just be colors (with no extension) and I get the exact same error. – paparush Oct 29 '11 at 02:52