-1

So this is my controller action, it gets a double (average) from a service and returns it as a JSON

Controller name(Product)

[HttpGet]
public JsonResult getAvgRating(int productId)
{
    double average = new WCF_Ratings.WCF_RatingsClient().getAvgRating(productId);
    return Json(average, JsonRequestBehavior.AllowGet);
}

This is the jquery function which gets the data, the data is shown correctly in the alert

function getAvg() 
{
    $.getJSON("/Product/getAvgRating", { "productId": productId }, function (data) {
        alert(data);
        return data;
    });
}

When I try to read the data from outside the jquery function by calling the function getAvg() I get unidentified data in my alert window.

$("#testbutton").click(function () 
{
    var d = getAvg();
    alert(d);
});

Can someone tell me why this is happening?

David
  • 15,894
  • 22
  • 55
  • 66
enzoborgfrantz
  • 468
  • 3
  • 11

1 Answers1

0

AJAX is asynchronous - you need to use callbacks! Pass a callback into getAvg and pass that the data as a parameter:

function getAvg(callback) 
{
    $.getJSON("/Product/getAvgRating", { "productId": productId }, function (data) {

        callback(data);
    });
}

And call!

getAvg(function(avg) {
    alert(avg);
});
tymeJV
  • 103,943
  • 14
  • 161
  • 157
  • I'm not sure what's happening but it works, I'll read up on callbacks thanks for your help :) I will accept this answer in 7 minutes. – enzoborgfrantz Apr 26 '14 at 18:49
  • The `async` nature of Javascript is one of the hardest things for novices to wrap their head around. However, it is a fundamental aspect of the language that also shows up when dealing with any kind of `events` as well. – Jeremy J Starcher Apr 26 '14 at 20:20