How to implement cross domain ajax calls on web pages using jsonp and CORS in both the client and the server.
For example, on www.mytestsite.com, to make an ajax call to www.otherdestinationserver.com, how to achieve either using JSONP or CORS implementation?
Finally I found some solutions after researching and going through all the other posts. I am writing answers for both the approaches.
1. Using JSONP only without CORS:
If using JSONP, there is always a need to make server side change to get json response with acallbackmethod. Also thecallbackmethod must be present in thejavascriptto execute. So in the below example, when we call the destination url, if we get the response asmyCallBackMethod({ "customerData": { "name": "testName", "age": 26 } }), then we must have ajavascript methodwith the namemyCallBackMethod. Using jsonp,cookies can also be shared across domains
callback method used in this example is myCallBackMethod. This name can be anything, except the names in javascript and the response jsonp string must matchclient / javascript:
function makeTheCall(queryString) {
var destinationUrl = "www.otherdestinationserver.com";
$.ajax({
type: 'GET',
url: destinationUrl + queryString,
dataType: 'jsonp',
jsonpCallback: 'myCallBackMethod',
async: false, // this is by default false, so not need to mention
crossDomain: true // tell the browser to allow cross domain calls.
// success: successResopnse, jsonpCallback will call the successCallback
// error: failureFunction jsonp does not support errorCallback. So cannot use this
});
}
window.myCallBackMethod = function(data) {
successResponse(data);
}
successResponse = function(data) {
//functionality goes here;
}
// the json response from the server when calling the url must be in the below format only.
myCallBackMethod({ "customerData": { "name": "testName", "age": 26 } })
2. Using CORS only without JSONP and WITHOUT URL REWRITES:
If using CORS, there is always aneed to make changes on server and client/javascript. In this approach,no need to get any callbackmethod as part of json response. Responsemust be a pure json. However, make appropriate code changes on the destination server to let the requests pass through. So need to set theheaderin theresponseobject.
Client / javascript:
function makeTheCall(queryString) {
var destinationUrl = "www.otherdestinationserver.com";
$.ajax({
type: 'GET',
url: destinationUrl + queryString,
dataType: 'json', // use json only, not jsonp
crossDomain: true, // tell browser to allow cross domain.
success: successResopnse,
error: failureFunction
});
}
successResponse = function(data) {
//functionality goes here;
}
failureFunction = function(data) {
//functionality goes here;
}
On server, add the below header.
httpServletResponse.setHeader("Access-Control-Allow-Origin", "*"); // Here need to give the origin url (the url in the address bar of the page which is making request). Using * means allow any value
On client / javascript:
xhrFields: {
'withCredentials': true // tell the client to send the cookies if any for the requested domain
}
On server:
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
Access-Control-Allow-Credentials in response, there is a restriction on the value for the header Access-Control-Allow-Origin. It should never be * if we want to use Access-Control-Allow-Credentials header. Hence give exact domain name.Update on server:
httpServletResponse.setHeader("Access-Control-Allow-Origin", "www.mytestsite.com"); // Give the origin url (the url in the address bar of the page which is making request).
final client / javascript: (CORS only approach)
function makeTheCall(queryString) {
var destinationUrl = www.otherdestinationserver.com;
$.ajax({
type: 'GET',
url: destinationUrl + queryString,
dataType: 'json', // use json only, not jsonp
crossDomain: true, // tell browser to allow cross domain
xhrFields: {
'withCredentials': true // tell the client to send the cookies if any for the requested domain
},
success: successResopnse,
error: failureFunction
});
}
successResponse = function(data) {
//functionality goes here;
}
failureFunction = function(data) {
//functionality goes here;
}
Final Server code: (CORS only approach)
httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
httpServletResponse.setHeader("Access-Control-Allow-Origin", "www.mytestsite.com");
3. Using CORS only WITH A URL REWRITE FILTER setting RESPONSE HEADERS:
If the application is using a url rewrite filter, (mostly all the web applications does), this would give much easier implementation. Instead of following the Final Server code: (CORS only approach) in the approach 2 above, follow the below url to change at xml ( url rewrite filter).
How to set origin or referer value which we got from request into the response-header using urlrewritefilter
Same code pasted below for quick reference.
<rule enabled="true" match-type="regex">
<name>Enabling CORS Headers</name>
<from>^/path/someMorePath.*$</from>
<condition name="origin" operator="equal">([a-z]+)</condition>
<set type="response-header" name="Access-Control-Allow-Origin">%1</set>
<set type="response-header" name="Access-Control-Allow-Credentials">true</set>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With