Ajax request "Access is denied" in IE - javascript

I use ajax request in order to check response of websites as follow,
$.ajax ({
url: 'https://www.example.com',
cache: false,
success : function() {
alert(new Date() - start)
},
})
It works on my local pc in all browsers. When I put it on the server, it works in Chrome and Firefox but not in IE8.
I get the error: "Access is denied" jquery.min.js
Why am I getting this error?

For my case the problem is resulted because of compatibility mode. I am in intranet and internet explorer is running with compatibility mode.
I added following tag and this solved all my problems. It forces IE to not use compatibility mode.
<meta http-equiv="X-UA-Compatible" content="IE=Edge" >

--- JAN 2014 ---
IE8 and IE9 use a different method (XDomainRequest) to communicate with cross domains.
You should consider using this if they are using jQuery:
https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
Make sure to use the same protocol as the originating call, i.e. HTTP or HTTPS.

Quoting "epascarello" from an other very similar question :
Making a call to a sub domain is seen as a different domain because of the Same Origin policy. Make sure that you are setting document.domain to avoid access denied with the Same Origin policy.
To get the document.domain in sync you need to set it in two places. Add a script tag that set the domain, and you need to have an iframe on the page that sets the same thing on the other domain.
The page that the Ajax call is made from "www.example.com" and is calling "ajax.example.com":
<script type="text/javascript">
document.domain = "example.com";
</script>
<iframe src="http://ajax.example.com/domainCode.html"></iframe>
The "domainCode.html" would just contain the script tag
<html>
<head>
<script type="text/javascript">
document.domain = "example.com";
</script>
</head>
<body>
</body>
</html>
With that in place you should be able to talk between your sub domains.
Hope that helps !

Note -- Note
do not use "http://www.domain.xxx" for URL in ajax.
only use path(directory) and page name without address.
false state:
var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;
AJAXobj.open('POST', 'http://www.example.com/dir/getSecurityCode.php', true);
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
AJAXobj.send(pack);
true state:
var AJAXobj = createAjax();
AJAXobj.onreadystatechange = handlesAJAXcheck;
AJAXobj.open('POST', 'dir/getSecurityCode.php', true); // <<--- note
AJAXobj.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded; charset=UTF-8');
AJAXobj.send(pack);

I had this problem in IE8. What solved it for me was changing my ajax request to use the same protocol as the original page request. In my case the original page was requested over https and the ajax request was using http. Switching them both to use https fixed the problem.

Related

Cookies not working when page accessed via file://

My code works in firefox and when i visit w3schools using chrome to test my code in their editor it works fine too but when i launch my code in chrome from notepad++ it doesn't work.It seems that body onload is not working because i don't get the alert.My chrome is up to date.Help would be appreciated.
<!DOCTYPE html>
<html>
<head>
<script>
function setCookie(cname,cvalue,exdays){
var d=new Date();
d.setTime(d.getTime()+(exdays*24*60*60*1000));
var expires="expires="+d.toUTCString();
document.cookie=cname +"="+cvalue+"; "+expires;
}
function f(){
var user=prompt("What is your name?","");
if(user!="" && user!=null){
setCookie("username",user,30);}
}
function getC(cname){
var name=cname+"=";
var ca=document.cookie.split(";");
for(var i=0;i<ca.length;i++){
var c=ca[i];
while(c.charAt(0)==" ")c=c.substring(1);
if(c.indexOf(name)==0) return c.substring(name.length,c.length);
}
return "";
}
function checkcooki(){
var user=getC("username");
if(user!=""){
alert("Welcome back "+user);
}
}
</script>
</head>
<body onLoad="checkcooki()">
<input type="button" onclick="f()" value="klick">
</body>
</html>
For a fact: Using the file:// protocol does NOT guarantee the proper workings with cookies. Since cookies need 3 things:
A name-value pair containing the actual data
An expiry date after which it is no longer valid
The domain and path of the server it should be sent to
The domain tells the browser to which domain the cookie should be sent. If you don't specify it, it becomes the domain of the page that sets the cookie.
On a file:// protocol you don't have a domain.
Now some browsers might have found work-arounds for this, like FireFox and IE. You can test your code on these browsers but they will not use cookies in the same way as on a webserver.
Proper x-browser testing in your case requires the http:// protocol.
I suggest you start a jsfiddle or setup a webserver(IIS, apache).
Proper read on cookies: quircksmode
If you are still persistent to get it working on chrome through the file:// protocol you might have a small chance if you get the path correctly.
path: properly escaped path => encodeURIComponent(document.domain) or "c:\/my%20folder\/index.html" (along these lines but again, very untrustworthy information here)
domain: "/" (no idea what else you can try here)
Your user variable must be a blank string.
Put an alert at the very top of your checkcooki() function to verify that body onload works.

Issue using jQuery to do a google maps api call (JSON not being returned)

This is the code I was originally using and worked perfectly fine up until yesterday (which is when I noticed it but I am unsure when it actually stopped working for sure). I know this was working at the beginning of last week so sometime between then and yesterday it broke. I am running this code within a RAD called Alpha Anywhere but have tested it outside of this program (in just a HTML page) and it still didn't work. Hoping someone knows if there is a bug or if there is something I can do to fix this issue. I ran this in firefox with firebug on and that is where I saw the error letting me know that the JSON wasn't retrieved.
var $jq = jQuery.noConflict();
$jq.getJSON('http://maps.googleapis.com/maps/api/directions/json?origin=Toronto&destination=Montreal&sensor=false',function(results){
// I have code in here to calculate miles driven per state
// (as in the above code origin and destination would be filled
// with variables but I went with this basic call because even this doesn't work).
});
This following code does not work (as of right now November 11, 2013 at 10:26 PM CDT) when running it in firefox or chrome. With firebug on it shows I am not getting a response from google. However this following code does respond when ran in safari 7.0.x on Mac OSX 10.9.
<!DOCTYPE html>
<html>
<head>
<script src="http://api.jquery.com/jquery-wp-content/themes/jquery/js/jquery-1.9.1.min.js"></script>
<script>
function getData() {
var url = 'http://maps.googleapis.com/maps/api/directions/json?origin=Huntsville,AL&destination=Atalanta,GA&sensor=false';
var $jq = jQuery.noConflict();
$jq.getJSON(url, function (results) {
alert(results.routes[0].legs[0].distance.value);
});
}
</script>
<title>jQuery Debug of Google API</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<button onclick="getData();">click</button>
</body>
</html>
There are a couple problems here:
First, from jsonp explained:
As you may be aware you cannot directly load data files from another domain. This is a security issue that has been around for a long time and is commonly solved by sharing data through an API, REST or such. However there are ways around this ... [for example] JSONP
To do this in jQuery:
Using $.ajax, add dataType: 'jsonp', which appends callback=? to the URL
Using $.getJSON (shorthand for .ajax), add callback=? at the end of the requested URL.
That indicates that we want to use JSONP. Remove it and a vanilla JSON request will be used; which will fail due to the same origin policy.
Another issue is that some external APIs (like Google Maps Directions API), don't automatically serve JSONP. If the server doesn't know what to do with the callback parameter then the response from the API will still be JSON, not JSONP. In order to ensure the returned content is formatted correctly, you can go through a proxy server like the jsonp.guffa.com
To use it, change the request to http://jsonp.guffa.com/Proxy.ashx?url=YourEncodedURI
Where you have replaced YourEncodedURI with the encoded requested url string.
Putting it all together:
var mapsUrl = 'http://maps.googleapis.com/maps/api/directions/json' +
'?origin=Toronto&destination=Montreal&sensor=false';
var encodedUrl = encodeURIComponent(mapsUrl);
var proxyUrl = 'http://jsonp.guffa.com/Proxy.ashx?url=' + encodedUrl;
$.ajax({
url: proxyUrl,
dataType: 'jsonp',
cache: false,
success: function (data) {
console.log(data);
}
});
Working Demo in jsFiddle
Further Reading:
What is JSONP all about?

Programmatically accessing an iframe that uses a data URI as a source

I'm creating an iframe programmatically using the "data" URI:
<iframe id="myFrame" src='data:text/html;charset=utf-8,<!DOCTYPE html><html><head></head><body><h1>Hello.</h1></body></html>'></iframe>​
This frame loads fine, but it seems that working with the iframe programmatically hits cross-domain security checks.
var iframeDoc = document.getElementById('myFrame').contentWindow.document;
$(iframeDoc.body).find('h1').text('Changed');
Throws an error in Chrome and Safari:
Unsafe JavaScript attempt to access frame with URL
data:text/html;charset=utf-8,... from frame with URL http://... The
frame requesting access has a protocol of 'http', the frame being
accessed has a protocol of ''. Protocols must match.
Here's a fiddle showing the security error: http://jsfiddle.net/bhGcw/4/
Firefox and Opera do not throw this exception and allow the iframe contents to be changed. Seems like Webkit sees a blank protocol for data URIs, and sees this as a cross-domain violation.
Is there any way around this?
It's a bit late, how about instead of using a data URL, you use the HTML5 attribute srcdoc.
<iframe id="iframe" srcdoc='<html><body><h1>Hello!</h1></body></html>'></iframe>
<script type="text/javascript">
$(function(){
$($("iframe")[0].contentWindow.document).find("h1").text("Modified from the parent window!");
});
</script>
There's an example at http://jsfiddle.net/ff3bF/
It appears that Webkit does a simple string comparison in their domain checking code:
String DOMWindow::crossDomainAccessErrorMessage(DOMWindow* activeWindow)
{
...
SecurityOrigin* activeOrigin = activeWindow->document()->securityOrigin();
SecurityOrigin* targetOrigin = document()->securityOrigin();
if (targetOrigin->protocol() != activeOrigin->protocol())
return message + " The frame requesting access has a protocol of '" + activeOrigin->protocol() + "', the frame being accessed has a protocol of '" + targetOrigin->protocol() + "'. Protocols must match.\n";
...
}
It looks like Chromium is being more strict than the HTML5 spec, at least according the following bug reports:
https://bugs.webkit.org/show_bug.cgi?id=17352
https://code.google.com/p/chromium/issues/detail?id=58999
Chromium devs don't seem to be in favor of relaxing this rule. Bummer.
The answer put forward by #jamie works well for loading HTML into an iframe and allowing subsequent programatic interaction with the content document.
XHTML is not so easy.
The srcdoc attribute appears to be limited to HTML, not XHTML.
A work around is to use a Blob URL which allows the content-type to be specified.
var documentSource = '<?xml version="1.0" encoding="UTF-8"?>\n<html xmlns="http://www.w3.org/1999/xhtml">\n<head>...';
var blob = new Blob([documentSource], { type: "application/xhtml+xml" });
iframe.src = URL.createObjectURL(blob);
This technique works for at least Chrome, Firefox and Safari.

Javascript check file size

Is it possible to keep checking with javascript if the filesize of a file on a webserver (e.g. http://www.mysite.com/myfile.js) is larger than 0 bytes and if so return a true or false value?
Thanks in advance!
Theoretically, you could use XHR to issue a HTTP HEAD request and check the Content-Length in the response headers.
A HEAD request is identical to a regular GET request except the server MUST NOT return the actual content. In other words, the server replies with the headers it would have had you tried to GET the resource, but then stops and does not send the file.
However, some severs respond to a HEAD request with a Content-Length header of 0, regardless of the actual size of the file. Others respond with the size of the file.
In order to accomplish this, you'll have to pray your server returns a file's actual size to a HEAD request.
If it does, getting that value is easy:
$.ajax('/myfile.js', {
type: 'HEAD',
success: function(d,r,xhr) {
fileSize = xhr.getResponseHeader('Content-Length');
}
});
Note that JSFiddle's server always returns 0 when we HEAD /, even though / is 16916 bytes.
Also note what jQuery's docs say about the HTTP request type option:
The type of request to make ("POST" or "GET"), default is "GET". Note: Other HTTP request methods, such as PUT and DELETE, can also be used here, but they are not supported by all browsers.
I just tested this Fiddle in IE 6-10, Firefox 3.6-7, Opera 9-11, and Chrome, and every single browser correctly issued the HEAD request, so I wouldn't worry about that vague incompatibility statement. Of more concern is how your server responds.
Javascript has no access to the filesystem (thankfully) so I'm afraid not.
The idea given by josh3736 is great. Only the code example he gave, refused to work in my browser (Chrome 20, Firefox 13, IE 8, Opera 12), for the reason, that I don't know.
Here is the one, that worked perfectly in my case:
jQuery.ajax
({
cache: false,
type: 'HEAD',
url: 'myfile.js',
success: function(d,r,xhr){alert('File size is ' + xhr.getResponseHeader('Content-Length') + ' bytes.')},
error: function(xhr, desc, er){alert('ERROR: "' + xhr.responseText + '"')}
});
I want also to notice, that Apache on-board XAMPP server works just fine with HEAD request, but of course, when run on localhost, such request is blocked by a browser with error message: "Origin localhost is not allowed by Access-Control-Allow-Origin" (example from Chrome).
IE:
If you set the Ie 'Document Mode' to 'Standards' you can use the simple javascript 'size' method to get the uploaded file's size.
Set the Ie 'Document Mode' to 'Standards':
<meta http-equiv="X-UA-Compatible" content="IE=Edge">
Than, use the 'size' javascript method to get the uploaded file's size:
<script type="text/javascript">
var uploadedFile = document.getElementById('imageUpload');
var fileSize = uploadedFile.files[0].size;
alert(fileSize);
</script>
Other browsers:
On all the other browsers you can use the javascript 'size' method without any problems.

Access denied to jQuery script on IE

I have an iframe using the jQuery 1.4.2 script. The same iframe is injected into both http and https sites. The jQuery script is included in the main HTML file as a relative path (e.g., /scripts/jquery-1.4.2.min.js).
When an AJAX call is made, Internet Explorer denies access. The AJAX is calling on another subdomain, but it's using the right protocol. All other browsers work but Internet Explorer gives the following error:
SCRIPT5: Access is denied.
jquery-1.4.2.min.js, line 127 character 344
I heard this error is from cross-domain AJAX calls. But why is IE the only one giving me crap? Is there an IE solution?
Also, this is my AJAX:
$.ajax({
url: thisURL,
dataType: "json",
data: {cmd : 'getMessage', uurl: urlVar, t: Math.random()},
success: function(ret){
callback(ret)
}
});
IE requires you to use XDomainRequest instead of XHR for cross site, you can try something like...
if ($.browser.msie && window.XDomainRequest) {
// Use Microsoft XDR
var xdr = new XDomainRequest();
xdr.open("get", url);
xdr.onload = function() {
// XDomainRequest doesn't provide responseXml, so if you need it:
var dom = new ActiveXObject("Microsoft.XMLDOM");
dom.async = false;
dom.loadXML(xdr.responseText);
};
xdr.send();
} else {
// your ajax request here
$$.ajax({
url: thisURL,
dataType: "json",
data: {cmd : 'getMessage', uurl: urlVar, t: Math.random()},
success: function(ret){
callback(ret)
}
});
}
Reference
http://forum.jquery.com/topic/cross-domain-ajax-and-ie
not sure whether it fits your scenario
xdr = new XDomainRequest();
xdr.onload=function()
{
alert(xdr.responseText);
}
xdr.open("GET", thisUrl); //thisURl ->your cross domain request URL
//pass your data here
xdr.send([data]);
you can find some more guidance here
This solved the issue gracefully for me:
https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
Just install/compile after jQuery and before your script and use the $.ajax method as you normally would, the rest is handled behind the automatically.
Have you try to use the lastest of JQuery(> jquery-1.8.0)? Since the version 1.8.0, they solved some IE9's bugs. Perhaps this one too.
http://blog.jquery.com/2012/08/30/jquery-1-8-1-released/
I had a similar problem and the solution for me was to use jsonp instead of json. That way I didn't have to break out a customer version for IE.
You can only do this if the json server host supports the callback request variable or you have access to the server and can add support. Here is a page that helped me understand the process. Its .net mvc focused, but it gives a good over view of the diffrence between json and jsonp.
http://blogorama.nerdworks.in/entry-EnablingJSONPcallsonASPNETMVC.aspx
Check the domain you are accessing, following response headers should be there
"Access-Control-Allow-Methods" : "POST, GET, OPTIONS"
"Access-Control-Allow-Origin" : "http://www.mydomain.com" or "*"
the other domain should allow your script request. One more header to be added to your response is P3P header.
"p3p" : "CP=IDC DSP COR ADM DEVi TAIi PSA PSD IVAi IVDi CONi HIS OUR IND CNT"
it should help you out.
I was facing similar issue.
I was using file upload control but it was hidden and I had another element trying to control the file upload and events to upload file in ajax way
try using the file upload control directly. this solved issue in my application.
I get this bug (and thus google here) but the reason was very different. So if you don't have cross site and still get this access denied error: double check the value sent
let's say that you affect one of you variable with the bad following expression:
urlVar = $("theID").val // without () this was the error!
[...]ajax call:
data: {cmd : 'getMessage', uurl: urlVar, t: Math.random()},
Google/FF have no problem with this (check what is receive server side...) BUT IE refuse to send this!
I changed my JQuery from version 1.10.1 to 1.10.2 and it seems to have solved this problem for me.
It seems that MS is finding its own way of doing things, rather than adopting industry recommendations. I found the solution here:
https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest/blob/master/jQuery.XDomainRequest.js
Simply add 'callback=?' on your ajax URL request like here:
http://wsvdmeer.blogspot.com.es/2012/08/bugfix-getjson-not-working-in-ie.html

Categories

Resources