0

I am running into an issue where I need to use the data that I get back from my Ajax code and it is grabbing the variable before it returns, so I think I have to use Promises or a callback for this. I looked at all kinds of documentation and tutorials on Promises and it was all very confusing. I'm just sending back a single int with one ajax call. I think it should be very simple.

Here is my JS/JQuery:

$('.products').on('click', '.btnaddtocart', function (e) {
        var itemid = $(this).attr('name');
        var qty = $(this).prev('input').val();
        var qtyAvailable = $("#qty" + itemid).html();
        var qtyInCart = 0;
        $.ajax({
            url: '/Shop/getItemCountInCart',
            data: { id: itemid },
            success: function (result) {
                qtyInCart = result;
                console.log("result: " + result);
            }
        });
        console.log("qty in cart: " + qtyInCart);

qtyInCart is always 0 and result has the number but gets output after the qtyInCart.

dmikester1
  • 1,374
  • 11
  • 55
  • 113

1 Answers1

1

This is correct, you just have to put console.log("qty in cart: " + qtyInCart); and all code using qtyInCar in the success function.

You don't need to use Promises. But, since it is an asynchronous call and you have no idea when qtyInCart will be assigned, you must put all code involving this variable in the success function.