I have problems with receiving json through ajax, the error is below. According to the information I’ve found so far regarding the error this seems to be some kind of cross domain issue, but I have no idea of what that means and how to solve it.
There may be an issue with the response header (I have created the API myself and have no experiences since before), however a 200 OK is received if accessing the url directly in the browser.
If accessing the url directly in the browser valid json is shown, so that shouldn’t be the problem.
How can this be solved?
Note: The url goes to an Apache server, not a file that has been the case for 95% of the questions here on Stack that I’ve read about the issue.
Error in inspector:
XMLHttpRequest cannot load http://localhost/api/v1/products?_=1355583847077.
Origin null is not allowed by Access-Control-Allow-Origin.
Error: error
The code:
$.ajaxSetup ({
url: "http://localhost/api/v1/products", // <--- returns valid json if accessed in the browser
type: "GET",
dataType: "json",
cache: false,
contentType: "application/json"
})
$.ajax({
success: function(data){
console.log("You made it!");
},
error: function(xhr) {
console.log("Error: " + xhr.statusText);
}
}).done(function(data){
console.log(data);
})
Params
_ 1355583610778
Headers
Response Headers:
Connection Keep-Alive
Content-Length 3887
Content-Type application/json
Date Sat, 15 Dec 2012 14:50:53 GMT
Keep-Alive timeout=5, max=100
Server Apache/2.2.14 (Unix) DAV/2 mod_ssl/2.2.14 OpenSSL/0.9.8l PHP/5.3.1 mod_perl/2.0.4 Perl/v5.10.1
X-Powered-By PHP/5.3.1
Request Headers:
Accept application/json, text/javascript, */*; q=0.01
Accept-Encoding gzip, deflate
Accept-Language sv-SE,sv;q=0.8,en-US;q=0.5,en;q=0.3
Connection keep-alive
Host localhost
Origin null
User-Agent Mozilla/5.0 (Macintosh; Intel Mac OS X 10.7; rv:17.0) Gecko/17.0 Firefox/17.0
Response
Nothing here…
Try and implement some form of JSONP mechanism. If you’re using PHP it could be something as simple as this…
All this would do is check for a
$_GETvar called callback, and then wrap the output in a function call – taking the$_GET['callback']name as a function name.Then your AJAX call becomes something like this…
When jQuery is given
'jsonp'as a dataType/contentType it will take care of providing a callback function name for you – and setting the callback function up etc; meaning you don’t have to do anything really!From the jQuery documentation:
Source
In closing; JSONP is going to be your best bet – I’ve included PHP code in the off chance that your server side script is using PHP; if not then the principles are the same. The jQuery/client side stuff stays the same regardless of server side technologies though. (in general)
Good luck 🙂