Sunday, October 20, 2013

ajax with cross domain


We may worked with jQuery ajax in many cases but when we try to use jQuery AJAX to get the data from other domain, we need to use "crossDomain" & set it to true.

Let us consider the basic jQuery AJAX within the domain.

$.ajax({
            url: "show_users.php",
            data: {data1:"val1", data2="val2"},
            type:'POST',
            success: function(res)
            {
                $('#element_name').html(res);
            },
            error: function (){alert('something went wrong');}
});

Above is the AJAX request within the domain & just we are passing the data to the page "show_users.php" with two values. As it is simple AJAX request, it works fine.

But when we work with cross domains (i.e. AJAX request to other domain from our domain) we need to rewrite the jQuery AJAX as below.

$.ajax({
            url: "http://domain.com/show_users.php",
            data: {data1:"val1", data2="val2"},
            type:'POST',
            crossDomain: true,
            success: function(res)
            {
                $('#element_name').html(res);
            },
            error: function (){alert('something went wrong');}
});

We need to use "crossDomain" & set it to TRUE & in the domain.com show_users.php page we need to set an header as below.

header('Access-Control-Allow-Origin: *');

We can set the "Access-Control-Allow-Origin" with only one IP address or '*' if it is not limited to single IP address

No comments: