Ajax with JQuery: 200 ok, but not "success"

tkm256 picture tkm256 · Jan 30, 2011 · Viewed 34.2k times · Source

I'm trying to use AJAX to send a query to Google Books and display the results on my website. I'm using JQuery to send the request and handling the response, like so:

var query = [formatted input from a form];
var URL = "http://books.google.com/books/feeds/volumes?q="+query+"&start-index=1&max-results=5";

$.ajax({
    type: "GET",
    url: URL,
    dataType: "xml",
    success: function(data, status){
        alert(status);
    }
});

Currently, I just have the script alerting "success" if a response is received. If I use my script to send that query to a local page for testing, this works just fine. But when I set the URL to the Google one listed above, as instructed on the Developer API page, I never see the alert. According to Firebug, I am receiving a response and a status of 200 ok as I should, but it's not getting to that "success" path. Does anyone know why?

Edit: I should add that if I follow the URL directly, to http://books.google.com etc. with some random q, it displays the feed XML with no problems, so the query is not the issue.

Answer

Jason LeBrun picture Jason LeBrun · Jan 30, 2011

You can't make cross-domain requests using XMLHttpRequest under the standard browser security settings. One possible solution is to write a local proxy function (assuming you can create server-side code) that forwards the query to the external site, and then returns the response.

Edit: It looks like Google provides a JavaScript API as well. I would assume that they've crafted in such a way to avoid the cross-domain XHR issue.

http://code.google.com/apis/books/docs/js/devguide.html#execute

Edit: The JavaScript API for books was deprecated. While it's no longer practically useful, you can see the original referenced documentation text via the Wayback Machine archive: http://web.archive.org/web/20120414070427/http://code.google.com/apis/books/docs/js/devguide.html#execute