Callback not getting called on Internet Explorer for Ajax JSONP call - jsonp

I'm making an Ajax call using JSONP to fetch JSON data from a third-party (domain different from my site) and its working on Chrome and Firefox but failing on IE (9 & 10 are the versions I have tried). In the IE debugger I see the call is completing (with Http 200) but the callback I've specified for the JSONP call is not being invoked.
My code looks like this:
$.ajax({
url: 'http://api.yipit.com/v1/deals/?key=mykey&division=seattle&limit=1000',
dataType: 'jsonp',
contentType: "text/javascript",
async: false,
cache: false,
crossDomain: true,
jsonp: 'callback',
jsonpCallback: 'processResult',
error: function (xhr, textStatus, error) {
window.alert(error);
},
success: function (data) {
window.alert(JSON.stringify(data));
_yipit_deals = data.response.deals;
}
});
And the response body looks like this:
<html><body><pre>processResult({
... [valid JSON data]
});</pre></body></html>
When the call is made, the error function is getting invoked with error as: Error: processResult was not called and the IE debugger shows a script error caused when trying to parse the <html><body><pre> tags in the response. When running on Chrome and Firefox these html tags don't exist in the response body and I'm not sure why the response is different in the case of IE.
It appears that these tags are causing IE to barf and not be able to invoke the callback. I've tried specifying other values for contentType such as "text/html", "text", "application/javascript" and even not specifying it at all, but its not made any difference. I'm using JSONP to get around the cross-domain issue.
Any ideas? Thanks!

You have to pass an explicit format argument to the URL:
&format=json
Otherwise, it's just pretty-printing the output:
<html><body><pre>{
"meta": {
"code": 401,
"message": "Key not recognized",
"name": "AuthenticationFailed"
},
"response": {}
}</pre></body></html>
Also, I would set async back to true.

Related

Callback response in Jest is different than normal response

I have a method that calls an endpoint in React Native and I want to test it with jest. Everything is asynchronous and it works but the callback response when the function is called in testing side is totally different than the response when the function is called normally in application.
Normally, my response will be a JSON like this:
"_bodyBlob":{
"_data":{
"__collector":[
"Object"
],
"blobId":"43564E12-D797-4971-80C7-A6E06D690F8A",
"name":"login",
"offset":0,
"size":784,
"type":"application/json"
}
},
"_bodyInit":{
"_data":{
"__collector":[
"Object"
],
"blobId":"43564E12-D797-4971-80C7-A6E06D690F8A",
"name":"login",
"offset":0,
"size":784,
"type":"application/json"
}
},
"bodyUsed":false,
"headers":{
"map":{
//a lot of private data here and others
}
},
"ok":true,
"status":200,
"statusText":"",
"type":"default",
"url":"private url"
}
But the response that is returned when called the method by Jest is like this:
Response {
size: 0,
timeout: 0,
[Symbol(Body internals)]: { body: <Buffer >, disturbed: false, error: null },
[Symbol(Response internals)]: {
url: undefined,
status: 200,
statusText: 'OK',
headers: Headers { [Symbol(map)]: [Object: null prototype] },
counter: undefined
}
}
Which is not even a JSON.
Is this a normal response for a callback when the method is called by Jest or could be something wrong while I call the function because it's all asynchronous?
Thank you for your time.
It seems in your Jest test the response is the javascript Response object: https://developer.mozilla.org/en-US/docs/Web/API/Response
In order to get the JSON out of it, you need to apply its json() method like in this example: https://developer.mozilla.org/en-US/docs/Web/API/Response#an_ajax_call
So once you get the response object, do this:
const jsonValue = await response.json();
The reason why the value is different in jest and in your actual application could be that in your actual application, the library handling the response probably calls the json object before passing you the response.

Crossdomain jQuery ajax request was not called and give error status "parsererror"

I am trying to call cross domain url. which has response text as below.and it is valid json response.
[{"LANG_CODE":"UK_EN","COU_ISO_CODE":"BGR"},
{"LANG_CODE":"UK_EN","COU_ISO_CODE":"HUN"},
{"LANG_CODE":"UK_EN","COU_ISO_CODE":"PRT"},
{"LANG_CODE":"UK_EN","COU_ISO_CODE":"UGA"}]
Jquery ajax code which i am using for calling cross.
$.ajax({
url: "http://someDomainName/restfulservice/Api/Countries/Get_Json",
dataType: 'jsonp',
crossDomain: true,
async: false,
success: function (data) {
alert("success >> "+data);
},
error: function (jqXHR, textStatus, errorThrown) {
alert("error : "+errorThrown + ", textStatus >> "+textStatus);
}
});
every time it goes to error block. when i inspect this service in browser then it gives response text with valid json string.but through code i am getting error "jQuery18305917718204907095_1409810925309 was not called, status: parsererror".
while this code is working for the url "http://api.geonames.org/findNearbyPlaceNameJSON?lat=47.3&lng=9&username=demo".
what could be the issue for same ?
It is sending back JSON but you have said dataType: 'jsonp'. JSON is not JSONP.
Either change the service to support JSONP or change the client to expect JSON (which might require you to find some other way to circumvent the same origin policy)

Googlemaps Api v3 getJson not working in IE

I have the following problem: I am trying to get data from the googlemaps api v3 via ajax with the code below. It works fine in Chrome and Firefox, but not in IE. What am I doing wrong?
var lat;
$.ajax({
url: "url",
cache: false,
dataType: "json",
success: function(data) {
lat = data.results[0].geometry.location.lat;
}
});
Add the following error event to your Ajax call
success: function(data) {
lat = data.results[0].geometry.location.lat;
},
error: function(xhr, status, error) {
alert(status);
}
And let us know what error message you get in IE, if any at all.
EDIT - Sounds like you are trying to do a cross-domain request?
If that is the case, try setting $.support.cors = true; before your ajax request.
Fetched from http://api.jquery.com/jQuery.support/
To enable cross-domain requests in environments that do not support cors yet but
do allow cross-domain XHR requests (windows gadget, etc), set
$.support.cors = true;
EDIT2 - Ill assume you are running IE9, in that case you need a plugin for jQuery found here:
https://github.com/jaubourg/ajaxHooks/blob/master/src/xdr.js
Also see this answer on SO for more details on why a plugin is needed for IE9 (with cors): IE9 jQuery AJAX with CORS returns "Access is denied"
EDIT3 - Download jQuery.XDomainRequest.js and include it before your AJAX call.

WCF Rest Service Call

I am calling a rest service in ajax.
If I add the svc file in the same project and call I am able to call the url
The below is the URL working
http://localhost:1947/GreenViewService.svc/?callback
If I add the svc in separate project layer and call in ajax I am unable to call it says 403 forbidden error and sometimes 405 error.
If I call the below url from different layer not working is it because port no. varies. should I give any access rights.
function GetDataPoints() {
alert('S');
var action = 'http://localhost:1984/GreenViewService.svc/?callback=';
alert(action);
$.ajax({
"type": "GET",
"url": action,
"cache": false,
"contentType": "application/json; charset=utf-8",
dataType: "text",
"success": function(result) {
alert(eval(result));
var json = eval(result);
//fillDropDown(json, prefix + 'DataPoint', 'NodeLabel', 'ID');
}
});
}
As you say it works when in the same project but not in a different project.
The difference is that when it is in a different project it is a cross site call.
To do a cross site call you need to use JSONP

Why doesn't dojo.io.script.get() execute the provided error function when receiving a 404?

I am trying to use the following to do a cross-domain get:
dojo.io.script.get({
url: myUrl,
callbackParamName: "callback",
preventCache: true,
load: dojo.hitch( this, loadFunction ),
error: dojo.hitch( this, function() {
console.log('Error!!!');
})
});
The load function runs fine, however, when the server returns a 404, the error function does not run. Can anyone tell me why?
EDIT
After some investigation, I found that a timeout and handler could be implemented in the following way:
dojo.io.script.get({
url: myUrl,
callbackParamName: "callback",
timeout: 2000
}).then(function(data){
console.log(data);
}, function(error){
alert(error);
});
This uses functionality provided by the dojo.Deferred object.
When accessing server with script tags (that what dojo.io.script.get does), status code and headers are not available.
You may try some other ways to detect a problem, like using a timeout and analyzing a content of a script. The latter is problematic for JSONP calls (like in your example).
I realize this is old but I thought I'd share a solution in case others, like I had, come across this thread.
dojo.io.script is essentially adding a <script/> to your html page. So you can try this:
var script = document.createElement('script');
script.setAttribute('type', 'text/javascript');
script.setAttribute('src', myUrl);
script.onerror = function() {
debugger
}
script.onload = function() {
debugger
}
document.getElementsByTagName('body')[0].appendChild(script);
That way if the script fails to load the onerror event is called.
*This may not work in every instance but is a good start