Pregunta

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
¿Fue útil?

Solución

$.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);
});

Otros consejos

.post() is an asynchronous request. that means JS doesn't wait for it to finish, it just move on to next instruction.

You need to put console.log("After", vm_good); inside your post callback like this-

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();

        console.log("After", vm_good); // you should put this here
    }, 'json');
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top