Ajax requests are only possible when the protocol, domain and port number are the same. But sometimes you want to do Ajax calls to a different domain for example when you are creating a shared service that people should be able to call using Ajax or when you are developing locally and you are testing on a remote server. There are multiple ways to get around this restriction for example by using CORS, an iFrame or JSONP. In my last project I got around the restriction using JSONP, so I will explain that here. See links for more information about solving it using CORS.
I am currently working on a mobile application with Phonegap that is running on my local machine. This application retrieves information from a remote server which is my own server but on a different location. I use jQuery to request this information:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function api_call(action,data,onready,method) { if (typeof(data) == 'undefined') data = {}; if (typeof(method) == 'undefined') method = "GET"; var url = "http://apache.test.noveesoft.com/i-trail.nl/backend/public/api/v1/"+action; $.ajax({ url: url, data: data, type: method, dataType: 'jsonp' }).done(function( response ) { // done response = { isSuccess: (response.status == "OK"), connectionFailure: false, authorisationFailure: (response.status == "NOT_AUTHORIZED"), data: response.data}; if ((typeof(onready) != 'undefined') && (onready != null)) onready( response ); }).fail(function( status ) { // failed response = { isSuccess: false, connectionFailure: true,authorisationFailure: false, data: status}; if ((typeof(onready) != 'undefined') && (onready != null)) onready( response ); }); } |
The problem is that my remote machine has another domain name then my local. So making an Ajax request wont work. The solution is using dataType: ‘jsonp’ on your Ajax call. This will send an extra parameter called Callback to the server. On your server you need to respond properly:
1 2 3 4 |
// Laravel $response = json_encode($respondObject); $callback = Input::get('callback',null); return ($callback == null) ? $response : $callback . "(" . $response . ")"; |
Now both sessions and Ajax calls should work Cross Domain.