I had a project where I needed to exchange data between two domains using AJAX. All major browsers don't allow cross-domain requests for security reasons. If you control both domains, you could use HTTP headers as described in Cross-Origin Resource Sharing. I tried it, and found that not all browsers support this standard. The good thing is that you can still do it by following this simple idea.
Consider two domains consumer.com and producer.com. Obviously, consumer.com needs to get some data from producer.com.
First, we call producer.com from a hidden
style="width:0;height:0;border:0px solid #fff;">
... process reply from producer.com
The 'style' attribute hides the
iframe. The ‘
proxy_done’ function is called when the reply is ready. The
iframe element with producer.com is not allowed to communicate with the parent page (consumer.com). We just need to redirect it back to consumer.com.
On producer.com, create request.html with something like the following.
var reply = ... process the request and get reply
self.location.href="consumer.com/proxy_page.php?reply=" + reply;
The script redirects the
iframe along with the reply data back to a proxy page (see below) that resides at consumer.com.
At this time, the original
iframe element on consumer.com contains proxy_page.html with the reply from producer.com. Because proxy_page.html is on consumer.com it can now access its parent page. Now, we can call the '
proxy_done' function, and pass it the reply.
echo '<script> var reply="'.$_GET['reply'].'"; </script>';
iframe element dynamically...
document.createElement("iframe")... all this DOM stuff follows...