0

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?

2
  • The way I understand it is success is a callback, and fired outside of the scope of the question you are asking. How about success: function(data) { $('#twitter').html(data); } Commented Nov 15, 2012 at 21:53
  • @DarenSchwenke: No need for a global. But yes, something in the scope containing the call. Commented Nov 15, 2012 at 21:55

1 Answer 1

2

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));
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.