Uncaught SyntaxError: Unexpected token :
Asked Answered
F

27

251

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();
  });
});
Flowerlike answered 29/6, 2010 at 18:37 Comment(6)
The JSON is fine. The problem is probably how you handle it. Showing the code will help.Vivyan
Added the portion of code to the question.Flowerlike
There doesn't seem to be anything wrong with the syntax, the JS nor JSON. Posting a (not)working test-case on jsfiddle.net would help - including HTML.Verde
You can check the site that is causing problems here: trobrock.com:8011 click on "Cat 1" and then the problem happens when clicking vote, and have only seen the problem in chrome so farFlowerlike
I'm currently tethering internet so my modem compresses the HTML source of the websites I browse, so I can't really make heads or tails out of the code. But, for starters put every JS code in external files - this always makes debugging easier - you'll know weather the error is caused by JS or something else.Verde
An "unexpected token" is likely some illegal character code. Such a code is likely not to show up when you print to console. Therefore, print out the string one character at a time or use a protocol analyzer or debugger etc. to see the actual bytes of the string.Koeppel
F
20

I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:

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

If anyone knows why the standard Request object was giving me problems I would love to know.

Flowerlike answered 30/6, 2010 at 20:27 Comment(6)
the difference between standard request and request.json is mostly in the headers, it adds this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'}); - go figureProceeding
Weird that that is what was causing the issue with this.Flowerlike
What are the double $$ there?Sierrasiesser
@DimitarChristoff --any answer for falsarella about the $$?Glyptodont
@Glyptodont The double dollar selector is defined in MooTools.Dust
@melpomene, you're right. Comment removed to avoid confusion.Dippold
J
151

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.

Jackqueline answered 28/10, 2014 at 17:56 Comment(9)
I have no idea why you are talking about "Unexpected token <" when question is about Unexpected token :. Your answer is completely unrelated to OP's problem.Purr
And how do I fix this? I have a php redirect that is causing this in Chrome.Tudela
To add to @andy_magoon, in my case, I had a script tag that was supposed to serve up javascript, but because the request was redirected to an HTML page (its not important why it was redirected), which begins with <!DOCTYPE html>, which is not valid javascript, the browser returns the SyntaxError when it attempt to parse the HTML as JS.Bilestone
@Thom The way to fix it is to make sure that the HTTP get returns the javascript file that you're looking for, and not unexpected HTML.Bilestone
I got exactly this error because, as it turns out, the file path is incorrect and it can't find the file specified in script tag.Inane
mine was 301 redirect issue itself. Fixed by appending / at the end of url.Crape
I sometimes get this error when I try running an uncompleted project deployment on Heroku.Niemi
@Bilestone I feel what you said is completely valid. But now how do i make the browser understand or send javascript file from the serverLachrymatory
for anyone with a similar issue, I ran into this as I added / before my query string after .htmlWonacott
C
88

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.

Crasis answered 28/8, 2010 at 20:19 Comment(5)
I think I am having the inverse of this problem. I'm requesting JSON from a third party API and they are returning application/javascript as the response and I am getting the same error you reported in this question. Not sure how to deal with it.Antefix
A strange problem is - it works fine on the localhost but not on the sever. Any idea why?Encipher
Hello. I have exact problem and I can't solve it, can someone tell me how you send JSON back to serverEntomology
Thanks I was sending application/javascript (as I misread this SO ) and was getting this error on simple valid JSON. Changing it to application/json resolved the error. I'm not using JSONP.Yarbrough
Even I'm getting the same error "Uncaught SyntaxError: Unexpected token :" , even after receiving the response in json format {"success":true,"data":2593}Etherize
R
42

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.

Redshank answered 2/5, 2012 at 11:35 Comment(3)
It helped me a lot. We should wrap the json data with jsoncallback data whenever we are using jsonp method. Also the jsonpcallback data should not start with numbers. When I tried with numbers, it didn't worked out. When I tried it with the same format shown in this answer, it worked...Molasses
True enough, but the error is the same and the code will degrade gracefully and still work if JSON is being used.Redshank
This worked for me with AJAX, jQuery & JSONP. Thanks a lot!Hellas
F
20

I have just solved the problem. There was something causing problems with a standard Request call, so this is the code I used instead:

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

If anyone knows why the standard Request object was giving me problems I would love to know.

Flowerlike answered 30/6, 2010 at 20:27 Comment(6)
the difference between standard request and request.json is mostly in the headers, it adds this.headers.extend({'Accept': 'application/json', 'X-Request': 'JSON'}); - go figureProceeding
Weird that that is what was causing the issue with this.Flowerlike
What are the double $$ there?Sierrasiesser
@DimitarChristoff --any answer for falsarella about the $$?Glyptodont
@Glyptodont The double dollar selector is defined in MooTools.Dust
@melpomene, you're right. Comment removed to avoid confusion.Dippold
D
11

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.

Dippold answered 19/12, 2013 at 2:50 Comment(2)
I did this. I was echoing out json somewhere inmy php file and was getting php[//json data] in my response but I wasn't able to parse it. Thanks for posting this so I could figure out my own mistake.Mirilla
OP problem is completely different. In your case you're trying to parse HTML as JSON, and in OP's case (s)he is trying to parse JSON as JavaScript.Purr
J
10

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.

Joselynjoseph answered 29/12, 2015 at 14:38 Comment(0)
G
5

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

Generator answered 13/8, 2015 at 19:39 Comment(0)
S
2

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.

Sparkman answered 24/3, 2016 at 22:31 Comment(0)
A
2

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.

Arcade answered 26/1, 2018 at 21:14 Comment(0)
S
2

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.

Sammons answered 9/11, 2018 at 19:45 Comment(0)
C
2

I got this error because I was missing the type attribute in script tag.

Initially I was using but when I added the type attribute inside the script tag then my issue is resolved

Chloromycetin answered 28/7, 2022 at 15:37 Comment(0)
N
1

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.

Nanna answered 13/11, 2013 at 8:31 Comment(1)
OP uses JSON, not JSONP.Purr
U
1

"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

Uintathere answered 17/3, 2015 at 10:11 Comment(1)
I recommend using console.log() instead of alert() for debugging.Purr
C
1

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";
Ci answered 11/4, 2020 at 8:3 Comment(0)
L
1

In my case putting / at the beginning of the src of scripts or href of stylesheets solved the issue.

Log answered 1/7, 2021 at 13:2 Comment(0)
B
0

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.

Broody answered 18/7, 2013 at 19:52 Comment(1)
This question is about "Unexpected token :".Purr
C
0

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)
Carmoncarmona answered 26/9, 2015 at 3:58 Comment(0)
A
0

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.

Ascocarp answered 21/6, 2017 at 13:47 Comment(0)
P
0

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...

Peg answered 21/7, 2017 at 6:13 Comment(0)
B
0

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.

Bitner answered 2/2, 2018 at 5:8 Comment(1)
i solved the same issue by correcting the baseref url - pointed to root folder => <base href="/">Pipistrelle
P
0

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

Petersham answered 20/12, 2018 at 18:1 Comment(0)
M
0

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

Megasporophyll answered 6/10, 2020 at 10:15 Comment(0)
R
0

Facing JS issues repetitively I am working on a Ckeditor apply on my xblock package. please suggest to me if anyone helping me out. Using OpenEdx, Javascript, xblock

xblock.js:158 SyntaxError: Unexpected token '=>'
at eval (<anonymous>)
at Function.globalEval (jquery.js:343)
at domManip (jquery.js:5291)
at jQuery.fn.init.append (jquery.js:5431)
at child.loadResource (xblock.js:236)
at applyResource (xblock.js:199)
at Object.<anonymous> (xblock.js:202)
at fire (jquery.js:3187)
at Object.add [as done] (jquery.js:3246)
at applyResource (xblock.js:201) "SyntaxError: Unexpected token '=>'\n    at eval (<anonymous>)\n    at Function.globalEval (http://localhost:18010/static/studio/common/js/vendor/jquery.js:343:5)\n    at domManip (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5291:15)\n    at jQuery.fn.init.append (http://localhost:18010/static/studio/common/js/vendor/jquery.js:5431:10)\n    at child.loadResource (http://localhost:18010/static/studio/bundles/commons.js:5091:27)\n    at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5054:36)\n    at Object.<anonymous> (http://localhost:18010/static/studio/bundles/commons.js:5057:25)\n    at fire (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3187:31)\n    at Object.add [as done] (http://localhost:18010/static/studio/common/js/vendor/jquery.js:3246:7)\n    at applyResource (http://localhost:18010/static/studio/bundles/commons.js:5056:29)"
Revolve answered 13/11, 2021 at 18:47 Comment(0)
H
0

Late to the party but my solution was to specify the dataType as json. Alternatively make sure you do not set jsonp: true.

Hickok answered 9/5, 2022 at 9:17 Comment(0)
C
0

Try this to ignore this issue:

Cypress.on('uncaught:exception', (err, runnable) => {
        return false;
    });
Carrel answered 9/9, 2022 at 11:17 Comment(0)
G
0

The best practice is to install all your dependencies using npm install or can install all dependencies dedicatedly

Grey answered 13/3, 2023 at 4:13 Comment(0)
P
-2

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..

Peppie answered 24/9, 2013 at 9:21 Comment(1)
OP asked about "Unexpected token :".Purr

© 2022 - 2024 — McMap. All rights reserved.