I have written an XMLHttpRequest which runs fine but returns an empty responseText.
The javascript is as follows:
var anUrl = "http://api.xxx.com/rates/csv/rates.txt";
var myRequest = new XMLHttpRequest();
callAjax(anUrl);
function callAjax(url) {
myRequest.open("GET", url, true);
myRequest.onreadystatechange = responseAjax;
myRequest.setRequestHeader("Cache-Control", "no-cache");
myRequest.send(null);
}
function responseAjax() {
if(myRequest.readyState == 4) {
if(myRequest.status == 200) {
result = myRequest.responseText;
alert(result);
alert("we made it");
} else {
alert( " An error has occurred: " + myRequest.statusText);
}
}
}
The code runs fine. I can walk through and I get the readyState == 4 and a status == 200 but the responseText is always blank.
I am getting a log error (in Safari debug) of Error dispatching: getProperties which I cannot seem to find reference to.
I have run the code in Safari and Firefox both locally and on a remote server.
The URL when put into a browser will return the string and give a status code of 200.
I wrote similar code to the same URL in a Mac Widget which runs fine, but the same code in a browser never returns a result.
Is http://api.xxx.com/ part of your domain? If not, you are being blocked by the same origin policy.
You may want to check out the following Stack Overflow post for a few possible workarounds:
Ways to circumvent the same-origin policy
PROBLEM RESOLVED
In my case the problem was that I do the ajax call (with $.ajax, $.get or $.getJSON methods from jQuery) with full path in the url param:
url: "http://mydomain.com/site/cgi-bin/serverApp.php"
But the correct way is to pass the value of url as:
url: "site/cgi-bin/serverApp.php"
Some browser don't conflict and make no distiction between one text or another, but in Firefox 3.6 for Mac OS take this full path as "cross site scripting"... another thing, in the same browser there is a distinction between:
http://mydomain.com/site/index.html
And put
http://www.mydomain.com/site/index.html
In fact it is the correct point view, but most implementations make no distinction, so the solution was to remove all the text that specify the full path to the script in the methods that do the ajax request AND.... remove any BASE tag in the index.html file
base href="http://mydomain.com/" <--- bad idea, remove it!
If you don't remove it, this version of browser for this system may take your ajax request like if it is a cross site request!
I have the same problem but only on the Mac OS machine. The problem is that Firefox treat the ajax response as an "cross site" call, in any other machine/browser it works fine. I didn't found any help about this (I think that is a firefox implementation issue), but I'm going to prove the next code at the server side:
header('Content-type: application/json');
to ensure that browser get the data as "json data" ...
The browser is preventing you from cross-site scripting.
If the url is outside of your domain, then you need to do this on the server side or move it into your domain.
This might not be the best way to do it. But it somehow worked for me, so i'm going to run with it.
In my php function that returns the data, one line before the return line, I add an echo statement, echoing the data I want to send.
Now sure why it worked, but it did.
Had a similar problem to yours. What we had to do is use the document.domain solution found here:
Ways to circumvent the same-origin policy
We also needed to change thins on the web service side. Used the "Access-Control-Allow-Origin" header found here:
https://developer.mozilla.org/En/HTTP_access_control
Related
Access to restricted URI denied" code: "1012 [Break On This Error]
xhttp.send(null);
function getXML(xml_file) {
if (window.XMLHttpRequest) {
var xhttp = new XMLHttpRequest(); // Cretes a instantce of XMLHttpRequest object
}
else {
var xhttp = new ActiveXObject("Microsoft.XMLHTTP"); // for IE 5/6
}
xhttp.open("GET",xml_file,false);
xhttp.send(null);
var xmlDoc = xhttp.responseXML;
return (xmlDoc);
}
I'm trying to get data from a XML file using JavaScript. Im using Firebug to test and debug on Firefox.
The above error is what I'm getting. It works in other places i used the same before, why is acting weird here?
Can someone help me why it's occuring?
Update:
http://jquery-howto.blogspot.com/2008/12/access-to-restricted-uri-denied-code.html
I found this link explaining the cause of the problem. But I didn't get what the solution given means can someone elaborate?
Another possible cause of this is when you are working with a .html file directly on the file system. For example, if you're accessing it using this url in your browser: C:/Users/Someguy/Desktop/MyProject/index.html
If that then has to make an ajax request, the ajax request will fail because ajax requests to the filesystem are restricted. To fix this, setup a webserver that points localhost to C:/Users/Someguy/Desktop/MyProject and access it from http://localhost/index.html
Sounds like you are breaking the same origin policy.
Sub domains, different ports, different protocols are considered different domains.
Try adding Access-Control-Allow-Origin:* header to the server side script that feeds you the XML. If you don't do it in PHP (where you can use header()) and try to read a raw XML file, you probably have to set the header in a .htaccess file by adding Header set Access-Control-Allow-Origin "*". In addition you might need to add Access-Control-Allow-Headers:*.
Also I'd recommend to replace the * in production mode to disallow everybody from reading your data and instead add your own url there.
Without code impossible to say, but you could be running foul of the cross-site ajax limitation: you cannot make ajax requests to other domains.
I have run in to a problem. Please help with your expertise.
I am developing web solution for a company. They have provided me Web API Method (REST). This API is in their domain. I am too access this from my domain. Even client has also already whitelisted my domain.
I am trying to call this method using below. But no luck. I am getting this below error.
Error NS_ERROR_DOM_BAD_URI: Access to restricted URI denied
function GetCustomerInfo()
{
var Url = "http://webapi.company.com/vx.x/customer/get?format=xml&mobile=9876543210" ;
myXmlHttp = new XMLHttpRequest();
myXmlHttp.withCredentials = true;
myXmlHttp.onreadystatechange = ProcessRequest;
myXmlHttp.open( "GET", Url, true,"UID","PWD");
myXmlHttp.send();
}
function ProcessRequest()
{
if(this.readyState == this.DONE)
{
if(this.status == 200 && this.responseXML != null )
{
alert ("Received Resoponse from Server");
}
else
{
alert ("Some Problem");
}
}
}
I am able to access this method from RESTClient in firefox plugin.
Even I am able to access this method copying credentials in URL as below in browser address bar. I get anticipated response XML
http://UID:PWD#webapi.company.com/vx.x/customer/get?format=xml&mobile=9876543210
Please enlighten me where I am wrong. Perhaps JSONP can come to my help. But why i am not able to access this API using XMLHttpRequest.
Regards
Rajul
The same origin policy of the browser does not allow you to send XMLHttpRequests to a different domain. The reason you can access it through a firefox plugin or the address bar is that the same origin policy is not applied there.
You are right, JSONP could solve your problem, although you may run into trouble because you do not control the serverside.
In response to your comment: In order to use JSONP effectively, the server will need to return not only the data you need in JSON format, but also javascript code to invoke a callback when the request is done. If you do not control the data that is returned, you can not add the necessary code for this. The wikipedia article gives a good example for the general case.
I have never used CORS, thus can not give you much information on it. It seems like a better solution, but I imagine it is not incredibly compatible across browsers. Also, as I understand it, you will need control of the server as well, as it seems to require additional HTTP headers.
I have a site that I enter a username/password and click a login button. The login button makes an XMLHttpRequest object, and fires it off.
On Chrome, Firefox, Opera, Safari, Android devices, iOS devices this works fine.
IE9 will work fin so long as I am on an HTTP address and not using HTTPS.
On HTTPS, IE9 behaves as follows:
The first login request never returns anything back. The F12 screen does show my login request in the network tab and all looks correct. The scripting tab never throws an error. Simply nothing happens.
Here's the crazy part:
- If I click login a second time, it actually works.
- If I click refresh on the browser, and then login, that will work as well!
I am making the request as follows:
var x = new XMLHttpRequest();
x.open("POST", "/Relative/URL/Path", true);
x.setRequestHeader("Content-Type", "text/plain");
x.onreadystatechange = function () {
if ((x.readyState == 4) && (x.status == 200)) {
// handle callback
}
}
x.send(my request);
When this fails, the debugger will go from the x.send() line into the onreadystatechange code. The readyState will be 1. This will be the last I can debug because nothing else happens.
Any ideas would be extremely appreciated.
[EDIT]: I let one request go to see what would happen. The onreadystatechange event fired again with readyState = 4 and status = 12152. The network view in IE9's F12 screen shows the result as Aborted and the time taken as 1589.07s. A Google search shows this means the connection was closed on the server.
[EDIT 2]: Based on a comment below I redid this code to just use jQuery's ajax() method. I thought this might have a chance at eliminating bad code on my part. No such luck. The same behavior occurs.
$.ajax({
"url": sUrl,
"success": function (data, textStatus, x) {
workerCallback(data, id, "");
},
"error": function (x, testStatus, errorThrown) {
workerCallback("nc", id, errorThrown);
},
"contentType": "text/plain",
"data": JSON.stringify(req),
"dataType": "json",
"timeout": 1600000,
"type": "POST"
});
[FINAL UPDATE:] I've updated the code. If a timeout occurs, I simply repost the same request - one time only. Quite the hack but it works. Unless anyone finds the solution I'll split the bounty between a few helpful ideas people have had below.
This seems like a strange issue and it's hard to test it without poking around the code on an https site.
If you want a quick fix you could try doing an initial (dummy) request then abort it right away with a short setTimeout and make a second (real) request.
As per your description it should work.
during debug on the first request this came through
There is a related post to this exact error...
IE 9 Javascript error c00c023f
The author put the following in the onreadystatechange handler
if (xmlHttpRequest.aborted==true) {
stopLoadAnimation();
return;
}
This may help point you in the right direction.
Timeouts prevents the request from being terminated at readyState 1, and it succeeds afterwards due to content sniffing.
Configure SSL client authentication on the login form using the web server config
Insert a hidden element (such as an image) that references an URL that requires SSL client authentication
Use a protocol relative gif hyperlink, such as //example.com/image.gif, to avoid the SEC7111 mixed content vulnerability
The URL of the open method matches the domain when using HTTP, but not HTTPS, which causes the request to fail, but subsequent requests fallback to the security zone policy
Use a comparison between window.location.protocol and document.location.protocol to check whether the script is executing in the same context as the page
Sending JSON as MIME type text/plain may trigger content sniffing
Compare the Accept header between the requests that fail versus those that succeed
HTTPS Caching may be an issue
The Connection header may need to be set
Proxy configuration may be an issue
The initial header response values may be too large (e.g. HTTP status description has a limit of 512 characters)
document.readystate may not be complete on the initial request, which causes premature execution problems
Certificate revocation checks may block the initial JSON POST, but allow subsequent requests after the GET callback
readyState and status properties should be referenced using the callback scope rather than the variable x to avoid using the closure scope:
function cb()
{
if ( (this.readyState === 4) && (this.status === 200) )
{
// handle callback
}
}
onreadystatechange = cb;
The first thing I would like to say is that I looked around for an answer to this for quite some time, but everything I found was about jQuery. This is not about jQuery.
I have some code (below), but when I ran it in Firefox then Firebug gave me this big, incomprehensible exception. I tried it in Google Chrome and got something a bit more useful: "XMLHttpRequest cannot load http://www.wikipedia.org/. Origin null is not allowed by Access-Control-Allow-Origin." (If you'd like to know why I was trying to access Wikipedia, I often use it as a test site.)
Here is my code:
function requestSite(url) {
var xmlhttp;
if (window.XMLHttpRequest) {
xmlhttp = new XMLHttpRequest();
}
else {
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.open("GET", url, false);
xmlhttp.send();
return xmlhttp;
}
All I tried to do with it was access Wikipedia. Then Google, which gave me the same result. Perhaps it is worth noting that when I triggered the function with a button on the page, it gave me this, while using the console was exactly the same, but without the error message. Another thing that may or may not be worth mentioning is that I was running this file from my local filesystem.
You can't make an AJAX request to a URL that is on a different domain. It's a basic browser security issue.
This error message means
"You are running this request from your local system".
Making ajax requests to some other domain besides the one you are running the code is (of course) not allowed.
I'm working on a very simple Sidebar Gadget to analyze my router's monthly bandwidth usage and determine how far ahead or behind I am for that month. The data is located in a router-hosted, password protected webpage (I'm using DD-WRT, if it matters). I'd like to pass a page request to the router with Javascript, along with all the authentication information, to retrieve the page all in one go, but I can't seem to find the proper syntax for that. Any ideas?
Here's my code so far:
var ua = navigator.userAgent.toLowerCase();
if (!window.ActiveXObject){
req = new XMLHttpRequest();
}else if (ua.indexOf('msie 5') == -1){
req = new ActiveXObject("Msxml2.XMLHTTP");
}else{
req = new ActiveXObject("Microsoft.XMLHTTP");
}
req.open('GET', 'http://192.168.1.1/Status_Internet.asp', false, "username", "password");
req.send(null);
if(req.status == 200){
dump(req.responseText);
} else{
document.write("Error");
}
document.write("Second Error");
Firebug indicates that it throws an error on req.send(null) - specifically,
Access to restricted URI denied" code: "1012.
It may be because of the same-origin policy, but in that case what can I use instead of an xmlhttpRequest?
It is because of the same-origin policy, the alternative is an iframe but that will not really give you what you wish for.
If it is http-auth you used to be able to request the page with http://username:pass#site but i must admit i haven't tried to use that for a long time, so i don't know if it is still supported.
EDIT:
If this doesn't work, maybe you can use basic http auth as described here: http://en.wikipedia.org/wiki/Basic_access_authentication but this would require you to sue a serverside proxy, since you can't manipulate the request headers from javascript when xhr is not an option.
You need to add a Authorization header to the request. I'm not an AJAX expert, so I'm not sure if you can modify header fields in AJAX requests. If you can't, then you're doomed.
If you can, then this Wikipedia article contains an example what it must look like.
That's a security feature: you see, there are malicious scripts that used a similar technique to hack the routers (who changes their router password anyway? Apparently not Joe X. Schmoe).
Under the Same Origin Policy, AJAX requests are limited to the domain (and port) whence they originated: therefore, from a local page, you can't make a request to 192.168.1.1:80 .
There is a possible workaround - a server-side proxy (e.g. a PHP script that fetches the router pages for you) inside your network.
If the same-origin policy is not the issue, then
load jQuery on your page.
and use jQuery's $.ajax method.
$.ajax({
url: "path/to/your/page.html", // self-explanatory
password:"your password", // a string with your password.
success: function(data){ // on sucsess:
$("someDiv").html(data); // load in the retrived page
}
});
See the jQuery ajax API for details.