How to handle jQuery cross domain AJAX request

jquery

Cross Domain jQuery AJAX request

AJAX Requests are only possible if port, protocol and domain of sender and receiver are equal, means that the following below listed requests won’t work-

    Requesting https://serverA.com/a.php from http://serverA.com/b.php
    Requesting http://subdomain.serverA.com from http://serverA.com
    Requesting http://serverA.com:5000 from http://serverA.com

Here in this tutorial we will cover the ways to handle this restriction. First lets look at the code, which was working fine when the jQuery AJAX call was within the application (same port, protocol and domain). But when the target system got migrated to another system it didn’t worked.

Not Working code (cross domain issue) –

function ping(pingURL) {
    	jQuery.ajax({ type : "GET",
    		url : pingURL,
           	contentType: "application/json; charset=utf-8",
           	dataType: "json",
           	success: function(data){
           		var result = data.response;
    			//do something here
		},
            	error:function(jqXHR, textStatus, errorThrown){
			//handle error here
	    	}
        });
}

Working code to handle Cross Domain issue

function ping(pingURL) {
    	jQuery.ajax({ type : "GET",
    		url : pingURL,
           	crossDomain: true,
           	contentType: "application/json; charset=utf-8",
           	dataType: "jsonp",
           	jsonpCallback: "jsonpresp",
           	success: function(data){
           		var result = data.response;
    			//do something here
            	},
            	error:function(jqXHR, textStatus, errorThrown){
            		//handle error here
            	}
        });
}

To handle the the cross domain jQuery AJAX issue we introduced few changes

crossDomain: true

crossDomain (default: false for same-domain requests, true for cross-domain requests)
Type: Boolean
If you wish to force a crossDomain request (such as JSONP) on the same domain, set the value of crossDomain to true.

dataType: "jsonp"

“jsonp”: Loads in a JSON block using JSONP. Adds an extra “callback” to the end of your URL to specify the callback. Disables caching by appending a query string parameter, “_=[TIMESTAMP]”, to the URL unless the cache option is set to true.

Basically, the client tells the server the callback function for the response. The server then wraps the response in this callback function.

To specify the callback method name to the server we used the parameter otherwise a random method name will get generated.

jsonpCallback: "jsonpresp"

With JSONP, when the server receives the “callback” parameter (here in this case jsonpresp), it wraps up the result a little differently, returning something like this:

jsonpresp({ foo: 'bar' });

This will now invoke the method you specified. So, in your page, you define the callback function:

jsonpresp = function(data){
  alert(data.response);
};

And now, when the script is loaded, it’ll be evaluated, and your function will be executed. And, cross-domain requests works!

So the final working code for jQuery AJAX request

function ping(pingURL) {
    	jQuery.ajax({ type : "GET",
    		url : pingURL,
           	crossDomain: true,
           	contentType: "application/json; charset=utf-8",
           	dataType: "jsonp",
           	jsonpCallback: "jsonpresp",
           	success: function(data){
           		var result = data.response;
    			//do something here
            	},
            	error:function(jqXHR, textStatus, errorThrown){
            		//handle error here
            	}
        });
}

jsonpresp = function(data){
  alert(data.response);
};