-1

I can't get the returned data of an GET AJAX call. The call gets the data properly but I can't get the data I need in a variable and return it.

I know that the AJAX calls are asynchronous and I've tried different approaches but failed.

   function getQuantity(Id) {
        var productQuantity = null;
        $.ajax({
            type: "GET",
            dataType: "json",
            url: "/Product/ProductData/" + Id,
            success: function (response) {
                productQuantity = response.QuantityInStock;
                console.log("in call: ", productQuantity);
            }
        });
        console.log("in return: ", productQuantity);

        return productQuantity;
   }

This is what I get in the console:

in return: null

in call: 2724 -> this is the right value

Hope you can help.

lok30
  • 114
  • 9

1 Answers1

0

You need to return the AJAX call and add asycn: false option

function getQuantity(Id) {
        var productQuantity = null;
        return $.ajax({
            type: "GET",
            dataType: "json",
            async: false,
            url: "/Product/ProductData/" + Id,
            success: function (response) {
                console.log("response:  ", response);
            }
        }).responseText;
   }
Nedko Dimitrov
  • 4,350
  • 3
  • 28
  • 30
  • @AlonEitan from 3 years I am not using jQuery at all – Nedko Dimitrov Nov 27 '18 at 08:31
  • @AlonEitan go do better than me and explain him how to use callbacks, promises and async/await – Nedko Dimitrov Nov 27 '18 at 08:33
  • It's all there in the duplicate, this is very common question on SO and I see it being asked almost every day – Alon Eitan Nov 27 '18 at 08:36
  • 1
    @AlonEitan yes, you're right, just when it comes to old technologies everything nowadays is actually a duplicate of some SO question. And note that he is not asking "How to do AJAX calls", but his question is more like "Come solve my problem, because I am junior and my senior is gonna hit me if I ask him another basic question" :D – Nedko Dimitrov Nov 27 '18 at 08:44