syntax error: unexpected token <

476,216

Solution 1

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.

Solution 2

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');
};

Solution 3

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

Solution 4

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.

Solution 5

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!

Share:
476,216

Related videos on Youtube

Geovane Krüger
Author by

Geovane Krüger

Mestrando no curso de pós-graduação em Ed. Física da UFSC. Treinador na consultoria esportiva Race Pace e também atleta de Mountain Bike. Professor de tênis na Elase. De vez em quando gosto de brincar no desenvolvimento de um site utilizando php e jQuery.

Updated on July 08, 2022

Comments

  • Geovane Krüger
    Geovane Krüger almost 2 years

    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
    
    • Sergio
      Sergio over 10 years
      Does it say which file in the console?
    • Patrick Evans
      Patrick Evans over 10 years
      the error should have given you a file and line number, post the specific line it points to.
    • Geovane Krüger
      Geovane Krüger over 9 years
      I don't remember where I found the error. But was in php code.
  • Geovane Krüger
    Geovane Krüger over 10 years
    Strange, because I have several other commands using JS URL's the same way and it works perfectly, I just gave you this problem. And in my PC works perfectly when put on server does not work.
  • lwdthe1
    lwdthe1 almost 7 years
    Thanks. This worked for me. I mispelled my js file name.
  • Admin
    Admin about 2 years
    As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.