Let's talk Contact us. No cost. No obligation.

Fill out this form and we will contact you with in 24 hrs.

    captcha

     

    Knowledge Base

    How to run ajax in cross domain

    April 22, 2014

    Many developer fraternity face problem when they try to use ajax in cross domain (i.e from any other website). Here is the solution for this problem.

    Step1: Write down the client side ajax code as usual as it is in simple Javascript or Jquery.

    Suppose we writting a Jquery code in the website call www.example.com

    Now we call here the server php file of the www.someone.com. No change in the usaul code of ajax in www.example.com

    Step2: Go to server side php file in www.someone.com. Lets global_ajax.php has code to respond the ajax call from their on site working perfectly.

    Now adding following code in the top of the file to work well for the ajax call from other site(cross domain) as well.

    header(‘Access-Control-Allow-Origin: ‘.$_SERVER[‘HTTP_ORIGIN’]);

    header(‘Access-Control-Allow-Methods: POST, GET, OPTIONS’);

    header(‘Access-Control-Max-Age: 1000’);

    header(‘Access-Control-Allow-Headers: Content-Type’);

    ?>

    Actually this header allows the other domain to access our code or in other words we opening our code for the other domain to access. However this practice is not good but we can reduce the implication by putting specific domain so that it can allow specific domain or domains of your faith in the header(‘Access-Control-Allow-Origin:http://yoursecuredomain.com’);

    Even we can check the $_SERVER[‘HTTP_ORIGIN’] in allowed domain before giving access to our server side code. So all in all this functionality for the cross domain ajax is fine but use it with proper restrication.

    About Abhinav Girdhar

    Abhinav Girdhar, is the CEO and Founder of Appy Pie and is a Content Contributor on Top Digital Verticals like Wired.com & India Digital Review. For More details about him Visit