How to Send Cross Domain AJAX Request with jQuery

In this tutorial, I explained how to send Cross Domain AJAX Request with jQuery and PHP. Different methods of handling cross domain AJAX requests are covered in this article.

Cross-domain AJAX request is possible in two ways
1). Using JSONP
2). Using CORS (Cross-origin resource sharing)

1).Using JSONP

We can send cross domain AJAX requests using JSONP. Below is the simple JSONP Request:

$.ajax({
    url : "http://hayageektest.appspot.com/cross-domain-cors/jsonp.php",
    dataType:"jsonp",
});

function mycallback(data)
{
	alert("Here: "+data.name);
}

jsonp.php response is:

mycallback({"name":"Ravishanker","age":32,"location":"India"})

when the JSONP request is successful, mycallback function is called.

If you want the function handling automatically, you can use the below approach. In this case, you need not have any extra function. You can get the server response in success callback

$.ajax({
	    url : "http://hayageektest.appspot.com/cross-domain-cors/jsonp.php",
	    dataType:"jsonp",
	    jsonp:"mycallback",
	    success:function(data)
	    {
	    	alert("Name:"+data.name+"nage:"+data.age+"nlocation:"+data.location);
	    }
	});

jsonp.php source code:

<?php
	$callback ='mycallback';

	if(isset($_GET['mycallback']))
	{
		$callback = $_GET['mycallback'];
	}	
	$arr =array();
	$arr['name']="Ravishanker";
	$arr['age']=32;	
	$arr['location']="India";	

    echo $callback.'(' . json_encode($arr) . ')';

?>

This works in all the browsers but the problem is: JSONP supports only GET method. POST method is not allowed.
[demo url1=”http://hayageek.com/examples/jquery/cross-domain-cors/jsonp.php&#8221; title1=”Cross Domain AJAX Request with JSNOP”]

 

2).Uing CORS (Cross-origin resource sharing)

Browser does not allow cross domain AJAX requests due to security issues. Cross-domain requests are allowed only if the server specifies same origin security policy.
Read more about Cross-origin resource sharing (CORS) : Wiki

To enable CORS, You need to specify below HTTP headers in the server.
Access-Control-Allow-Origin – Name of the domain allowed for cross domain requests. * indicates all domains are allowed.
Access-Control-Allow-Methods – List of HTTP methods can be used during request.
Access-Control-Allow-Headers – List of HTTP headers can be used during request.

In PHP, you can use the below code to set the headers.

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 the sample code which handles Cross Domain AJAX POST requests: post.php

<?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);
?>

CORS works fine in all the latest browsers, but IE8 and IE9 don’t support this.
[demo url1=”http://hayageek.com/examples/jquery/cross-domain-cors/cors.php&#8221; title1=”Cross Domain AJAX Request with CORS”]

 

IE8,IE8 handles AJAX request using window.XDomainRequest. So We can use this jQuery plugin: https://github.com/MoonScript/jQuery-ajaxTransport-XDomainRequest
In order to use XDomainRequest in IE, request must be:
a). Only GET or POST
When Posting, the data will always be sent with a Content-Type of text/plain
b). Only HTTP or HTTPS
Protocol must be the same scheme as the calling page
c). Always asynchronous

Follow the steps for XDomainRequest:
Step 1). Add the script in <head>

<script type='text/javascript' src="http://cdnjs.cloudflare.com/ajax/libs/jquery-ajaxtransport-xdomainrequest/1.0.1/jquery.xdomainrequest.min.js"></script>

Step 2). You need to set contentType value text/plain in $.ajax request.

	var contentType ="application/x-www-form-urlencoded; charset=utf-8";

	if(window.XDomainRequest) //for IE8,IE9
		contentType = "text/plain";

	$.ajax({
		 url:"http://hayageektest.appspot.com/cross-domain-cors/post.php",
		 data:"name=Ravi&age=12",
		 type:"POST",
		 dataType:"json",	
		 contentType:contentType,	 
		 success:function(data)
		 {
		 	alert("Data from Server"+JSON.stringify(data));
		 },
		 error:function(jqXHR,textStatus,errorThrown)
		 {
		 	alert("You can not send Cross Domain AJAX requests: "+errorThrown);
		 }
		});

[demo url1=”http://hayageek.com/examples/jquery/cross-domain-cors/cors-ie.php&#8221; title1=”Cross Domain AJAX Request with CORS”]

Below is the sample code, works in all the browsers.

<!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"  value="Send X GET"/>
<input id="postdata" type="button" value="Send X POST" />

<script>
$(document).ready(function()
{
	var contentType ="application/x-www-form-urlencoded; charset=utf-8";

	if(window.XDomainRequest)
		contentType = "text/plain";

	$("#postdata").click(function()
	{
		$.ajax({
		 url:"http://hayageektest.appspot.com/cross-domain-cors/post.php",
		 data:"name=Ravi&age=12",
		 type:"POST",
		 dataType:"json",	
		 contentType:contentType,	 
		 success:function(data)
		 {
		 	alert("Data from Server"+JSON.stringify(data));
		 },
		 error:function(jqXHR,textStatus,errorThrown)
		 {
		 	alert("You can not send Cross Domain AJAX requests: "+errorThrown);
		 }
		});

	});

	$("#getdata").click(function()
	{
		$.ajax(
		{
		 url:"http://hayageektest.appspot.com/cross-domain-cors/get.php?name=Ravi&age=32",
		 dataType:"json",
		 contentType:contentType,
		 success:function(data)
		 {
		 	alert("Data from Server"+JSON.stringify(data));
		 },
		 error:function(jqXHR,textStatus,errorThrown)
		 {
		 	alert("You can not send Cross Domain AJAX requests : "+errorThrown);
		 }
		});

	});

});
</script>
</body>
</html>

post.php source code:

<?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 hayageek.com';
  echo json_encode($arr);
}
else
{
	$_POST['extra']='2.POST Request from hayageek.com';
	echo json_encode($_POST);
}
?>