erik
erik

Reputation: 83

Using AJAX returned data into a variable

I have a simple AJAX call that is querying the Twitter API to return the number of times a URL has been tweeted. I'm trying to set that return value along with similar AJAXs calls from other social networks. I'm then want to add all the values together to get a 'sharing' total that will be used within HTML Page.

Here was what I was trying with my code:

var twitter = $.ajax({
        dataType: 'jsonp',
        url: 'http://cdn.api.twitter.com/1/urls/count.json',
        data: { url: shareUrl},
        async: 'false',
        success: function(data) {
            return data.count;
        }
    });

My goal is in then run a simple math function like this:

var total = twitter + facebook;

And then output that total to a DOM element.

When I run a console.log(twitter); I'm getting an object readystate but if I run a console.log of the count in the success function, I'm getting the correct number. Since this is going to be a very light page set 'async: false' hoping that it would return the value then move on to the next function. But not matter what I try and I can't get the value out of the AJAX function. Where have I gone wrong or what do I need to modify?

Upvotes: 0

Views: 235

Answers (1)

devnull69
devnull69

Reputation: 16544

This is a perfect example for using deferreds in jQuery. With deferreds you can create callbacks that will be called after a series of asynchronous actions finished (and not only one as for usual callbacks).

Then you can calculate the total of the results coming from the "inner" callbacks

EDIT: Now more elegant without globals!

function Twitter() {
   var dfd = $.Deferred();
   $.ajax({
      ...
      success: function(data) {
         dfd.resolve(data.count);
      }
   });
   return dfd.promise();
}

function Facebook() {
   var dfd = $.Deferred();
   $.ajax({
      ...
      success: function(data) {
         dfd.resolve(data.count);
      }
   });
   return dfd.promise();
}

$.when(Twitter(), Facebook()).then(function(twitter, facebook) {
   alert('The total is ' + (twitter+facebook));
}

Upvotes: 2

Related Questions