I have this polling script to check if a text file is created on the server. Works great locally, but fails when the file is on a different domain. How would i rewrite this for cross domain support?
$.ajax({
url: 'http://blah.mydomain.com/test.txt',
type: "GET",
success: function(result) {
//Success!
window.location.replace(Successful.aspx');
},
error: function(request, status, error) {
setTimeout("VerifyStatus(" + pollingInterval + ")");
}
});
EDIT:
I ended up using YQL to solve the cross domain issue and although it works, YQL is really slow that's adding quite a bit of performance overhead. Can anyone suggest a better solution for cross domain JQuery calls?
Set the dataType to "JSONP" on your $.ajax() call. You'll have to make sure the response is properly formatted for it to work. Wikipedia has a good section on JSONP.
Ajax doesn't go cross domain. Your best bet is to create a php page on the local domain that does the check, and go to -that- with your ajax call.
To get cross-domain AJAX via jQuery, you might want to check this out:
http://github.com/jamespadolsey/jQuery-Plugins/tree/master/cross-domain-ajax/
Almost modern browsers are now supporting cross domain with CORS protocol, so you can use Ajax jQuery to do your job without editing anything in your script code. The change is into your server, you need to enable your server with CORS. It's just the job with adding header fields in each responses to client to support CORS protocol. See an implementation example here.
http://zhentao-li.blogspot.com/2013/06/example-for-enabling-cors-support-in.html
Related
This question already has answers here:
$.ajax call working fine in IE8 and Doesn't work in firefox and chrome browsers
(3 answers)
Closed 9 years ago.
Maybe I'm the Nth user that ask this question, but I can't figure it out.
The data string of the ajax call seems to be empty or what? Either I don't get any feedback on the succes or error function.
$.ajax({
type:'POST',
url:'http://www.example.com/test.php',
data:'lid=test',
succes: function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
});
I hope someone can help me out with it?
Kind regards,
Frank
There's no succes function. You probably mean success.
This is because of the Same origin policy. you cannot use ajax to call external sites. if you really want to use, you have to use JSONP. Or you can use serverside proxy for this. means, call external site in the server side and do ajax call to the that webservice.
for more information please refer this link and this answer
https://stackoverflow.com/a/8698786/880434
Try this
$.ajax({
type:'POST',
url:'http://www.example.com/test.php',
crossDomain: true,
data:'lid=test',
success: function(data){
console.log(data);
},
error:function(data){
console.log(data);
}
});
AJAX requests are generally limited to same domain. Here is some information I found on another Stack Overflow Answer, Using Access-Control-Allow-Origin header
Alternatively, if your response is of the right format, you could try a JSONP request
You're being blocked by the browser "Same origin policy". That is, you cannot do ajax requests to other than the same domain that the script was loaded from. There are, however, some workarounds:
Use JSONP. This is probably the most cross browser compatible solution
Configure your application to support CORS. This works in most modern browsers, but not in some older.
Create a proxy service on your own server. That is, mount an endpoint, e.g. /externalService that proxies the request on the server side to the remote endpoint. It also will work in all browsers, but will involve more work on the server side.
The server www.example.com should have the cross-domain.xml which will contain the domain names allowed to request and get response. So add your domain from which the request is coming or just add the doamin name as '*' to accept all doamins
Been running into what appears to be the Same Origin Policy which is causing quite some headache!
To cut to the chase, I am essentially trying to acquire a user's steam64id when only supplied their username.
For example, my username: "Emperor_Jordan" I would go to:
http://steamcommunity.com/id/emperor_jordan?xml=1
And the steamid I need is right at the top. So I figured I would use JQuery Ajax to acquire this and parse out the id I need for later usage (steamapi usage requires the steam64id) as follows. Here is a snippet of the code in question:
$.ajax({
url: "http://steamcommunity.com/id/emperor_jordan/?xml=1",
datatype: "xml",
complete: function()
{
alert(this.url)
},
success: parse
});
function parse(xml)
{
alert("parsing");
_steamID = $(xml).find("steamID64").text();
}
The problem here is while I do get the alert for the completion, I never see "parsing". Ever. It never gets that callback, which leads me to believe I am running into the SOP (same origin policy).
Am I approaching this the wrong way, is there a workaround?
Thanks!
Correct. You are running into the same-origin policy:
XMLHttpRequest cannot load http://steamcommunity.com/id/emperor_jordan/?xml=1. Origin http://fiddle.jshell.net is not allowed by Access-Control-Allow-Origin.
and it looks like Steam does not offer a cross-origin solution like JSONP. That means you're back to the old-but-reliable solution: fetch the data on your server, not in the browser.
Some relevant feedback on the Steam Web API: https://developer.valvesoftware.com/wiki/Steam_Web_API/Feedback#API_Considerations_for_Web_Developers
You need to create a proxy server in Heroku in order to get the data. Cors is restricting us to call the data directly to our browser not server to server interaction. So we need a proxy server to send the requests and receive the data on our behalf. It's working for me.
Thanks in advance.
Ok, so basically.
I inject some javascript code into a web page and it uploads an image on that page to another server.
Now I have it working when I run it on my domain (of course), but I need to post the multipart/form-data request to a PHP file that I do not own.
Since it is a upload and not a simple request to just get data, I cannot use jsonp in the initial call since the response would not be in json.
Using James Padolsey's cross domain script, I am able to do $.get and $.post request across domains, but since I am using $.ajax it does not work.
He uses the Yahoo Query Language to acomplish this
This is basically how I am making the request
$.ajax({
url: 'http://website.com/upload.php',
type: 'POST',
contentType:'multipart/form-data',
data: postData,
success: successCallback,
error : function(XMLHttpRequest, textStatus, errorThrown) {
console.log('Error');
}
});
I want to make it completely JavaScript based to avoid making my server do the request.
So to re-cap, I can get the image bytes and make the request with javascript. But so far I cannot make it cross domain since I am $.ajax to set the content Type to "multipart/form-data".
Is there another way to make the request cross domain with or without the YQL?
Making the request with an iframe will not work since the domain of the iframe would change and I would not have access to the response.
This is a well known and difficult problem for web development, know as the Same Origin Policy
Javascript prevents access to most methods and properties to pages across different origins. The term "origin" is defined using the domain name, application layer protocol, and (in most browsers) port number of the HTML document running the script. Two resources are considered to be of the same origin if and only if all these values are exactly the same.
There are several ways around this.
Create your own proxy
Create a page that simply forwards the request to the other server, and returns its response
or, Use Apache's rules to form a proxy (see above link)
Use someone else's proxy
For GET requests which are typical Use YQL to access yahoo's proxy
For POST requests, if the 3rd party supports Open Data Tables
or, Use some other public proxy
See if the 3rd party conforms to the CORS specification
Cross domain POST query using Cross-Origin Resource Sharing getting no data back
If you are willing to allow a little flash on your page, try flXHR
it claims to implement the exact XHR api and also has a jquery plugin
These are pretty much your only options
I am currently trying to send a POST message which works fine except for the error that there are not correct credentials. However, after I add the credentials header, the message type is changed into OPTIONS and fails. I do not understand how adding a header causes the type to change to OPTIONS. Any help would be appreciated.
ajaxRequest = $j.ajax({
url: url,
type: 'POST',
beforeSend : function(req) {
req.setRequestHeader('Authorization', auth),
}
success: function(data, status) {
console.log("Success!!");
console.log(data);
console.log(status);
},
error: function(xhr, desc, err) {
console.log(xhr);
alert('fail')
console.log("Desc: " + desc + "\nErr:" + err);
}
});
EDIT: just to be more clear, I can literally go in and comment out the setRequestHeader function and it sends the message POST.
The problem you're encountering is because of cross-domain restrictions when using AJAX. When you try to set an authorization header, the browser issues what's known as a pre-flight request to see if the server will accept requests from this domain.
A pre-flight request is typically sent as an OPTIONS request. If the server you're invoking doesn't return an Access-Control-Allow-Origin header that matches your domain, the AJAX request is blocked.
There's more on this here: Cross-Origin Resource Sharing
"User agents can discover via a preflight request whether a cross-origin resource is prepared to accept requests, using a non-simple method, from a given origin."
I've run into the same problem- there are a few possible workarounds depending on your scenario.
If you have any way of setting the above mentioned header on the 3rd party server (some applications/services offer this) then that's probably the easiest way.
There's also a javascript library called EasyXDM that may work for you, but again, it will only be of use if you have access to the 3rd party server to upload a configuration file for this library.
Other options to investigate are PostMessage and Cross Domain Iframe communication. The latter is more of an old-school hack, the former is the recommended approach for newer browsers. It won't work for IE6/7.
The option we will probably end up using is a simple proxy- invoke our own server with the AJAX request, and on the server invoke the 3rd party server. This avoids the cross domain issue entirely, and has other advantages for our scenario.
I guess this is a problem in Internet Explorer. without explicitly telling the request-method (POST|GET) the request header doesn't contain the custom-header in IE, but it works in other browsers.
Yet try to post this in the bugs for jquery. Also try in other browsers.
Edit 1 : I saw this as a bug in jQuery 1.4.x .... I reported a bug report now.
The OPTIONS response happens when the server does not know how to respond to the ajax request.
I've seen it happen often when trying to post to a third-party domain (i.e. cross-site posting)
The OPTIONS method represents a request for information about the communication options available on the request/response chain identified by the Request-URI. This method allows the client to determine the options and/or requirements associated with a resource, or the capabilities of a server, without implying a resource action or initiating a resource retrieval.
Have you tried:
Having some sort of callback on the url that is being posted to?
Explicitly setting the headers (I'm assuming you're using PHP) on the url that is being posted to?
Right now, I am using curl in PHP to get the HTML source code of some remote web page.
Is there any way I can get the same HTML source code of some cross-domain web page in JavaScript? Any tutorials?
I think you need to know about JSONP to access cross-domain web pages in js
https://stackoverflow.com/questions/tagged/jsonp?sort=votes
Q. How is this any different than issuing an AJAX "GET http://otherdomain.com/page.html" call?
A. The same-origin policy checks the HTTP response headers for AJAX requests to remote domains, and if they don't contain a suitable Access-Control-Allow-Origin header, the request fails.
So, there are two ways to make this work:
If you control the other domain, you can include the following header in the HTTP response:
Access-Control-Allow-Origin: *
(details at MDC)
If you don't, you're stuck implementing a server-side proxy (for example, this simple PHP proxy).
In any case, once you implement one of the two options above, you're left with a simple AJAX call:
$.ajax({
url: "http://mydomain.com/path/to/proxy.php?url="+
encodeURI("http://otherdomain.com/page.html"),
dataType: "text",
success: function(result) {
$("#result").text(result);
}
});
This solution I just found might be of use like the other workarounds...
http://www.ajax-cross-domain.com/