views:

833

answers:

4

When using an XMLHTTPRequest in javascript, I want to send it to an external website, rather than the one where the .js file is hosted. To send it to test.php on the current server, I would use

request.open("POST", "test.php", true);

but for the second arguemnt, how do I send it to another website. "example.com/test.php" looks for a file on the current server, and "http://example.com/test.php" justseems to outright fail.

+4  A: 

This sounds like a bad case of Same Origin Policy, my friend :)

roosteronacid
+3  A: 

You can't for security reasons. See the same origin policy for JavaScript.

There are some workarounds that exploit browser bugs or corner cases, but using them is not recommended.

The best approach is having a server-side proxy that receives Ajax requests, and in turn, sends HTTP requests to other servers. This should be carefully implemented by sanitizing input and whitelisting the types of requests that are sent, and the servers that are contacted.

Ayman Hourieh
+1  A: 

You can't (for the most part) use XmlHttpRequest to get data from an external website. What you can do, however, is dynamically create a SCRIPT tag and reference an external address. jQuery wraps this functionally as part of its ajax handling.

Nathan Ridley
+1  A: 

Indeed you can. Not in any browser although.

In Internet Explorer 8.0 there is XDomainRequest, an object enabling cross-domain requests. You would need to properly handle request made with this object on server by sending Access-Control-Allow-Origin header first with "*" or requester domain name.

Since you are doing some hacky things anyway, why not trying to use it on IE8 first?

Sergey Ilinsky