0

Possible Duplicate:
How to return the value of a function after the result of an ajax call has come?

I have one function that use to count the quantity of item in my controller.

function GetQtyItem() {
  var qty;
  var urlQuantity = "Quotation/CountQuantity";
  $.getJSON(urlQuantity, function (quantity) {
      qty = quantity.ja;
  });
  alert(qty); //3
  return qty;
}

I included the file name with the correct part, and called this function in another view of my asp.net mvc project :

<script language="javascript" type="text/javascript">
  var i = GetQtyItem();
  alert(i);
</script>

But the result in the alert dialog is Undefined.

Could any one tell me, how can I alert it with the correct value(3). Thanks in advanced.

Community
  • 1
  • 1
Nothing
  • 2,644
  • 11
  • 64
  • 115

1 Answers1

1

$.getJSON is an AJAX request... which takes time. You must wait for the data to come back, and then alert the result.

Try this:

var qty, i;
function GetQtyItem() {
  var urlQuantity = "Quotation/CountQuantity";
  return $.getJSON(urlQuantity, function (quantity) {
      qty = quantity.ja;
      alert('Request is done');
  });
}

i = GetQtyItem();
i.done(function() {
  alert("Quantity is " + qty);
});
Ryan Wheale
  • 26,022
  • 8
  • 76
  • 96