Getting parse error while fetching text file content in JQuery - javascript

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"
});
on console,
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.

You said:
dataType: "jsonp",
But the URL is responding with:
Deployment automatically finished…
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.
async: false,
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).
crossDomain: true,
This has no effect unless you are making a:
non-JSONP request
to the same origin
which gets redirected to a different origin
… which is very rare.
headers: {
"Access-Control-Allow-Origin": "*"
},
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:
function logResults(result){
console.log(result);
}
$.ajax({
url: u,
success: logResults
});
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.

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.

Related

Request [/.../_search] contains unrecognized parameters: [_], [callback] AJAX and elasticsearch 5.x

I have part AJAX code, but it returns status 400 Bad Request
{
"error" : {
"root_cause" : [
{
"type" : "illegal_argument_exception",
"reason" : "request [/.../_search] contains unrecognized parameters: [_], [callback]
My code is blow:
jQuery.ajax({
url:url/_search?pretty=true',
type: 'POST',
dataType: 'jsonp',
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(query)
}).done(function(xhr) {
alert("Success");
}).fail(function(xhr) {
alert(xhr.hits.hits);
})
I have enabled Cross in elasticsearch.yml file with http.cors.enabled: true. Need some help pls
Those parameters are being added because you have told jQuery to expect a JSONP response. Consequently it is making a JSONP request (with <script> tags instead of XMLHttpRequest) and telling the server what callback function name to use.
As a side-effect this forces the request to be GET and prevents headers (such as content-type) being modified.
Don't tell jQuery to use JSONP unless the API requires that you do (JSONP is a dirty hack that has been superceeded by CORS so you should only have to use it with legacy APIs now).

"Uncaught SyntaxError: Unexpected token <" after successful HTTP Request

I am trying to do AJAX using jQuery with an ODATA REST service provided by an SAP backend system.
$.ajax({
type: 'GET',
url: 'http://sapxx.sapms/sap/opu/odata/.../',
async: true,
dataType: 'jsonp',
username: 'username',
password: 'password',
crossDomain: true,
success: function() {
alert('Done.');
},
error: function() {
alert('Error.');
},
});
The request returns status 200 and I get a response from the server which is called something like "?callback=jQuery3100687..." and contains xml code. All this is visible in the Chrome debugger. But after the successful HTTP Request I get the aforementioned error
Uncaught SyntaxError: Unexpected token <
I suspect the error is due to the "dataType" parameter which is set to "jsonp" in the request. Is there any way to work around this error? The server can only respond using XML format. The request only works when the dataType is set to "jsonp", I guess because it enables CORS. After sending the request, I get the "Error" alert despite the 200 status.
You say you get an xml response from the server. Your ajax request is set up for jsonp, though:
dataType: 'jsonp',
Try this instead:
dataType: 'xml',
success: function(xml) {
//remainder of the code
}
If you set the dataType to jsonp, jQuery will try to parse the response as JSON. This results in errors, because the response ins't JSON.

Uncaught SyntaxError: Unexpected token : ajax call

So I'm trying to query the below json feed, however I keep getting the error in the topic.
I've searched around this site for possible answers however none that I've come across have worked so far. Commented out datatype and jsonp, jsonpCallback isnt it either, either is data, I've made sure that it validats via http://jsonformatter.curiousconcept.com/ and it does. I really dont know.
$.ajax({
type: 'GET',
url: 'http://raidbots.com/json/playerdata/us/mannoroth/usiris',
cache:true,
dataType: 'jsonp',
data: {
format: 'json',
},
success: ranks,
jsonpCallback:'callbackName',
error: function(data) { console.log(data); },
jsonp: false,
});
function callbackName(data){
console.log("jsonpCallback");
}
var ranks = function(data) {
console.log(data);
}
Thank you
-Art
The error is in your JSONp data because it's just JSON and not JSONp. JSONp requires the document to be valid JavaScript containing a function call.
If they don't support jsonp you need to use a proxy script (e.g. a php script on your server that retrieves the document) or ask them to send CORS headers so you can use a normal non-JSONp AJAX call to retrieve the data directly.

XmlHttpRequest status 0 even when the call to service succeeded

I call to Wcf Service via Jquery(JS), after a long time of trying it works.
The call to service is as follows:
function CallService() {
var request = { userName: "aaa", password: "123" };
var jsondata = JSON.stringify(request);
$.ajax({
type: "POST", //GET or POST or PUT or DELETE verb
url: "http://localhost:xxxx/Service1.svc/GetUser", // Location of the service
data: jsondata, //Data sent to server
contentType: "application/json; charset=utf-8", // content type sent to server
dataType: "json", //Expected data format from server
processdata: true, //True or False
crossDomain: true, //True or False
success: function (result) {
alert('success');
},
complete: function () {
alert('completed');
},
error: function (xhr, status, message) {
alert('error with status - ' + xhr.status);
}
});
}
I put BreakPoint in GetUser function that is in service and when I call the function CallService I go to the BreakPoint of Service (which means it works!).
Service function works great and returns the correct data, but to Jquery I get the Error function with status 0.
In addition, in the console I see a red error:(Not generally understood as an error)
POST http://localhost:xxx/Service1.svc/GetUser
What could be the problem?
It could be that you're making a cross-domain request. Note that the same host name with different ports are considered different domain. For example: http://localhost:20 and http://localhost:40 are considered different domains.
In your case, it could be that your browser supports CORS and therefore requests to a different domain are still sent. That's why when you debug on server side you see it works, but when the browser receives response from the server, the response is discarded and an error is raised because of missing Access-Control-Allow-Origin header from the response or having the Access-Control-Allow-Origin header but with a value different than your domain.
My problem was that in User object I had DateTime.
When I turned it to String it worked.

Rails: Get remote page via ajax

I use Rails3 and I try to get remote page via ajax. (https://play.google.com/store/apps/details?id=).
$.ajax({
url: app_url,
type: 'GET',
data: "id=<id>",
crossDomain : true,
dataType: 'jsonp',
success: function ( code ) {
alert("Good.");
}
});
When I run the script, the I see: "Uncaught SyntaxError: Unexpected token < " error message.
By the way, I tried do it as:
$.ajax({
url: app_url,
type: 'GET',
data: "id=<id>",
crossDomain : true,
dataType: 'jsonp',
success: function ( code ) {
alert("Good.");
}
});
But I see "Origin http://example.com:3000 is not allowed by Access-Control-Allow-Origin." error message.
How can I fix the error and get the page ?
Thanks.
If you are trying to access remote pages via AJAX, that page may be blocking your request. The error message would suggest this: https://developer.mozilla.org/en-US/docs/HTTP_access_control
EDIT
For clarity, Access-Control-Allow-Origin is the server setting which "origins" are allowed to retrieve from it. You could possibly grab this page server-side, and depending on google's level of security, you may have to spoof a browser. PHP CURL comes to mind. You would then set up an ajax call to your server script, your server would go get the page for you, then return it to you ajax call.

Categories

Resources