Check out "Do you speak JavaScript?" - my latest video course on advanced JavaScript.
Language APIs, Popular Concepts, Design Patterns, Advanced Techniques In the Browser

Javascript: handling with crossdomain requests

Ajax is a powerful tool for loading new content or data asynchronously. The well known problem is that we can't make requests to other hosts. In other words if your code is located at aaa.com you can't load bbb.com/getData.php. There are several solutions available.

1. Using frameworks. One of the popular solutions is to use some of the nice frameworks like jQuery that will do the job for you. jQuery supports native crossdomain requests. For more information check this page.

2. Using server-side code as a proxy. The other method that I prefer is to use some server-side language as a proxy. For example if you need to access bbb.com from aaa.com you can create a php file aaa.com/getDataFromBBB.php. This file is on your domain and you have access to it. Then you can simply use curl to access bbb.com and return the result to your local javascript code.

3. Using server's proxy. This is the ideal solution, but of course you have to have an administration access to your server. For example Apache has a module called mod_proxy, which perfectly fits in our needs. The basic idea is to add a rule that will forward your requests from aaa.com to bbb.com.

LoadModule proxy_module modules/mod_proxy.soLoadModule proxy_http_module modules/mod_proxy_http.so
<Proxy *>
    Order deny,allow
    Allow from all
</Proxy>

ProxyPass /data http://bbb.com/data

For example if you try to open aaa.com/data/getData.php the server will automatically open http://bbb.com/data/getData.php

If you enjoy this post, share it on Twitter, Facebook or LinkedIn.