1

I am successfully sending a getJson request to lastFM using the code below. This code is within a javaScript script. Can I get the result from the getJson function and use it outside of that function as a variable, i.e. in this within the calling javaScript?

function getArtistInfo(lastFmArtist) {

    var urlArtist = 'http://ws.audioscrobbler.com/2.0/?callback=?',
        params = {
            method:  "artist.getInfo",
            artist: lastFmArtist,
            format:  "json",
            api_key: "xxxxxxxxxx"
        };

    $.getJSON(urlArtist, params, function(data) {

        var myartist = data.artist.bio.summary;

    });
}

alert(myartist);
Mark Hildreth
  • 42,023
  • 11
  • 120
  • 109
David T
  • 13
  • 3
  • You need to use it inside the callback. Not outside. –  Jul 11 '13 at 17:47
  • 1
    Not entirely true, @CrazyTrain. He could use promises for this. – holographic-principle Jul 11 '13 at 18:15
  • @finishingmove: That's the same as using the result in a callback. Please don't try to correct me. You've already shown in your now deleted answer that you don't understand how it works. –  Jul 11 '13 at 18:17
  • Nope, it's not the same. – holographic-principle Jul 11 '13 at 18:20
  • @finishingmove: You keep changing your comment. Yes, it's the same. Only difference is the location of the callback. –  Jul 11 '13 at 18:21
  • @CrazyTrain As you can see, I do in fact know how it works. The context of the question just escaped me (I couldn't see the trees from the forest etc.). You were unnecessarily rude though. But let's put it behind us. – holographic-principle Jul 11 '13 at 18:25

3 Answers3

2

You could use a callback

function isFunction(object) {
  return (typeof object == 'function');
}

function getArtistInfo(lastFmArtist, callback) {

  var urlArtist = 'http://ws.audioscrobbler.com/2.0/?callback=?',
  var params = {
        method:  "artist.getInfo",
        artist: lastFmArtist,
        format:  "json",
        api_key: "xxxxxxxxxx"
  };

  $.getJSON(urlArtist, params, function(data) {
    var myartist = data.artist.bio.summary;
    if (isFunction(callback))
    {
      callback(myartist);
    }
  });
}

function getArtistInfoComplete(myartist )
{
  alert(myartist);
}

Then call it

getArtistInfo(lastFmArtist, getArtistInfoComplete);
Erik Philips
  • 53,428
  • 11
  • 128
  • 150
0

Try this way:

 $.ajax({
      type:"GET",
      url:"file.php",
      success:function(){
           // get your php file returned values
      },
      error:function(){
           // error message
      }
 });

Try to do all the coding based on the returned values inside you success function. In this way you do not even need to use global variables. If you try to access returned values outside of success you will get nothing.

Brian
  • 4,958
  • 8
  • 40
  • 56
-1

Sure.

So first, a variable outside the scope of the callback will help you out, instead of assigning myartist in the callback, you can assign it to a a variable that will exist outside the function.

var myartist;
function getArtistInfo(lastFmArtist) {

    var urlArtist = 'http://ws.audioscrobbler.com/2.0/?callback=?',
    params = {
        method:  "artist.getInfo",
        artist: lastFmArtist,
        format:  "json",
        api_key: "xxxxxxxxxx"
    };

    $.getJSON(urlArtist, params, function(data) {
      myartist = data.artist.bio.summary.toString();
    });
}

but it would also be nice to know if it worked or not, so you would want to have another global that would track if the callback has hit.

Using internet services like this, mostly will return instantly when your online, but it is always good to check to be sure that it worked before attempting to use the variable in the callback.

You might also want to look in to promise functions, as in the comments below.

nycynik
  • 7,371
  • 8
  • 62
  • 87
  • 1
    How would you use that? Namely, how does the caller know he can already use the value? – John Dvorak Jul 11 '13 at 17:49
  • 1
    Not to mention that returning anything via global variables is a bad idea – John Dvorak Jul 11 '13 at 17:50
  • well you can use a watch, added it as a comment. That way you would know when it returns, if it returns. You might also need some additional logic to show something while its pending. – nycynik Jul 11 '13 at 17:51
  • This is just a really bad answer. Who gave it +1? –  Jul 11 '13 at 17:52
  • 1
    Ew. Polling a global variable is a bad idea, and `Object.watch` is a firefox-specific thing. – John Dvorak Jul 11 '13 at 17:53
  • @CrazyTrain I gave it a +1. It's the only way to expose a variable to an outer scope. It doesn't have to be global. Just an outer scope. Combining this with a promise pattern (like jQuery's Deferred object) is a good way to do things. – Paul Jul 11 '13 at 17:54
  • The polyfill for `Object.watch` won't work in IE – John Dvorak Jul 11 '13 at 17:54
  • Im not sure what you would recommend to use? You dont need to set up a global, or just set the variable on the page immediately in the callback. I guess it depends on what your using it for, and how often it chagnes. – nycynik Jul 11 '13 at 17:55
  • @Paulpro: If you use a promise, you don't need this at all. No, this isn't good. –  Jul 11 '13 at 17:55
  • @Paulpro no. Exposing a variable is fine. Telling your caller to watch it is not. Exposing a variable by a library function is not fine either. This looks quite library-ish (residing in an app-wide scope) – John Dvorak Jul 11 '13 at 17:55
  • @Paulpro there should be no _need_ to "export" a variable like this, especially not from a callback. You never know when the callback finishes and if you can use the variable. – John Dvorak Jul 11 '13 at 17:57
  • @JanDvorak That's what the promise pattern is for. It allows you to know when to callback is finished and you can use the variable. it would look like `promise = $.getJson(...)`. With promise also declared in the outer scope. Then `promise.done(function(){ // use myartist here });` – Paul Jul 11 '13 at 17:59
  • What's that Angular.js thing you've added a link to? – John Dvorak Jul 11 '13 at 18:00
  • @Paulpro this is fine. But, you don't export the promise from within the success callback. You need to set it right away, and then there's no reason to "export" variables like this. – John Dvorak Jul 11 '13 at 18:01
  • @Jandvorak I was responding to you, you did not like the ff link, I'm trying to give a link to a general page that talks about watches in JavaScript. I should also add a link for promises. – nycynik Jul 11 '13 at 18:14
  • Thanks for all the replies guys - I will give it a go starting with the "How to return the response from an AJAX call?" suggestion first. – David T Jul 12 '13 at 08:11