JSONP Parse Error with valid JSON Output - javascript

I am calling a Cross Domain AJAX Request using JSONP. Now, i am able to make it work using CORS. But, i want to know why it is not happening with JSONP. I looked at other threads with similar problem but couldnt figure out why it is not working in my case.
Here is the code:
$.ajax({
type: "GET",
url: http://XXXX:8000/sap/bc/test_rest/jsonp_test?mode=S&ticket=123,
dataType: "jsonp",
jsonp: false,
jsonpCallback: "myJsonMethod",
success: function (data) {
alert(data);
},
error: function (httpReq, status, exception) {
alert(status + " " + exception);
}
});
Now, this calls my server, the data is populated and then i get an alert "parse error myJSONMethod was not called" on a callback URL http://xxxx:8000/sap/bc/test_rest/jsonp_test?mode=S&ticket=123&_=1470322282936
Additionally, in the console i get the error as Uncaught SyntaxError: Unexpected token :
The response structure is:
{"ROOT":{"CONTRACT":"40002356","ITEM":"000010","KUNNR":"0000004676","NAME":"REALTY EXECUTIVES","NET_PRICE":19.95,"GROSS_PRICE":19.95,"MATNR":"144","SQFEET":""}}
When i run this JSON Output on jsonlint it says it is a valid JSON. I don't know where the JSON is getting messed up.

Your data must be like this to be valid for JSONP:
myJsonMethod({"ROOT":{"CONTRACT":"40002356","ITEM":"000010","KUNNR":"0000004676","NAME":"REALTY EXECUTIVES","NET_PRICE":19.95,"GROSS_PRICE":19.95,"MATNR":"144","SQFEET":""}});

the responsetext must be valid js code and it will run immediately when the response is over.So if you write your code
{"ROOT":{"CONTRACT":"40002356","ITEM":"000010","KUNNR":"0000004676","NAME":"REALTY
EXECUTIVES","NET_PRICE":19.95,"GROSS_PRICE":19.95,"MATNR":"144","SQFEET":""}}
in a <script> tag,the console will throw an err like that

Related

Unexpected token < in JSON at position 4

var url="http://fsa.citop.in/lnct/service/signProcess.aspx";
var data={txtLogId: "abc#xyz.com",txtLogPass: "xyz",hdnReqType2: "sign87162"};
var success=function(data, textStatus, jqXHR) {
console.log(data);
};
var fail=function(jqXHR, textStatus, errorThrown) {
console.log("Error:" + errorThrown );
}
$.ajax({
type: "POST",
url: url,
data:data,
success:success,
error:fail,
});
This POST request gives me the error, SyntaxError: Unexpected token < in JSON at position 4, in the console of the page 'http://fsa.citop.in/lnct/' in chrome.
But if I use fsa.citop.in/lnct/service/signProcess.aspx (i.e. no http://), it gives me no error, but nothing comes back in data. On success of POST request, a JSON object is expected. Please somebody explain what is happening here and how it could be resolved.
For those who encounter this problem in AWS Lambda code editor it is most likely your session has timed out.
Try reloading the page and signing in again.
It should resolve this.
It's most likely because the response is HTML and it's trying to parse it as something else. The < at position 4 is the first < of <!DOCTYPE html....
You should try to specify dataType in your ajax call (see http://api.jquery.com/jquery.ajax/) and also make signProcess.aspx to return something more useful (currently the response content type is application/json but it prints HTML).

jquery ajax always throws error (never becomes success)

Below is my piece of code.
My issue is the function on success never gets called.
It always throws the error section.
$.ajax({
url: 'http://localhost/zd/get_list',
data: 'term=' + medical_provider,
dataType: 'json',
type: 'GET',
success: function(data){
alert('success');
},
error: function(jqXHR, textStatus, errorThrown){
alert(jqXHR);
}
});
when i alert jqXHR is get [object Object] and when I alert textStatus I get "error" and when I alert errorThrown I get a blank error message.
I am using jquery 1.11.0.
I never get the success alert.
Your help is greatly appreciated.
Also the the data returned in json is properly validated. I did a test on jsonlint.
Your get_list server-side functionality is erroring.
Use chrome developer tools to breakpoint and inspect your jqXHR object in the error callback, it will have more details about what is going wrong.
Edit:- based on your updated comments, try adding:
contentType: 'application/json',
to your ajax call parameters
So it turns out, the base url (was using codeigniter) was my computers ip address instead of localhost. Accessing the through the ip addy OR changing the base url to localhost worked.
Thank you all for the help.

SyntaxError: Unexpected token : when using Ajax & Facebook JS API in Chrome

OK I'm using PHP and the Facebook JS API to post stories on users' pages with jQuery's $.ajax() function and it's working fine everywhere except in Chrome.
Chrome is returning the error "SyntaxError: Unexpected Token : ".
I have it alerting the XHR response on error and it is as follows:
{
"id" : "30800681_37922830145443"
}
which is valid JSON. It can't be anything I'm doing wrong with the JSON result because it throws the error before any parsing can be done (i.e., it's not making it into the 'success' function).
The code that's behind this is as follows:
if ($('#post-facebook').is(":checked")) {
// Do the FB post
$.ajax({
type: "POST",
url: "https://graph.facebook.com/<?= $this->session->userdata('fb_id') ?>/feed",
data: "message=" + $("#upload-caption").val() + "&access_token=<?= $this->session->userdata('fbtoken'); ?>&app_id=<?= $this->config->item('appId') ?>&link=" + post_url,
success: function(msg) {
// Save the FB post ID to the DB
var result = $.parseJSON(msg);
var result_array = result.id.split("_");
// Do more stuff here, but it's not even getting into this success function
},
error: function(xhr,ajaxOptions,thrownError) {
// This is what's executing because the thrown error is getting alerted
alert(thrownError);
}
});
}
When I add dataType: "json" in the Ajax parameters, it still goes through the Error function but the thrownError parameter is empty.
I am pulling my hair out...any suggestions? Thanks in advance,
Using jQuery with post is not possible as POST require CORS support, and that is not readily available.
Use FB.api instead, which handles all of this for you, in a much better way.

Download JSON file via JavaScript/JQuery - HTTP-Status Ok - JQuery Error

I've got the following problem: I need to download a JSON file from an API via JQuery / JavaScript. In theory this should be quite basic.
I tried $.ajax and all of its siblings like $.get or $.getJSON. I alway get an 200 OK but my Firebug reports an error. Printing the error just says: "error" - so not that helful.
I read that maybe the JSON file is corrupt. So I tried it with a plain text file (*.txt). Same result.
The JSON file is valid, I check it against a validator.
I also tried ContentType and dateType and experimented with json and jsonp...
I basically used something like this (with a million variations for testing purposes):
$.ajax({
url: 'http://www.myurl.com/api/v1/myfile.json',
...
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error.statusText);
}
});
Am I missing something important here? It's really odd that nothing seems to change the behavior of the AJAX-call.
In fact I don't really need AJAX because I need to grab the JSON file when loading the page...
And the JSON file is not on the same domain as the AJAX caller.
Is that URL located on the same server you're trying to get the data from?
If not, you ran into a cross-domain request, which can only be handled using JSONP. So, the JSON file itself must be compatible with JSONP format, otherwise jQuery won't be able to process it (even if you provide a 'jsonp' dataType).
P.S.: Firebug will always show response code 200 but give an empty response body for such requests
Try in this way by disabling security
$.ajax( {
type : 'GET',
contentType : "application/json; charset=utf-8",
url : surl, \\specify your url
async : false,
dataType : 'json',
headers : {
Accept : "application/json",
"Access-Control-Allow-Origin" : "*"
},
crossDomain : true,
success : SucceedFunc,
error : function(data, textStatus, errorThrown) {
console.log("error" + ' ' + JSON.stringify(data) + ' ' + textStatus + ' ' + errorThrown);
}
});
function SucceedFunc(data) {
alert("success");
}
}
Did you try to catch the error the correct way?
$.ajax({
url: 'http://www.myurl.com/api/v1/myfile.json',
success: function(data) {
console.log(data);
},
error: function(error) {
console.log(error.message);
}
});
If you are using chrome go to cmd prompt and run the chrome by disabling the security. You can disable security using pathwhere_chrome_is_located\chrome.exe --disable-web-security
and run the html page. I think this may help you.

how to get error message of failed ajax

I want to consume a webService which I get JSON Data from
$.ajax({
type: 'GET',
contentType: 'application/json',
dataType: 'JSON-P',
//the url shows the correct JSON Data when I copy the URL in my browser
url: 'http://url.com',
success: function(data){
console.log(data);
alert(data);
},
error: function(xhr, testStatus, error){console.log("Error occured: "+error+" "+xhr+" "+testStatus)}
})
In Firefox, It calls back with the error function, but I dont know what the problem is, it would be great to know the error message but my approach doesnt work.
thanks in advance
edit: In Chrome I get the following error:
Origin null is not allowed by Access-Control-Allow-Origin.
edit: It´s solved, the problem was indeed that json doesnt work cross site, and the data was not "jsonp-conform" (it had to set a function(json data...))arround the json data. This could be done by changing the url at the end "_&jsonp=successCallback. Sorry for bothering you
I think there was a JSON object syntax error. Check your JSON object syntax error with jsonlint.com.
Are you getting this error locally?
Try it on a server and if it doesn't work: XmlHttpRequest error: Origin null is not allowed by Access-Control-Allow-Origin

Categories

Resources