jQuery cross domain request still failing in IE, but using jsonp - javascript

My Ajax cross domain request is failing in IE 9 with "Access denied". I have read through several posts regarding this topic, and AFAIK it should work.
IE9 and jQuery 1.8.1
Call is async, jsonp and crossdomain, cache is false. These are the prerequisites I have found.
Works in latest Firefox and Chrome.
jQuery.support.cors is true
Even the response header is set: Access-Control-Allow-Origin:* (SO)
The returned JSON code would also be correct, have used a checker (also see 3.)
So why is this failing with Access denied? Any idea? Could it be because my code is called from within a "JavaScript" library, and not a <script></script> tag on the page?
What am I missing?
// The code is part of an object's method (prototype)
// code resides in a library "Mylib.js"
$.ajax({
type: 'GET',
url: url,
cache: false,
async: true,
crossdomain: true, // typo, crossDomain, see my answer below
datatype: "jsonp", // dataType
success: function (data, status) {
if (status == "success" && !Object.isNullOrUndefined(data)) { ... }
},
error: function (xhr, textStatus, errorThrown) {
// access denied
}
});
-- Edit -- based on Robotsushi's comments, some further research ---
Indeed, cannot find XDomainRequest in the jQuery source code (1.8.1)
If I do not set cors (jQuery.support.cors = true) I'll end up with a "No Transport" exception.
Still wondering why others obviously succeed with IE9 cross domain requests, e.g. here: jQuery Cross-Domain Ajax JSONP Calls Failing Randomly For Unknown Reasons In Some IE Versions
The way jQuery handles this, seems to be around the code below, but this is not called in my particular case, no idea why?
// Bind script tag hack transport
jQuery.ajaxTransport( "script", function(s) {
// This transport only deals with cross domain requests
if ( s.crossDomain ) {
A similar situation here in year 2010: Jquery $.ajax fails in IE on cross domain calls However, this should have been solved by the later jQuery versions.

Ok, working now. Couple of mistakes on my side:
It is crossDomain: true, dataType: "jsonp" , typo - missed capital letters.
JSONP requests are not transparent. The data are not simply JSON notation, but have to be wrapped in a Js function call (on the server side): see http://en.wikipedia.org/wiki/JSONP Basically this means, if you cannot modify the sent data, JSONP is not the right option for you.
All things considered, it works. So my personal checklist would be:
Use json if possible (e.g. with Chrome, FF, or most likely IE10). Make sure response header is set: Access-Control-Allow-Origin:*
If using jsonp, check: async: true, jsonp and crossdomain: true, cache is false, jQuery.support.cors is true These are the prerequisites I have found.
Also make sure the jsonp response is a function call (JSON wrapped in function), not "just ordinary" JSON data.

I've had a similar issue trying to access some json that I'm storing on Google Cloud Storage and accessing using jQuery's ajaxing. This worked fine in Chrome and Firefox, but I was getting 'access denied' messages when testing in IE (9 and below).
The way I got around it was to use jsonP, explicitly:
re-write my json file to be a javascript file with a javascript variable to hold the json data, e.g.
(function (o) {
variableName = [json];
}(window.[nameSpace] = window.[nameSpace]|| {}));
include the url to the javascript file within the tag of the html file, e.g.
<script type="application/javascript" src="[url to javascript file]"></script>
Consume the data via it's variableName
Hope this helps :)

IE requires you to use XDomainRequest instead of XHR for cross site.
You can check out the easyXDM which is a js library that abstracts this process for you.
Alternatively see this :
Access denied to jQuery script on IE

Related

Ajax Callback function's location

I had a problem about callback function which was located in $(document).ready . Callback function didn't used to work. When I put it outside of $(document).ready the code has started to work perfectly. I don't understand why. Is location is important?
This works:
$(document).ready(function() {
$("#button1").click(function() {
$.ajax({
url: "http://www.example.com/data.php",
type: "get",
dataType: "jsonp",
jsonpCallback: "read",
});
});
});
var read = function(data) {
console.log(data);
}
This does not work.
$(document).ready(function() {
$("#button1").click(function() {
$.ajax({
url: "http://www.example.com/data.php",
type: "get",
dataType: "jsonp",
jsonpCallback: "read",
});
});
var read = function(data) {
console.log(data);
}
});
UPDATE1: Sorry guys, links werent't different. I forgot to change 2nd one. There is just one difference that location of read function.
The reason you pass in the JsonP callback name as a string like that is because JQuery needs to add it to your URL like this ?callback=read. A JsonP request is just a <script> tag created by JQuery in the background and added to the page <script src="http://www.csstr.com/data.json?callback=read"></script>. Once JQuery adds that script tag to your page the browser will treat it like it's loading a normal JavaScript document to be exectued. Because of the ?callback=read part of the request, the remote server knows to respond with executable JavaScript and not just the raw data. That executable JavaScript is just a function call to a function with the name you provided, in this case the read function. Because the returned script is being executed in the global scope, the read function also needs to exist in the global scope. The global scope in the browser is the window object, so basically the read function needs to be present on the window object in order for the executed script to find the function.
$(document).ready(function() {
$("#ara-button").click(function() {
$.ajax({
url: "http://www.csstr.com/data.json",
type: "get",
dataType: "jsonp",
jsonpCallback: "read",
});
});
window.read = function(data) {
console.log(data);
}
});
It works outside of the ready function in your first example because anything defined at the root level like that is globally scoped.
Codpen Demo: http://codepen.io/anon/pen/qNbRQw
If you want to know more about how JsonP works, read on.
If you're still confused it's probably because you're not 100% familiar with how JsonP actually works. JsonP is a hack to get around the Same-origin Policy. The short version of the Same-origin Policy is that the browser won't let you read the response returned from requests to domains other than the one the request originated from unless the server on that other domain says it's okay.
The Same-origin Policy was implemented by most browsers to help protect users from malicious scripts. For example, if you authenticated with your bank website in one browser tab and then went to a nefarious website in another tab, without same-origin restrictions in the browser that nefarious site could make an ajax request to your bank website. That request would carry any cookies your browser has stored for that domain and your cookies would show you as authenticated, thus giving the attacking script access to authenticated data from your bank account. The Same-origin Policy prevents the nefarious site from being able to see the response data from that request.
In the beginning there was no official way for the client and server to opt-in to cross-domain sharing. It was just straight up blocked by the browsers at the time. To get around this JsonP was invented. The Same-origin Policy only hides the response from ajax requests, but as you may have noticed the browser is totally fine with loading scripts from other websites via <script> tags. The script tag just does a plain old GET request for a javascript document, then starts executing that script on your page. JsonP takes advantage of the fact that same-origin restrictions don't apply to <script> tags.
Notice if you go directly to http://www.csstr.com/data.json in your browser you'll see the data you're after. However, try going there with the following query string added.
http://www.csstr.com/data.json?callback=read
Notice anything different? Instead of just returning the data you want the response comes back with your data being passed into a function named read. This is how you know the server understands the JsonP hack. It knows to wrap the data you want in a function call so that JQuery can perform the JsonP hack on the client, which it does by creating a <script> tag and embedding it in your web page. That script tag points to the URL but also adds that querystring to the end of it. The result is a script tag that loads a script from that URL and executes it. That script is being loaded into your page's global scope, so when the read function is called it expects that function to also exist in the global scope.
Today, the official way around the Same-origin Policy is via the Cross-origin Resource Sharing policy (aka CORS). JsonP essentially accomplishes the same thing that a proper CORS request does. The server has to opt-in by knowing how to format the response as executable JavaScript, and the client has to know not to do a normal ajax request but instead dynamically create a script tag and embed it in the page body. However, JsonP is still a hack and as hacks do it comes with its own set of downsides. JsonP is really hard to debug because handling errors is almost impossible. There's no easy way to catch errors if the request fails because the request is being made via a <script> tag. The <script> tag also lacks control over the format of the request being made; it can only make plain GET requests. The biggest downside to JsonP is the need to create a global function to be used as a callback for the data. Nobody likes polluting the global namespace but for JsonP to work it's required.
Proper CORS requests don't require extra effort on the client's part. The browser knows how to ask the server if it is allowed to read the data. The server just has to respond with the right CORS headers saying its okay and then the browser will lift the same-origin restrictions and allow you to use ajax as normal with that domain. But sometimes the resource you're trying to hit only knows JsonP and does not return proper CORS headers so you have to fallback on it.
For more info about CORS I wrote a pretty detailed blog post a little while ago that should really help you understand it. If you control the server that is returning the data you're after then you should consider just having it return the proper CORS headers and forget about JsonP. But it's totally understandable when you don't control the server and can't configure it to return the proper headers. Sometimes JsonP is the only way to get what you need, even if it does make you throw up in your mouth a little bit as you write the code.
Hope that helps clear some things up for you :)
$(document).ready(function() { means : Do it when the page finished to load.
In the second example, you are defining the read function only after the page finished to load.
In the working example, you are defining the read function first and say, "Once the page will be loaded, do the ajax call and then, call read function"
Edit : Also, you can read #IGeoorge answer for a more detailed explaination.
Add read method before ajax
$(document).ready(function() {
var read = function(data) {
console.log(data);
}
$("#ara-button").click(function() {
$.ajax({
url: "http://www.csstr.com/data.json",
type: "get",
dataType: "jsonp",
jsonpCallback: "read",
});
});
});
Your function is defined into Jquery Scope, so at the moment the ajax is executed, cannot find definition of "read" function.
That's why the first example works.
Hope this helps.

Failing to get remote JSON using JSONP

I'm trying to retrieve a remote JSON using jQuery 1.11.1. The remote server does support jsonp and I'm able to download the .jsonp file by simply entering the call address and ?callback=foo in a browser.
However, when I try to get it using ajax, it fails.
$.ajax({
type: "GET",
url: "http://path-to-remote-server.net/file.jsonp",
dataType: 'jsonp',
jsonp : "callback",
jsonpCallback: "e",
success: function(r) {
console.log(r);
}
});
A quick look at the console tells me that it's a bad request, probably because it seems that jQuery passes a second unwanted parameter, making the request look like this :
http://path-to-remote-server.net/file.jsonp?callback=e&_=1406722474006
This happens even when I omit the jsonp and jsonpCallback options. The request then looks like this :
http://path-to-remote-server.net/file.jsonp?callback=jQuery111106199050471186638_1406722685544&_=1406722685545
Using the short cut $.getJSON doesn't work either, but not for the same reason it seems :
$.getJSON("http://path-to-remote-server.net/file.jsonp?callback=e", function(r){
console.log(r);
});
This doesn't trigger any error in the console, but nothing gets logged either, as if it didn't get anything back from the server.
Why is that, and how can I avoid it?
Thank you all in advance!
From the manual:
cache (default: true, false for dataType 'script' and 'jsonp')
Type: Boolean
If set to false, it will force requested pages not to be cached by the browser. Note: Setting cache to false will only work correctly with HEAD and GET requests. It works by appending "_={timestamp}" to the GET parameters. The parameter is not needed for other types of requests, except in IE8 when a POST is made to a URL that has already been requested by a GET.
So add cache: true to your Ajax parameters.
The last query string argument automatically added by jQuery is needed to avoid browser caching. Otherwise if you do the same JSONP call in the same or in any other page of your site, you will get the cached result instead of the fresh one. So if your server does support JSONP it should accept such requests.
It seems to be a server-side issue, so you should check what is going on there :)

jQuery .ajax getting Access Denied on Cross Domain Request in IE8/9

I am using jQuery's .ajax to pull in content from other pages into a modal window. The majority of these pages are on the same domain and work correctly across all browsers.
There is one link that goes to another domain. That link works correctly in Chrome, Firefox, and Safari but gives an Access Denied error in Internet Explorer 8 and 9.
I searched quite a bit for a solution and tried several things that have not helped so far including:
I confirmed Access-Control-Allow-Origin was set to allow my domain. I tried setting it to "*" as well just to confirm that wasn't the issue.
I tried using different jQuery methods to make the AJAX call. I used jQuery's load, get, and ajax methods. jQuery's ajax method gave me the Access Denied error.
I tried using Internet Explorer's XDomainRequests. XDomainRequests told me there was an error but gave me no more information. I tried several changes to this code I found suggestions for like setting a timeout on the send function but no change.
I set jQuery.support.cors = true; and added crossDomain: true to my .ajax call.
I found someone who suggested that jQuery version 1.8.0 caused the issue which happens to be the version that is used on the website I am working on. The suggestion they had was to step back to version 1.7.2 which did not fix the issue. I also tried changing to version 1.11.0 but that also did not make a difference.
I saw a suggestion that adding &callback=? to the end of the url would solve it but that didn't make a difference.
I am probably forgetting something that I tried today but that should be most of it.
Here is the code I have at the moment:
jQuery.support.cors = true;
var request = $.ajax(
{
crossDomain: true,
type: "GET",
url: url,
success: function () {
console.log('success');
},
error: function (a, status, error) {
console.log('error: ' + error);
},
complete: function () {
console.log('complete');
}
});
Chrome, Firefox, and Safari log 'success' and 'complete' in the console. IE8/9 log 'error: Error: Access is denied.' and 'complete' in the console.
I ran into similar problem the other day. This is what I tried and it worked like a charm
I had the attribute dataType set to jsonp (i.e. dataType: 'jsonp') this will work for GET but not for POST
If the above still doesn't work then you can reference below script from MoonScript and it hooks the support up automatically
https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
I used this to make internet explorer work for me on cross domain ajax calls. I'd be happy to list my solution here as well, but I think that the link below probably explains in detail enough from a more intelligent user than me.
Jquery $.ajax fails in IE on cross domain calls

Ajax call on phonegap not sending request

I am pulling my hair out on this one.
I have a jquery ajax call to my server that works on my browser, it works on my device when I have it connected to my local proxy for http sniffing, but just hangs when it's off my proxy on the wifi or on the cell network.
I've set up the phonegap config.xml to allow my domain. The request is a get on the server as well as the ajax call. You'll notice it's jsonP.
The call is straight forward jquery, I'll post the code anyway. The api object is a custom object I made to hold the application's functionality.
var dfd = $.ajax({
url: myurl, // I've confirmed the url, but prefer to keep it private
data: {
ApplicationID: api.applicationID,
DeviceID: api.device.uuid(),
OSVersion: api.device.version(),
DeviceVersion: api.device.platform(),
Lat: lat,
Lng: lng,
Bearing: bearing
},
dataType: "jsonp",
timeout: 30000
})
.fail(function (event, jqXHR, ajaxSettings, thrownError) {
console.error(jqXHR);
});
I've tried this answer, the closest I could find to my problem, but it doesn't seem to work.
Phonegap jQuery ajax request does not work
Is there something I'm missing? What am I doing wrong?
EDIT:
I forgot to mention, the timeout I have set on the ajax call does nothing, it just seems to ignore it.
Since you pull a json string, why not use
$.getJSON("http://www.example.com?jsoncallback=?",
function(data){ ... }
Note the jsoncallback. What happens here is that jquery parses an extra parameter to the code to verify the result is from the actual request. This happens on cross-domain requests.
To make your 'json-builder' compatible, simple place the jsoncallback in front of the request:
$return = $_GET["jsoncallback"].'({"title" : "test", "author" : "someone"});
Your problem may not be, as you mentioned, cross domain. Does your server logs any requests? I have similar problem with second (the same) request after linking it from index.html, first request works fine. I found an information that it may be a phonegap bug.
It turns out my problem was entirely different. My dependencies were not loading because of how the mobile browsers add AMD scripts. I've fixed this by consolidating all scripts into a single file and it's worked ever since.

Jquery ajax() cross domain remote server does not work in IE8 [duplicate]

This question already has answers here:
$.ajax call working fine in IE8 and Doesn't work in firefox and chrome browsers
(3 answers)
Closed 4 years ago.
I have a script that makes an ajax request to a remote server, that returns a plain text response. It works fine in all browsers except IE8 (shocker).
Here's the code:
$.ajax({
url: 'abc.com/?somerequest=somevalue',
cache: false,
type: 'POST',
data:{
sub: 'uploadprogress',
uploadid: this.uploadId
},
dataType: 'html',
success: this.uploadProgressResp,
error: this.errorResp
});
In IE8, it returns a "No Transport" error. I suppose it's because IE8 doesn't allow cross domain requests?
NOTE: I didn't write the API for the remote server. If I did, I would return JSON response rather than a plain text response. So yes, the dataType is supposed to be HTML rather than JSON.
Try adding this somewhere before the ajax call - Best place for it is before any other JavaScript executes!
jQuery.support.cors = true;
Without this, the "No transport" error will be thrown by Internet Explorer. The error message itself is rather confusing, but by default cross-domain ajax requests are blocked by IE, but do not appear to be so by other browsers - or at least, Chrome and Firefox will function to that effect.
I shared your pain on this one, historically. Quite confident that it will sort your issue.
I know this is very old question, but sadly people still using IE8/9 and sometimes we have to support them :/
This is best solution I was able to find for this issue:
https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
Just include following script in your html and that's it, you don't have to modify anything in your jQuery request
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.3/jquery.xdomainrequest.min.js"></script>
Limitations:
IE6/7 isn't supported, only IE8 and IE9
Minimum jQuery version is 1.5
When using POST method in IE8/9, Content-Type header always will be
set to text/plain
Current website and requested URL both must be using same protocol (HTTP->HTTPS or HTTPS->HTTP requests will not work)

Categories

Resources