0

I am trying to put a url from an ajax response into a variable in jquery. I have written the following code:

var thumb = $.ajax({
        dataType: 'json',
        url: 'https://www.googleapis.com/books/v1/volumes?q=isbn:' + isbn,
        success: function(response){
            return $(response).volumeInfo.imageLinks.thumbnail;
        }}).responseText;

It was my understanding from looking at other answers that I must add .responseText at the end, or the code will continue without waiting for the ajax response. However, thumb variable remains undefined.

I tried implementing the following solution with relevant changes (As I am passing only one ISBN at a time, there shouldn't be an array. The response should contain only one imageLinks.thumbnail url), but I cannot seem to catch the response correctly.

I looked into other answers, especially this one, but I am still not clear about how to reach the ajax response.

Nimrod Yanai
  • 777
  • 2
  • 8
  • 30

1 Answers1

1

$.ajax is asynchronous, meaning the code will execute completely and the success callback will be fired at a later time.

var thumb is evaluated immediately. Do some reading on "callbacks" and "promises" to get more familiar with this topic.

A solution to your issue is:

function setThumbnail(thumbnail){
    // this will evaluate later, when the ajax returns success
    console.log('thumbnail gotten!');
    var thumb = thumbnail; // do something with in in this function
}
$.ajax({
    dataType: 'json',
    url: 'https://www.googleapis.com/books/v1/volumes?q=isbn:' + isbn,
    success: function(response){
        setThumbnail($(response).volumeInfo.imageLinks.thumbnail);
    }
});
// This line will evaluate immediately and carry on
console.log('ajax executed');

I threw in some logs for you to help you understand the order of execution here. I would also note that $(response) looks odd to me, without testing it I think it should probably be just response.volumeInfo....
console.log(response) in the success callback to make sure you understand what data you are getting back.

Jordan
  • 3,813
  • 4
  • 24
  • 33
  • This is great, but I need thumb outside the function. If I can't use var X = $ajax and return thumb from the function, how can I use it outside the function? – Nimrod Yanai Jun 19 '18 at 18:45
  • Do whatever you need to do with the thumbnail info inside of the setThumbnail function. – Jordan Jun 19 '18 at 19:00