I am trying to call a jQuery GET request on the successful completion of a POST request. The functions work and the data is being fed through from the GET request, however, it is responding before the POST.
function getCartCount() {
var d = new Date().getTime();
$.get("/ajax/countCart.php", { "rand": d }, function(res) {
$("#view-cart").text(res);
alert(res);
});
}
$(".products form img").click(function() {
$.post("/ajax/addToCart.php", $(this).parent("form").serialize())
.done(function(data) {
alert(data);
})
.always(getCartCount());
});
The above code produces an alert box from the GET request first then an alert box from the POST which is not ideal as the value from the GET is dependent on the POST being completed first.
Please see http://www.cccomforts.co.uk/small-furries for the output.
.always(getCartCount());
^^
You are calling the function immediately and passing the return value to always
.
Remove the ()
to pass the function itself.
.always(getCartCount);
This is because you are not waiting for POST request to complete successfully. Do this -
$(".products form img").click(function() {
$.post("/ajax/addToCart.php", $(this).parent("form").serialize())
.done(function(data) {
alert(data);
getCartCount();
})
});