Sal P. Sal P. - 4 months ago 18
Ajax Question

Ajax call to API not working

I am trying to retrieve data from an API using Jquery's ajax(), but it doesn't work with this implemenation:



$.ajax('http://api.forismatic.com/api/1.0/?method=getQuote&format=json').done(function(data) {
alert(1);
alert(JSON.stringify(data));
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>





After running the code the alert function doesn't work, so I concluded that the success callback function isn't working, but I have no idea why.

Answer

After inspecting the server response headers, there is no Access-Control-Allow-Origin, this means that the server doesn't allow cross-origin access. Since you make a cross-origin HTTP request, your request will be rejected by the browser following the Same-origin policy:

The same-origin policy restricts how a document or script loaded from one origin can interact with a resource from another origin. It is a critical security mechanism for isolating potentially malicious documents.

Look at your console you will see the following error (Chrome):

XMLHttpRequest cannot load http://api.forismatic.com/api/1.0/?method=getQuote&format=json. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://s.codepen.io' is therefore not allowed access.

For more details please refer to: https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

Comments