JavaScript

Uncaught SyntaxError: Unexpected token <

This is a common error in JavaScript, and it is hard to understand at first why it happens. But if you bear with me and remember that Bugs are a good thing you will be on your way in no time.

Here is a simple example that may cause this error.

// including jquery.js
// this script is myapp.js

// Get the json data instead of making a request
$(".mybtn").on("click",function(e){
    // Stop the default behaviour.
    e.preventDefault();
    //
    var jsonUrl = this.href + "&json=1";

    $.ajax({
        url: jsonUrl,
        type: "json",
        method: "get",

        success: function(data){
            // do something with the data
            alert(data);
        }
    });

});

In the example above, when the user clicks on a link an ajax request is triggered to return json data. If the json data is returned correctly, everyone is happy and move on. But if it doesn't, well we have to fix it. In situations like this, it's often common to see the error:

Uncaught SyntaxError: Unexpected token <

Don't run to stackoverflow right away. What the interpreter is telling us is that it found a character it was not expecting. Here the interpreter was expecting json, but it received < or HTML. If you check the response on your network developer tab, you will see that the response is HTML.

Another way you can get this error is if you add a script tag and have the src return HTML:

<script src="index.html"></script>

All it means is that the interpreter is expecting JavaScript or JSON and you are feeding it HTML/XML. If you don't think you are returning HTML, check if you are not getting a 404.

<!DOCTYPE html>
<html>
...

Comments

There are no comments added yet.

Let's hear your thoughts

For my eyes only