Thursday, January 26, 2012

Cross Domain request in Ajax

Today I am discussing How the ajax request handled by server.
Through ajax in javascript we can load almost every kind of data from server side,Let's take an example.
Write an html page on your localhost(I take wamp server) name test.html.and include the jQuery file in that html file,also include the js that given below in this page,the code snippet for jquey scipt is given below.


$(document).ready(function()
{
$.ajax({
type: "GET",
url: "http://localhost/test/data.php",
dataType: "text",
success: function(result) {
alert(result);
}
});

});

Now create a folder test inside your web deployment folder eg. For wamp, www folder is web deployment folder,inside test folder create a php file name data.php which contains the following code.remember to place the test.html file in the same test folder.
echo "Hi This is a Text";
It will work on same server,but when we place this data.php file in some another server like www.abc.com,then test.html file can not find response from server.This is very good fetaure for security purpose that is implemented by almost all modern browser.but sometimes we need resources from different server like in web services we get response from different domain.In that case we have to change something in our resource file we have to include a header that describe which domains are allowed to use the resources. replace the code of data.php with following code snippet:
<?php
header("Access-Control-Allow-Origin: *");
echo "Hi This is Text";
?>

and we should change the path of resource in our html file also like:
$(document).ready(function()
{
$.ajax({
type: "GET",
url: "http://www.abc.com/data.php",
dataType: "text",
success: function(result) {
alert(result);
}
});

});

We can also put a string of domains in place of * from where we want accessing of the required resources.Now If we run .html file then it works.We can check it from different servers also,but for simplicity I have taken localhost.Avoid use of *,because it allows every request for this resource.In real world it is security threat for your resources Instead of this we should provide domain List.
I have checked this work on almost all new browsers.I have checked this application on Mozilla and Google chrome.


Thanks:

1 comment:

  1. Best knowledge base ajax and many technology.
    thanks sir for tips.

    ReplyDelete