I am trying to fetch data from text file which resides on server. I have access of that location and able to see content when I put URL in browser tab.
I am trying to make AJAX call and get file content, but I am getting Error: Uncaught SyntaxError: Unexpected identifier
Code
function logResults(json){
console.log(json);
}
$.ajax({
url: u,
dataType: "jsonp",
jsonpCallback: "logResults"
});
I tried below code too, but same result,
$.ajax({
type: 'GET',
url: u,
crossDomain: true,
dataType: 'jsonp',
async: false,
headers: {
"Access-Control-Allow-Origin": "*"
},
success: function(succ) {
console.log("Success: ", succ)
},
error: function(err) {
console.log("Error: ", err)
}
});
This code is always going into error block.
2
Answers
It is because you have added dataType as jsonp, so that it will try to parse the response to JSON and if the response is not a JSON it will throw error.
You said:
But the URL is responding with:
Which is not JSONP, it is plain text.
You get the error when it tries to execute the plain text as JSONP.
Don’t put wrong information in the
dataType
field.That’s deprecated. Don’t use it. It’s also pointless since you are using callbacks.
It’s also incompatible with JSONP so it is ignored (until you remove the incorrect
dataType
).This has no effect unless you are making a:
… which is very rare.
Access-Control-Allow-Origin
is a response header. It doesn’t belong the request. Trying to add it to the request will cause extra problems as it will make the request preflighted.(At least, that would be the case if you hadn’t said
dataType: 'jsonp'
because adding request headers is incompatible with JSONP).All you need on the client
The only code you need on the client is:
The server you are requesting the data from will need to use CORS to grant you permission to access it if it is a cross-origin request.