How do I send a cross-domain POST request via JavaScript?
Notes - it shouldn't refresh the page, and I need to grab and parse the response afterwards.
To send an HTTP POST request, we need to first create the object by calling new XMLHttpRequest() and then use the open() and send() methods of XMLHttpRequest. To receive notifications when the status of a request has changed, we need to subscribe to the onreadystatechange event.
Cross-Domain JavaScript Requests allow developers to work around security restrictions that would prevent an application from contacting Places (Search) API directly. For example, certain location information might not be retrievable without enabling this method.
Browser does not allow cross domain AJAX requests due to security issues. Cross-domain requests are allowed only if the server specifies same origin security policy. To enable CORS, You need to specify below HTTP headers in the server.
Update: Before continuing everyone should read and understand the html5rocks tutorial on CORS. It is easy to understand and very clear.
If you control the server being POSTed, simply leverage the "Cross-Origin Resource Sharing standard" by setting response headers on the server. This answer is discussed in other answers in this thread, but not very clearly in my opinion.
In short here is how you accomplish the cross domain POST from from.com/1.html to to.com/postHere.php (using PHP as an example). Note: you only need to set Access-Control-Allow-Origin
for NON OPTIONS
requests - this example always sets all headers for a smaller code snippet.
In postHere.php setup the following:
switch ($_SERVER['HTTP_ORIGIN']) { case 'http://from.com': case 'https://from.com': header('Access-Control-Allow-Origin: '.$_SERVER['HTTP_ORIGIN']); header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS'); header('Access-Control-Max-Age: 1000'); header('Access-Control-Allow-Headers: Content-Type, Authorization, X-Requested-With'); break; }
This allows your script to make cross domain POST, GET and OPTIONS. This will become clear as you continue to read...
Setup your cross domain POST from JS (jQuery example):
$.ajax({ type: 'POST', url: 'https://to.com/postHere.php', crossDomain: true, data: '{"some":"json"}', dataType: 'json', success: function(responseData, textStatus, jqXHR) { var value = responseData.someKey; }, error: function (responseData, textStatus, errorThrown) { alert('POST failed.'); } });
When you do the POST in step 2, your browser will send a "OPTIONS" method to the server. This is a "sniff" by the browser to see if the server is cool with you POSTing to it. The server responds with an "Access-Control-Allow-Origin" telling the browser its OK to POST|GET|ORIGIN if request originated from "http://from.com" or "https://from.com". Since the server is OK with it, the browser will make a 2nd request (this time a POST). It is good practice to have your client set the content type it is sending - so you'll need to allow that as well.
MDN has a great write-up about HTTP access control, that goes into detail of how the entire flow works. According to their docs, it should "work in browsers that support cross-site XMLHttpRequest". This is a bit misleading however, as I THINK only modern browsers allow cross domain POST. I have only verified this works with safari,chrome,FF 3.6.
Keep in mind the following if you do this:
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With