John
John

Reputation:

How to specify an external website for XMLHTTPRequest

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.

Upvotes: 4

Views: 10452

Answers (5)

Michael
Michael

Reputation: 9402

If you have control over the server, you can use this header in the HTTP reply, although it may not work with all browsers.

Access-Control-Allow-Origin: *

Upvotes: 1

Sergey Ilinsky
Sergey Ilinsky

Reputation: 31535

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?

Upvotes: 1

Nathan Ridley
Nathan Ridley

Reputation: 34396

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.

Upvotes: 1

Ayman Hourieh
Ayman Hourieh

Reputation: 137166

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.

Upvotes: 7

cllpse
cllpse

Reputation: 21727

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

Upvotes: 6

Related Questions