Reputation: 1772
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?
Upvotes: 3
Views: 21614
Reputation: 5525
If you can not control the sever side, you can work around like me on
Client side only.
If you can control server side, you can use server side solution. I am not discus it here.
Only on client side, work around is
use dataType: 'jsonp',
async function get_ajax_data(){
var _reprojected_lat_lng = await $.ajax({
type: 'GET',
dataType: 'jsonp',
data: {},
url: _reprojection_url,
error: function (jqXHR, textStatus, errorThrown) {
console.log(jqXHR)
},
success: function (data) {
console.log(data);
// note: data is already json type, you just specify dataType: jsonp
return data;
}
});
} // function
Upvotes: -1
Reputation: 1772
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 acallback
method. Also thecallback
method must be present in thejavascript
to 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 method
with 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 match
client / 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 callback
method 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 theheader
in theresponse
object.
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).
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>
Upvotes: 12