X
    Categories: Jquery

Cross domain request using Ajax

Due to security issue browser will not allow cross site request using ajax. Cross domain request will allow only server specify same origin server policies.

Read about CORS in wiki.

To enable CORS need to specify header in server.

1. Access-Control-Allow-Origin -> Domain name. (* for all domain).

2. Access-Control-Allow-Methods -> Http methods like GET,POST, DELETE…

3. Access-Control-Allow-Headers -> Http headers like content-type, content-range.

See blow example code for php

header('Access-Control-Allow-Origin: *');  
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: Content-Type, Content-Range, Content-Disposition, Content-Description');

Below code shows how destination domain handles the Cross domain request.

<?php
header('Access-Control-Allow-Origin: *'); 
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
 
$_POST['extra']='POST Request from hayageek.com';
echo json_encode($_POST);
?>

note * : Cross site request working in all latest browsers including ie9.

If you are using IE8 means need to use content type as window.XDomainRequest.

Use the cross site request site plugin https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest.

When using XDomainRequest we need to follow 3 rules.

1. Use only neither GET or POST.

2. Use only neither HTTP or HTTPS.

3. Always asynchronous.


Sample Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta http-equiv="content-type" content="text/html; charset=UTF-8">
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.1/jquery.xdomainrequest.min.js"></script>
 
</head>
<body>
 
<input id="getdata" type="button"  >
 destination.php
<?php
header('Access-Control-Allow-Origin: *'); 
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
 
if(isset($HTTP_RAW_POST_DATA)) {
  parse_str($HTTP_RAW_POST_DATA,$arr); 
  $arr['extra']='1.POST Request from 17educations.com';
  echo json_encode($arr);
}
else
{
    $_POST['extra']='2.POST Request from 17educations.com';
    echo json_encode($_POST);
}
?>

 

Marimuthu:

View Comments