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
Browser security prevents making an ajax call from a page hosted on one domain to a page hosted on a different domain; this is called the "same-origin policy".
For Microsoft Azure, it's slightly different.
Azure has a special CORS setting that needs to be set. It's essentially the same thing behind the scenes, but simply setting the header joshuarh mentions will not work. The Azure documentation for enabling cross domain can be found here:
https://docs.microsoft.com/en-us/azure/app-service-api/app-service-api-cors-consume-javascript
I fiddled around with this for a few hours before realizing my hosting platform had this special setting.
I had to load webpage from local disk "file:///C:/test/htmlpage.html", call "http://localhost/getxml.php" url, and do this in IE8+ and Firefox12+ browsers, use jQuery v1.7.2 lib to minimize boilerplate code. After reading dozens of articles finally figured it out. Here is my summary.
Here is an example jQuery ajax call with some debug sysouts.
Use JSONP.
jQuery:
PHP:
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).You can control this via HTTP header by adding Access-Control-Allow-Origin. Setting it to * will accept cross-domain AJAX requests from any domain.
Using PHP it's really simple, just add the following line into the script that you want to have access outside from your domain:
Don't forget to enable mod_headers module in httpd.conf.
I use Apache server, so I've used mod_proxy module. Enable modules:
Then add:
Finally, pass proxy-url to your script.