0

I am not a seasoned Javascript programmer so may be there is something basic wrong here. I just want to write a function that makes an AJAX call to a WEBAPI and return the array back. But I am making some mistake with understanding variable scope.

function GetProductsOfAccount(AccountID) {
      var returnProducts;
      console.log("In GetProductsOfAccount");
      var serviceURL = productURI + "/GetProductsOfAccount/" + AccountID;
      console.log(serviceURL);
      $.ajax({
          type: "GET",
          datatype: "json",
          url: serviceURL,
          context: this,
          success: function (Products) {
              console.log("From AJAX" + Products);
              returnProducts = Products;

              //This correctly holds and shows all products
              console.log("Return Products 1 " + returnProducts);
          },
          error: function (x, y, z) {
              returnProducts = null;
              console.log("Error" + x + '\n' + y + '\n' + z);
          }
      });

     //This just shows undefined
      console.log(" Returned Products 2 " + returnProducts);
      return returnProducts;
  }

Why does the returnedProducts lose value at the end and what is the correct way to do such a thing?

user2645830
  • 362
  • 1
  • 6
  • 22

1 Answers1

0

Edit: yet slightly alternative syntax using jQuery deferred (I didn't see it in Arun's link):

var productsOfAccount = function (AccountID) {

  var serviceURL = productURI + "/GetProductsOfAccount/" + AccountID;

  return $.ajax({
      type: "GET",
      datatype: "json",
      url: serviceURL,
  }).promise();
}

var test = $.productOfAccount(20)

test.then(function(products){
          console.log("From AJAX" + products);
          returnProducts = Products;

          //This correctly holds and shows all products
          console.log("Return Products 1 " + returnProducts);
}); 

You can apply test.then multiple times for different purposes.

html_programmer
  • 18,126
  • 18
  • 85
  • 158