jQuery AJAX cross domain
Here are two pages, test.php and testserver.php.
test.php
<script src="scripts/jq.js" type="text/javascript"></script>
<script>
$(function() {
$.ajax({url:"testserver.php",
success:function() {
alert("Success");
},
error:function() {
alert("Error");
},
dataType:"json",
type:"get"
}
)})
</script>
testserver.php
<?php
$arr = array("element1",
"element2",
array("element31","element32"));
$arr['name'] = "response";
echo json_encode($arr);
?>
Now my problem: when both of these files are on the same server (either localhost or web server), it works and alert("Success")
is called; If it is on different servers, meaning testserver.php on web server and test.php on localhost, its not working, and alert("Error")
is executing. Even if the URL inside ajax is changed to http://domain.com/path/to/file/testserver.php
Solution 1:
Use JSONP.
jQuery:
$.ajax({
url:"testserver.php",
dataType: 'jsonp', // Notice! JSONP <-- P (lowercase)
success:function(json){
// do stuff with json (in this case an array)
alert("Success");
},
error:function(){
alert("Error");
}
});
PHP:
<?php
$arr = array("element1","element2",array("element31","element32"));
$arr['name'] = "response";
echo $_GET['callback']."(".json_encode($arr).");";
?>
The echo might be wrong, it's been a while since I've used php. In any case you need to output callbackName('jsonString')
notice the quotes. jQuery will pass it's own callback name, so you need to get that from the GET params.
And as Stefan Kendall posted, $.getJSON() is a shorthand method, but then you need to append 'callback=?'
to the url as GET parameter (yes, value is ?, jQuery replaces this with its own generated callback method).
Solution 2:
JSONP is a good option, but there is an easier way. You can simply set the Access-Control-Allow-Origin
header on your server. Setting it to *
will accept cross-domain AJAX requests from any domain. (https://developer.mozilla.org/en/http_access_control)
The method to do this will vary from language to language, of course. Here it is in Rails:
class HelloController < ApplicationController
def say_hello
headers['Access-Control-Allow-Origin'] = "*"
render text: "hello!"
end
end
In this example, the say_hello
action will accept AJAX requests from any domain and return a response of "hello!".
Here is an example of the headers it might return:
HTTP/1.1 200 OK
Access-Control-Allow-Origin: *
Cache-Control: no-cache, no-store, max-age=0, must-revalidate
Content-Type: text/html; charset=utf-8
X-Ua-Compatible: IE=Edge
Etag: "c4ca4238a0b923820dcc509a6f75849b"
X-Runtime: 0.913606
Content-Length: 6
Server: WEBrick/1.3.1 (Ruby/1.9.2/2011-07-09)
Date: Thu, 01 Mar 2012 20:44:28 GMT
Connection: Keep-Alive
Easy as it is, it does have some browser limitations. See http://caniuse.com/#feat=cors.