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

34,310

Solution 1

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

Solution 2

It's a cross-domain problem with ajax calls because browsers have a security model based on a domain policy.

if you don't wan to include the whole Google Books API, you can also use Google Ajax API with jsonp for cross-domain ajax calls.

Docs here:

http://code.google.com/apis/books/docs/js/jsondevguide.html#basic_query

jQuery example

var query = 'jquery';
var URL = 'https://ajax.googleapis.com/ajax/services/search/books?v=1.0&q=' + query;

$.ajax({
    type: 'GET',
    url: URL,
    dataType: 'jsonp',
    success: function( data, status ){
        alert( data.responseData.results.length + ' results found!' );
    },
    error: function() {
        alert( 'Something goes wrong!' );
    }
});

Ciao!

Share:
34,310
tkm256
Author by

tkm256

Updated on August 09, 2022

Comments

  • tkm256
    tkm256 almost 2 years

    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.