Ajax post not working to external domain [duplicate] - javascript

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

Related

Cross Domain http get requests [duplicate]

This question already has answers here:
Ways to circumvent the same-origin policy
(8 answers)
Closed 9 years ago.
I need to make a cross domain ajax call to a server I own but the problem is that the request must come from the client not the server so proxies wont work for me. Our server will be behind a vpn so it won't be able to reach the internet but the client will be able to so we wanted to do a call home from the client to our metrics server to validate a product key.
My remote domain has a php script that simply writes either a 0, 1, or 2. I need my javascript to read this value in and react to it.
I want to do something simple like this but clearly it won't work. Any suggestions?
$.ajax({
url: callHomeUrl,
type: 'GET',
success: function(res) {
document.write($(res.responseText).text());
}
});
You can use a JSONP style implementation for that to get access to your server which works across all browser without CORS!
Example -
var script=document.createElement('script'):
script.type='text/javascript'; script.src='path/to/the/file';
document.getElementsByTagName('head')[0].appendChild(script);
Note that the file in the server should output the javascript function along with any relevant data.

Steam API Get SteamID using Javascript

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.

Sending POST message with AJAX Problem

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?

Get HTML of another page in another domain using JavaScript

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/

JQuery ajax cross domain call and permission issue

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

Categories

Resources