[javascript] syntax error: unexpected token <

I've tried many things and there's no way, always appears this error I tried to use only one option to see if passed, changed the call of jquery, but not.

I looked in various places on the internet about this error, but could not solve or understand why it is happening. On my pc using EasyPHP works perfectly, but when I put online does not work.

Syntax Error: unexpected token <

Here's my code:

$(function(){
$('#salvar').click(function(){
    var key = 'salvar';
    var title = $('#title').val();
    var opcao1 = $('#opcao1').val();
    var opcao2 = $('#opcao2').val();
    var opcao3 = $('#opcao3').val();
    var opcao4 = $('#opcao4').val();
    var opcao5 = $('#opcao5').val();
    var opcao6 = $('#opcao6').val();

    if(title.length > 0){
        if(opcao2.length > 0){
            $('#resposta').removeClass().html('Salvando a enquete...<br clear="all"><br><img src="images/switch-loading.gif" />');
            $.ajax({
            type : 'POST',
            url : 'funcoes/enquete_adm.php',
            dataType : 'json',
            data: {key:key,title:title,opcao1:opcao1,opcao2:opcao2,opcao3:opcao3,opcao4:opcao4,opcao5:opcao5,opcao6:opcao6},
            success : function(data){
                if(data.sql == 'ok'){
                        $('#resposta').addClass('success-box').html('Enquete Salva!').fadeIn(1000);
                        $('#control').fadeOut();
                    }else if(data.sql == 'error'){
                        $('#resposta').addClass('info-box').html('Ops, aconteceu um erro. Por favor, tente novamente').fadeIn(1000);
                    }
                },
            error: function (XMLHttpRequest, textStatus, errorThrown) {    
                alert("XMLHttpRequest " + XMLHttpRequest[0]);alert(" errorThrown: " + errorThrown);alert( " textstatus : " + textStatus);    
            }
            });
        }else{
            $('#resposta').addClass('warning-box').html('É necessário no mínimo duas opções');
        };
    }else{
        $('#resposta').addClass('warning-box').html('Coloque a pergunta da enquete');
    };
    return false;

});
}); // End

This question is related to javascript jquery ajax syntax token

The answer is


You have unnecessary ; (semicolons):

Example here:

 }else{
        $('#resposta').addClass('warning-box').html('É necessário no mínimo duas opções');
    };

The trailing ; after } is incorrect.

Another example here:

}else{
    $('#resposta').addClass('warning-box').html('Coloque a pergunta da enquete');
};

I was also having syntax error: unexpected token < while posting a form via ajax. Then I used curl to see what it returns:

curl -X POST --data "firstName=a&lastName=a&[email protected]&pass=aaaa&mobile=12345678901&nID=123456789123456789&age=22&prof=xfd" http://handymama.co/CustomerRegistration.php

I got something like this as a response:

<br />
<b>Warning</b>:  Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>3</b><br />
<br />
<b>Warning</b>:  Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>4</b><br />
<br />
<b>Warning</b>:  Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>7</b><br />
<br />
<b>Warning</b>:  Cannot modify header information - headers already sent by (output started at /home/handymama/public_html/CustomerRegistration.php:1) in <b>/home/handymama/public_html/CustomerRegistration.php</b> on line <b>8</b><br />

So all I had to do is just change the log level to only errors rather than warning.

error_reporting(E_ERROR);

This error can also arise from a JSON AJAX call to a PHP script that has an error in its code. Servers are often set up to return PHP error information formatted with html markup. This response is interpreted as invalid JSON, resulting in the "unexpected token <" AJAX error.

To view the PHP error using Chrome, go to the Network panel in the web inspector, click the PHP file listed on the left side, and click on the Response tab.


make sure you are not including the jquery code between the

< script > < /script >

If so remove that and code will work fine, It worked in my case.


I suspect you're getting text/html encoding in response to your request so I believe the issue is:

dataType : 'json',

try changing it to

dataType : 'html',

From http://api.jquery.com/jQuery.get/:

dataType Type: String The type of data expected from the server. Default: Intelligent Guess (xml, json, script, or html).


Just gonna throw this in here since I encountered the same error but for VERY different reasons.

I'm serving via node/express/jade and had ported an old jade file over. One of the lines was to not bork when Typekit failed:

script(type='text/javascript')
  try{Typekit.load();}catch(e){}

It seemed innocuous enough, but I finally realized that for jade script blocks where you're adding content you need a .:

script(type='text/javascript').
  try{Typekit.load();}catch(e){}

Simple, but tricky.


When posting via ajax, it's always a good idea to first submit normally to ensure the file that's called is always returning valid data (json) and no errors with html tags or other

<form action="path/to/file.php" id="ajaxformx">

By adding x to id value, jquery will not process it.

Once you are sure everything is fine then remove the x from id="ajaxform" and the empty the action attribute value

This is how I sorted the same error for myself just a few minutes ago :)


i checked all Included JS Paths

Example Change this

<script src="js/bootstrap.min.js" type="text/javascript"></script>

TO

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js" type="text/javascript"></script>

This usually happens when you're including or posting to a file which doesn't exist. The server will return a regular html-formatted "404 Not Found" enclosed with

'<html></html>' 

tags. That first chevron < isn't valid js nor valid json, therefore it triggers an unexpected token.

What if you try to change 'funcoes/enquete_adm.php' to an absolute url, just to be sure?

EDIT (several years later)

The root cause might not always come from 404 errors. Sometimes you can make a request to an API and receive HTML formatted errors. I've stumbled to a couple of cases in which the API endpoint should have returned

{
   error: "you must be authenticated to make this request"
}

With header 401. And instead I got

<html>You must be authenticated to make this request</html>

With header 200.

Given the header is 200 you can't tell the request has failed beforehand, and you're stuck to try and JSON.parse the response to check if it's valid.


I suspect one of your scripts includes a source map URL. (Minified jQuery contains a reference to a source map, for example.)

When you open the Chrome developer tools, Chrome will try to fetch the source map from the URL to aid debugging. However, the source map does not actually exist on your server, but you are instead sent a regular 404 page containing HTML.


Removing this line from my code solved my problem.

header("Content-Type: application/json; charset=UTF-8"); 

I had a similar problem, and my issue was that I was sending javascript to display console messages.

Even when I looked at the file in my browser (not through the application) it showed exactly as I expected it to (eg the extra tags weren't showing), but there were showing in the html/text output and were trying to be parsed.

Hope this helps someone!


Just ignore parameter passing as a false in java script functions

Ex:

function getCities(stateId,locationId=false){    

    // Avoid writting locationId= false kind of statements
   /*your code comes here*/

 }

Avoid writting locationId= false kind of statements, As this will give the error in chrome and IE


This happened to me with a page loaded in via an iframe. The iframe src page had a 404 script reference. Obviously I couldn't find the script reference in the parent page, so it took me a while to find the culprit.


The error SyntaxError: Unexpected token < likely means the API endpoint didn't return JSON in its document body, such as due to a 404.

In this case, it expects to find a { (start of JSON); instead it finds a < (start of a heading element).

Successful response:

<html>
  <head></head>
  <body>
    {"foo": "bar", "baz": "qux"}
  </body>
</html>

Not-found response:

<html>
  <head></head>
  <body>
    <h1>Not Found</h1>
    <p>The requested URL was not found on the server.  If you entered the URL manually please check your spelling and try again.</p>
  </body>
</html>

Try visiting the data endpoint's URL in your browser to see what's returned.


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 jquery

How to make a variable accessible outside a function? Jquery assiging class to th in a table Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Getting all files in directory with ajax Bootstrap 4 multiselect dropdown Cross-Origin Read Blocking (CORB) bootstrap 4 file input doesn't show the file name Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource how to remove json object key and value.?

Examples related to ajax

Getting all files in directory with ajax Cross-Origin Read Blocking (CORB) Jquery AJAX: No 'Access-Control-Allow-Origin' header is present on the requested resource Fetch API request timeout? How do I post form data with fetch api? Ajax LARAVEL 419 POST error Laravel 5.5 ajax call 419 (unknown status) How to allow CORS in react.js? Angular 2: How to access an HTTP response body? How to post a file from a form with Axios

Examples related to syntax

What is the 'open' keyword in Swift? Check if returned value is not null and if so assign it, in one line, with one method call Inline for loop What does %>% function mean in R? R - " missing value where TRUE/FALSE needed " Printing variables in Python 3.4 How to replace multiple patterns at once with sed? What's the meaning of "=>" (an arrow formed from equals & greater than) in JavaScript? How can I fix MySQL error #1064? What do >> and << mean in Python?

Examples related to token

Sending the bearer token with axios JWT (JSON Web Token) library for Java Python requests library how to pass Authorization header with single token best practice to generate random token for forgot password syntax error: unexpected token < What is the difference between a token and a lexeme? how to generate a unique token which expires after 24 hours? Parse (split) a string in C++ using string delimiter (standard C++) How do I fix a "Expected Primary-expression before ')' token" error? How can a Jenkins user authentication details be "passed" to a script which uses Jenkins API to create jobs?