jublikon
jublikon

Reputation: 3447

Request issue: Uncaught SyntaxError: Unexpected token /

I am developing i small app that displays some JSON data inside of a listview. To receive the data I am using a simple request.
And I am getting always the same issue:

Uncaught SyntaxError: Unexpected token :

my code:

 $.ajax({
   url: 'http://localhost/documents.json',
   data: {
      format: 'json'
   },
   error: function() {
      $('#info').html('<p>An error has occurred</p>');
   },
   dataType: 'jsonp',
   success: function(data) {
    // do something with the data
   },
   type: 'GET'
});      
});

My JSON file is valid. I checked it with a JSON validator.

Upvotes: 1

Views: 750

Answers (2)

&#193;lvaro Gonz&#225;lez
&#193;lvaro Gonz&#225;lez

Reputation: 146450

Invalid JSON (no matter how mangled) cannot generate a JavaScript syntax error if you parse it with JSON.parse() or any decent dedicated parser (and that's what jQuery does). The same happens with all other standard data types (XML, HTML, plain text...). All symptoms suggest you're expecting JSONP but getting some other data type. The builtin browser network pane should reveal what you're getting exactly.

Whatever, if you only want JSON and nothing but JSON you should simplify your code as follows:

  1. Omit protocol and host:

    url: 'http://localhost/documents.json',
    

    should be:

    url: '/documents.json',
    

    (Probably not required, but will help to void errors.)

  2. Ask for the correct data type:

    dataType: 'jsonp',
    

    should be:

    dataType: 'json',
    
  3. Do not parse again what jQuery already parsed for you:

    var json = $.parseJSON(data);
    

    should be:

    var json = data; // Yeah, nothing :)
    

This should be enough for local AJAX. If you really need a cross-site request (I asked twice and never got an answer) you have to tweak your server to either return the appropriate CORS headers or implement JSONP data type and change your client-side code accordingly because you'll no longer have JSON—because JSONP is not JSON!

Upvotes: 2

Robert Auer
Robert Auer

Reputation: 23

Check if your json is valid by using jsonlint.com or you can use jsonmate.com. These are very helpful to me when I'm debugging json.

Also - it would help to have a link to the full code. Use jsfiddle.net to put your code into - then link it to this post. This will help the community debug your code.

Upvotes: 0

Related Questions