[javascript] Uncaught SyntaxError: Unexpected token :

I am running an AJAX call in my MooTools script, this works fine in Firefox but in Chrome I am getting a Uncaught SyntaxError: Unexpected token : error, I cannot determine why. Commenting out code to determine where the bad code is yields nothing, I am thinking it may be a problem with the JSON being returned. Checking in the console I see the JSON returned is this:

{"votes":47,"totalvotes":90}

I don't see any problems with it, why would this error occur?

vote.each(function(e){
  e.set('send', {
    onRequest : function(){
      spinner.show();
    },
    onComplete : function(){
      spinner.hide();
    },
    onSuccess : function(resp){
      var j = JSON.decode(resp);
      if (!j) return false;
      var restaurant = e.getParent('.restaurant');
      restaurant.getElements('.votes')[0].set('html', j.votes + " vote(s)");
      $$('#restaurants .restaurant').pop().set('html', "Total Votes: " + j.totalvotes);
      buildRestaurantGraphs();
    }
  });

  e.addEvent('submit', function(e){
    e.stop();
    this.send();
  });
});

This question is related to javascript mootools google-chrome

The answer is


When you request your JSON file, server returns JavaScript Content-Type header (text/javascript) instead of JSON (application/json).

According to MooTools docs:

Responses with javascript content-type will be evaluated automatically.

In result MooTools tries to evaluate your JSON as JavaScript, and when you try to evaluate such JSON:

{"votes":47,"totalvotes":90}

as JavaScript, parser treats { and } as a block scope instead of object notation. It is the same as evaluating following "code":

"votes":47,"totalvotes":90

As you can see, : is totally unexpected there.

The solution is to set correct Content-Type header for the JSON file. If you save it with .json extension, your server should do it by itself.


I thought I'd add my issue and resolution to the list.

I was getting: Uncaught SyntaxError: Unexpected token < and the error was pointing to this line in my ajax success statement:

var total = $.parseJSON(response);

I later found that in addition to the json results, there was HTML being sent with the response because I had an error in my PHP. When you get an error in PHP you can set it to warn you with huge orange tables and those tables were what was throwing off the JSON.

I found that out by just doing a console.log(response) in order to see what was actually being sent. If it's an issue with the JSON data, just try to see if you can do a console.log or some other statement that will allow you to see what is sent and what is received.


Uncaught SyntaxError: Unexpected token }

Chrome gaved me the error for this sample code:

<div class="file-square" onclick="window.location = " ?dir=zzz">
    <div class="square-icon"></div>
    <div class="square-text">zzz</div>
</div>

and solved it fixing the onclick to be like

... onclick="window.location = '?dir=zzz'" ...

But the error has nothing to do with the problem..


This happened to me today as well. I was using EF and returning an Entity in response to an AJAX call. The virtual properties on my entity was causing a cyclical dependency error that was not being detected on the server. By adding the [ScriptIgnore] attribute on the virtual properties, the problem was fixed.

Instead of using the ScriptIgnore attribute, it would probably be better to just return a DTO.


My mistake was forgetting single/double quotation around url in javascript:

so wrong code was:

window.location = https://google.com;

and correct code:

window.location = "https://google.com";

Seeing red errors

Uncaught SyntaxError: Unexpected token <

in your Chrome developer's console tab is an indication of HTML in the response body.

What you're actually seeing is your browser's reaction to the unexpected top line <!DOCTYPE html> from the server.


I did Wrong in this

   `var  fs = require('fs');
    var fs.writeFileSync(file, configJSON);`

Already I intialized the fs variable.But again i put var in the second line.This one also gives that kind of error...


I had the same problem and it turned out that the Json returned from the server wasn't valid Json-P. If you don't use the call as a crossdomain call use regular Json.


Just an FYI for people who might have the same problem -- I just had to make my server send back the JSON as application/json and the default jQuery handler worked fine.


In my case it was a mistaken url (not existing), so maybe your 'send' in second line should be other...


This happened to because I have a rule setup in my express server to route any 404 back to /# plus whatever the original request was. Allowing the angular router/js to handle the request. If there's no js route to handle that path, a request to /#/whatever is made to the server, which is just a request for /, the entire webpage.

So for example if I wanted to make a request for /correct/somejsfile.js but I miss typed it to /wrong/somejsfile.js the request is made to the server. That location/file does not exist, so the server responds with a 302 location: /#/wrong/somejsfile.js. The browser happily follows the redirect and the entire webpage is returned. The browser parses the page as js and you get

Uncaught SyntaxError: Unexpected token <

So to help find the offending path/request look for 302 requests.

Hope that helps someone.


It sounds like your response is being evaluated somehow. This gives the same error in Chrome:

var resp = '{"votes":47,"totalvotes":90}';
eval(resp);

This is due to the braces '{...}' being interpreted by javascript as a code block and not an object literal as one might expect.

I would look at the JSON.decode() function and see if there is an eval in there.

Similar issue here: Eval() = Unexpected token : error


For me the light bulb went on when I viewed the source to the page inside the Chrome browser. I had an extra bracket in an if statement. You'll immediately see the red circle with a cross in it on the failing line. It's a rather unhelpful error message, because the the Uncaught Syntax Error: Unexpected token makes no reference to a line number when it first appears in the console of Chrome.


This has just happened to me, and the reason was none of the reasons above. I was using the jQuery command getJSON and adding callback=? to use JSONP (as I needed to go cross-domain), and returning the JSON code {"foo":"bar"} and getting the error.

This is because I should have included the callback data, something like jQuery17209314005577471107_1335958194322({"foo":"bar"})

Here is the PHP code I used to achieve this, which degrades if JSON (without a callback) is used:

$ret['foo'] = "bar";
finish();

function finish() {
    header("content-type:application/json");
    if ($_GET['callback']) {
        print $_GET['callback']."(";
    }
    print json_encode($GLOBALS['ret']);
    if ($_GET['callback']) {
        print ")";
    }
    exit; 
}

Hopefully that will help someone in the future.


"Uncaught SyntaxError: Unexpected token" error appearance when your data return wrong json format, in some case, you don't know you got wrong json format.
please check it with alert(); function

onSuccess : function(resp){  
   alert(resp);  
}

your message received should be: {"firstName":"John", "lastName":"Doe"}
and then you can use code below

onSuccess : function(resp){  
   var j = JSON.decode(resp); // but in my case i'm using: JSON.parse(resp); 
}

with out error "Uncaught SyntaxError: Unexpected token"
but if you get wrong json format
ex:

...{"firstName":"John", "lastName":"Doe"}

or

Undefined variable: errCapt in .... on line<b>65</b><br/>{"firstName":"John", "lastName":"Doe"}

so that you got wrong json format, please fix it before you JSON.decode or JSON.parse


If nothing makes sense, this error can also be caused by PHP Error that is embedded inside html/javascript, such as the one below

<br />
<b>Deprecated</b>:  mysql_connect(): The mysql extension is deprecated and will be removed in the future: use mysqli or PDO instead in <b>C:\Projects\rwp\demo\en\super\ge.php</b> on line <b>54</b><br />
var zNodes =[{ id:1, pId:0, name:"ACE", url: "/ace1.php", target:"_self", open:true}

Not the <br /> etc in the code that are inserted into html by PHP is causing the error. To fix this kind of error (suppress warning), used this code in the start

error_reporting(E_ERROR | E_PARSE);

To view, right click on page, "view source" and then examine complete html to spot this error.


I got a "SyntaxError: Unexpected token I" when I used jQuery.getJSON() to try to de-serialize a floating point value of Infinity, encoded as INF, which is illegal in JSON.


In my case i ran into the same error, while running spring mvc application due to wrong mapping in my mvc controller

@RequestMapping(name="/private/updatestatus")

i changed the above mapping to

 @RequestMapping("/private/updatestatus")

or

 @RequestMapping(value="/private/updatestatus",method = RequestMethod.GET)

This error might also mean a missing colon or : in your code.


For those experiencing this in AngularJs 1.4.6 or similar, my problem was with angular not finding my template because the file at the templateUrl (path) I provided couldn't be found. I just had to provide a reachable path and the problem went away.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to mootools

preg_match in JavaScript? Uncaught SyntaxError: Unexpected token : Comparing date part only without comparing time in JavaScript event.preventDefault() function not working in IE

Examples related to google-chrome

SessionNotCreatedException: Message: session not created: This version of ChromeDriver only supports Chrome version 81 SameSite warning Chrome 77 What's the net::ERR_HTTP2_PROTOCOL_ERROR about? session not created: This version of ChromeDriver only supports Chrome version 74 error with ChromeDriver Chrome using Selenium Jupyter Notebook not saving: '_xsrf' argument missing from post How to fix 'Unchecked runtime.lastError: The message port closed before a response was received' chrome issue? Selenium: WebDriverException:Chrome failed to start: crashed as google-chrome is no longer running so ChromeDriver is assuming that Chrome has crashed WebDriverException: unknown error: DevToolsActivePort file doesn't exist while trying to initiate Chrome Browser How to make audio autoplay on chrome How to handle "Uncaught (in promise) DOMException: play() failed because the user didn't interact with the document first." on Desktop with Chrome 66?