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 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.
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 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).
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.
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!
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.
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.
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 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=array#f.com&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);
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>
Removing this line from my code solved my problem.
header("Content-Type: application/json; charset=UTF-8");
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.
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.
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.
If you are running the NVM on your system, you must check the node version before starting the server.
Related
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();
});
});
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.
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.
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.
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.
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.
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.
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
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.
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.
"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
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.
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.
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";
In my case putting / at the beginning of the src of scripts or href of stylesheets solved the issue.
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
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)
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.
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...
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.
In my case it was a mistaken url (not existing), so maybe your 'send' in second line should be other...
This error might also mean a missing colon or : in your code.
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)"
Late to the party but my solution was to specify the dataType as json. Alternatively make sure you do not set jsonp: true.
Try this to ignore this issue:
Cypress.on('uncaught:exception', (err, runnable) => {
return false;
});
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..
I have a Django web app which has various instances of ck-editor instances on a web page.By using on blur event I am saving whole of data of the instance in the database -
{% for editor in editors %}
CKEDITOR.appendTo("{{editor.ck_id}}" ,
{
on: {
blur: function(event){
var data = event.editor.getData();
console.log("data of {{editor.ck_id}} is " + data);
var request = $.ajax({
url: "/editor/save/",
type: "GET",
data: {
content : data,
content_id : "{{editor.ck_id}}"
},
dataType: "html"
});
}
}
}
// "{{editor.data}}"
);
CKEDITOR.instances['{{editor.ck_id}}'].insertHtml("{{editor.data}}");
Here ck_id and data are the two database fields of ckeditors.Now suppose I write this on one instance of ckeditor -
Tony Stark
When I lose focus on that instance then on blur event is fired and I use 'getData()' to get the html data of that instance.
<p>Tony Stark</p>
is saved into the database.On the python interpreter now when I fetch editor's data it shows -
<p>Tony Stark</p>
which is obvious.
Now When I re start the server and set the data of every ck-editor instance again then this exception is raised -
Uncaught SyntaxError: Unexpected token ILLEGAL
I know why this is happening - due to this -
CKEDITOR.instances['ck_1'].insertHtml("<p>Tony Stark</p>
");
The data which I sent by fetching from database was -
<p>Tony Stark</p>
and it somehow got converted to above mentioned text with illegal tokens.I have tried to use setData() but with no result. Do I need to encode/decode this HTML or something?
Now my question is how to again reset data to a ck-editor instance which I fetched from it and stored in database. I have posted this question on several forums but many people have got no clue of what I am asking?
Is there anyone here who has tried to do same thing and have succeeded in it?
Thanks
PS: Adrian Ghiuta solution seems to be working but there is just problem. When the editor is loaded first time then in google chrome's debugger inserted line is seen as -
"<p>Tony Stark</p>"
which is rendered due to line "{{editor.data|safe}}".But when I change my editor's content to just
Tony
then in database
<p>Tony</p>
is being saved but when I restart the server it does not render and throws this error
Unexpected ILLEGAL TOKEN
due to this -
"<p>Tony</p>
"
Here ending double quotes are in the next line.But during initial data loading it was on the same line.Might this be causing be any problem?
Because my chrome console shows error at that position.
I will add some images to show the condition.
Initial loading -
Initial console -
Editor after editing -
Error being shown after restarting server and reloading editors -
Console -
You can see how error is thrown at line where double quotes are at the next line.Do I to escape html or something?
Sorry for my naivety but I do not have much command over HTML.
I got this javascript code in a JSP:
$('#myForm').submit(function(event) {
event.preventDefault();
var act = $('#myForm').attr('action') + '&act=' + $('#submitBtn').val();
var dataStr = $("#myForm").serialize();
$.post(act, dataStr, function(data, status) {
$('body').html(data);
});
return false;
});
The facts:
I'm using jquery v1.3.x (and I can't replace with newer version because of company policy).
The jsp is in a pop-up window.
There is a submit button with id=submitBtn
When the submit button is clicked, it will execute above code and send the data into struts action.
The action url:
someAction.do?someParam=blabla&someNo=213354345&mode=POP&act=Update Your Data
(note: I had replaced some sensitive data, but the argument pattern is same)
The problem is at this line:
$('body').html(data);
It produces Error: NS_ERROR_FAILURE: Failure in error console. I heard it's related with cross domain request, but my application is at localhost, how could it happened?
In IE 8, it successfully replaced the current page content with the data value (which is html string). But in firefox (v22), it gave blank page, I checked with right click -> View Source, it's really empty. Then I checked with firebug, the response data indeed contains the result html page string. If I debug with alert(data); before the $('body').html() call, it also show the html string.
So the $.post() function successfully returns the response data but it seems the $('body').html() function failed to render the data.
So what is actually happened? I'm really have no clue.
What is the solution for this?
UPDATE:
I checked the error console, I got this error after submitted the page:
Error: NS_ERROR_FAILURE: Failure
Source File: http://localhost:8080/myapp/script/jquery.js
Line: 19
UPDATE 2:
I debug the java code, I found out that the input html tag in the JSP that has indexed array name like this:
myItem[0].name
myItem[1].name
...
were not successfully submitted to the ActionForm class. I investigated the source of problem might come from a 3rd party javascript library.
try something like this
$.post(act, dataStr, function(data) {
document.body.innerHTML = data;
});
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 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.
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 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).
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.
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!
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.
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.
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 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=array#f.com&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);
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>
Removing this line from my code solved my problem.
header("Content-Type: application/json; charset=UTF-8");
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.
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.
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.
If you are running the NVM on your system, you must check the node version before starting the server.
I am new to the web development world and I would like to be able to connect an HTML page to a web api through . and I was really not successful in this.
I followed this tutorial to be able to make this connection : http://www.asp.net/web-api/overview/getting-started-with-aspnet-web-api/tutorial-your-first-web-api
All I need is to send some inputs from an HTML page to a web api that takes these parameters and returns an object
I am using this code
$.getJSON("api/GeneratorController/setparameters/"+firstparameter+"/"+secondparameter+"/"+thirdparameter+"/"+fourthparameter+"/"+fifthparameter+"/"+sixthparameter,
function (data) {
alert(data); //never comes here
}).fail(function (jqXHR, textStatus, err) {
alert("All checks are correct, image was not generated. jqXHR = " + jqXHR.valueOf() + " textStatus=" + textStatus + " Error" + err);
});
it always goes into the fail portion , I attached the alert message that comes out of it
Any Reason why it is doing this ?
#smartmeta (I changed the typo , thanks) I followed your advice and here is the output of the alert (as expected , values that I have inserted are displayed):
Your url needs to start with your domain, not 'api/generatorcontroller/...'. If you are developing locally, something like http://localhost:[port]/api/generatorController/....
Also, webApi maps to url verbs, (get, post, put, delete..), not functions like setparameters, unless you have a [name=setparameters] above your get() function.
Also, I am pretty sure you don't have a route setup to handle the url with all those parameters. What you want to look at, as it seems your using jQuery, is jQuery.get documentation. The second example near the bottom shows where to place parameters. WebAPI will check for them in the body if they are not in the query string. so it would end up looking like:
$.getJSON("http://"+window.location.host+"/api/GeneratorController/setparameters", {parameter1: parameter1, parameter2:parameter2 ...});
Well, the first thing to check is to make sure that your server-side function is returning the values you expect. You can do this with Chrome's developer tools or with the Firebug Firefox extension, and I think IE10 has something equivalent, too. Go to the "net" tab, find the request corresponding to your API call, and take a look at what the server responded with.
Please add the line
alert("api/GeneratorController/setparameters/"+firstparemeter+"/"+secondparameter+"/"+thirdparameter+"/"+fourthparameter+"/"+fifthparameter+"/"+sixthparameter)
Then call your script and take the output of the alert into a browser. Then check if your application Handels that route.
By the way I think you have a typo. I guess it should be firstparameter.
I assume you would like to do
"api/GeneratorController?foo=Bar
But when you are new to this, I would suggest that you first try the example like it is. And After that you can start changing setails.
So I found what was the problem with my code
Two things :
1- I shouldn't use the word "Controller" when I call my API ,it should be api/Generator/...
2- the function name needs to start with "get" and not "set" since it "gets" the return value from the api
Thanks everyone!