JQuery Ajax Race Condition?

I have code below JavaScript that iterates through a list of text fields on a page. It takes the text in the text box as a price, sends it to the server via AJAX GET and receives the parsed double back from the server. If any of the returned prices is less than the existing price, the form should not be submitted.

The problem is that the form is submitted before all AJAX requests are completed due to non-blocking immediate response to Ajax calls. I need to set up the wait () function (or callback when all Ajax methods are complete), but don't know how to do it with jQuery.

Any suggestions?

// .submitForm is a simple button type="button", not type="submit" $(".submitForm").click(function(e){ var submittable = validatePrices(); if (submittable) { $("#myForm").submit(); } }); function validatePrices() { var submittable = true; $(".productPrice").each(function(){ var $el = $(this); $.ajax({ type: "POST", url: "/get_price.jsp", async: false, dataType: "html", data: "price=" + $el.val(), success: function(data) { var price = new Number(data.split("|")[1]); var minPrice = new Number($el.data("min-price")); if (price < minPrice) { $el.addClass("error"); $(".dynamicMessage").show().addClass("error").append("<p>ERROR</p>"); submittable = false; } } }); return submittable; }); } 
+4
source share
2 answers

You are already using synchronous AJAX (a really bad idea for your user), so this is not a problem. The problem is that you need to undo the default action in the send handler:

 $(".submitForm").click(function(e){ var submittable = validatePrices(); e.preventDefault(); // this line if (submittable) { $("#myForm").submit(); } }); 

Using a synchronous HTTP request to your server for each individual field will make your site terribly slow. You will have to check the parameters on the server again when you submit the form anyway, so it would be much better to just check and return an error.

edit - now that the situation is clearer, I think the way to continue is to completely stop checking the AJAX check. What for? Well, even if you perform these tests, you still need to do almost the same validation tests when the form is actually submitted. You cannot rely on really valid JavaScript validation code, as in any other form validation script. If you still validate while submitting the form, it will save a ton of HTTP requests to just do it all at once.

+4
source

You do not cancel submitting the form. You have to work strictly with ajax callbacks (if you want to use them asynchronously, that would be nice).

 $(".submitForm").click(function(e){ e.preventDefault(); validatePrices().done(function () { /* ajax success function here */ if (submittable) { $("#myform").trigger('submit'); } } }); function validatePrices() { var checks = []; $(".productPrice").each(function(){ var $el = $(this); checks.push($.ajax({ /* snip */ }); return $.when.apply(null, checks); } 
+1
source

All Articles