Implementing Cross Domain Communication Between Sites Through Cors Using Php And Javascript
Solution 1:
Javascript Code for the client side
<scripttype='text/javascript'>// function for making an object for making AJAX requestfunctiongetXMLHTTPRequest() {
try {
req = newXMLHttpRequest();
} catch(err1) {
try {
req = newActiveXObject("Msxml2.XMLHTTP");
} catch (err2) {
try {
req = newActiveXObject("Microsoft.XMLHTTP");
} catch (err3) {
req = false;
}
}
}
return req;
}
var http899 = getXMLHTTPRequest();
functionsearchFabIndia() {
var myurl = "http://my2nddomain.com/yebhi.php";
myRand = parseInt(Math.random()*999999999999999);
var modurl = myurl+"?rand="+myRand;
http899.open("GET", modurl, true);
http899.onreadystatechange = useHttpResponse899;
http899.send(null);
}
functionuseHttpResponse899() {
if (http899.readyState == 4) {
if(http899.status == 200) {
// do all processings with the obtained values / response here
}
}
}
</script><bodyonload='searchFabIndia();'>
Part of the code required on the server side. You need to set the origin(referrers) who can ask for the page content, allow methods and headers. These settings can be stored either in the .htaccess file together for all the files on the 2nd domain to which you are making request, or, you can put them in your specific PHP file as shown:-
<?php
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, OPTIONS, PUT, DELETE");
header("Access-Control-Allow-Headers: Content-Type, Depth, User-Agent, X-File-Size, X-Requested-With, If-Modified-Since, X-File-Name, Cache-Control");
header("Access-Control-Max-Age: 18000");
// Put it in your PHP file?>
OR else , you can specify these settings for the entire domain/sub-domain together by mentioning the same in your .htaccess file as shown :-
<IfModule mod_headers.c><FilesMatch "\.(php)$">
Header set Access-Control-Allow-Origin: *
Header set Access-Control-Allow-Methods : POST,GET,OPTIONS,PUT,DELETE</FilesMatch></IfModule>
Also not that the wildcard allowance to all the referrers can be sometimes unnecessary , so, in that case you can specify the specific domain/sub-domain by naming them , each of them separated by comma(,) as shown
Header set Access-Control-Allow-Origin: http://abc.com,http://def.com,http://ghi.com
Please comment in case you face some difficulty in implementing any of these. You can see live demo of what I mentioned here
Post a Comment for "Implementing Cross Domain Communication Between Sites Through Cors Using Php And Javascript"