javascriptjqueryjquery-events.post

jQuery events after the $.post is happening before the request finishes


I have the following code, and for some odd reason, the order in which the events are happening is not making sense to me. Is there anyway in which I can make it so that it goes in the order?

var vm_good = false;
console.log("Before", vm_good);
    $.post("./ajax/call_price", {id: product_id}, function(data){
        $.each(data, function(key, value){
           $(".unit-price span").html(value);
        });
        vm_good = true;
        console.log("Inside", vm_good);
        enableNext();
    }, 'json');
    console.log("After", vm_good);

And the results on the console window is:

>Before false
>After false
>Inside true
>window.vm_good // I called it manually after the page loaded
>>true

Solution

  • $.post is a shorthand of $.ajax. A in AJAX stands for asynchronous, so interpreter will execute next command, while $.post will run your event handler (function(data)) when your request is done. If your request wouldn't be asynchronous then your browser would freeze, because it would wait for your request to finish.

    You can use $.when(deffered).then(handler) to execute code after your request is done:

    var callPrice = $.post("./ajax/call_price", {id: product_id}, function(data){
        $.each(data, function(key, value){
           $(".unit-price span").html(value);
        });
        vm_good = true;
        console.log("Inside", vm_good);
        enableNext();
    }, 'json');
    
    $.when(callPrice).then(function () {
        console.log("After", vm_good);
    });