Function $.getJSON returns Undefined

Asked

Viewed 225 times

3

I’m having problems with a system that downloads the photo of 10 artists from a TOP 10. Follows the function:

function baixarCapa(capa) {
   $.getJSON("https://ajax.googleapis.com/ajax/services/search/images?callback=?", {
       q: '"' + capa + '"',
       v: '1.0'
   }, function(data) {
       return data.responseData.results[0].url;
   });
}

And further down:

showTopMusicas: function(){
    this.ajax('callCustomApi', ['getTop'], function(dados) {
        if (!dados || !dados.length) {
            return;
        }

        var html = '';
        capa = '';

        for (var i=0; i< dados.length; i++) {
            var nome = CentovaApi.formataNomeMusica(dados[i]);
            if (!nome) {
                continue;
            }

            capa = nome.split('/').pop();

            console.log(baixarCapa(capa));

            html += '<tr>';
            html += '<td>' + baixarCapa(capa) + '</td>';
            html += '<td>' + (i+1) + 'º</td>';
            html += '<td>' + nome.split('/').pop() + '</td>';
            //html += '<td>' + dados[i].count + '</td>';
            html += '</tr>';
        }
        $('#table_top_musicas').find('tbody').html( html );
    }, true);
},

Everything works, with this exception of the covers, appears only undefined.

1 answer

4


Its function baixarCapa returns undefined because you do not specify any return on it. You specify return on a callback passed to her, but he only runs later (it is asynchronous), and it is not possible to capture their return.

How you only get the data on that callback, need to use them right there, either directly, or calling another function and passing this data forward. And so you can’t mount the HTML the way you’re doing, which expects the cover to be available already. What you can do is reserve a seat for the cover in HTML, but only put the image later.

For example, you can do so:

baixarCapa(capa, i);
html += '<td data-capa="' + i + '"></td>';

With a function like this:

function baixarCapa(capa, item) {
   $.getJSON("https://ajax.googleapis.com/ajax/services/search/images?callback=?", {
       q: '"' + capa + '"',
       v: '1.0'
   }, function(data) {
       var url = data.responseData.results[0].url;
       $('[data-capa=' + item + ']').html('<img src="' + url + '">');
   });
}
  • IT WORKED ON TIME! You are champion friend. Thank you very much.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.