tags:

views:

289

answers:

1

Hi, I asked a related question previously, but the question I need answering now seems to have gone on a bit of a specific tangent so I thought it would be better to make a new question.

I am trying to prevent form submission until all ajax calls on a page have returned successfully.

I have a simple test for this (add 1 to a counter when call is started, subtract 1 on success).

I belive I should be able to do:

// can we submit yet?
  $('#checkoutform').submit(function() {
    if (ajaxcallcounter == 0) {
      return true;
    }
    return false;
  });

to prevent form submission until the counter has reached zero (all calls are complete) but for some reason this does not seem to be 100% effective.

I don't know if this is a red herring but all the reports from customers who have managed to check out before the calls have completed have been using Mac Safari (this could just be a coincidence though)

You can see the code in action here - try changing delivery country to fire off some ajax calls. The submit button in bottom right should be disabled while the counter is > 0.

+1  A: 

Define var ajaxcallcounter = 0; outside of your function. Put it at the top of the JavaScript file to make it a global variable.

In general, you can make sure you have complete control over an event by stopping its propagation. Each event handler has an implicit parameter, usually defined as "e" or "event", and you can call preventDefault() on that, like so:

$('#checkoutform').submit(function(e) {
    e.preventDefault();
    if (ajaxcallcounter == 0) {
      return true;
    }
    return false;
  });
Tom
He's already doing that. It's not global, but it's in the closure formed by his jQuery "ready" function where all the event handlers are defined. Also, he almost certainly does not want to always "prevent default" on every event.
Pointy
Yeah, I know it's in the scope of the stuff that's currently defined, but that style always gives me hives. It's too easy to define a function somewhere else (e.g., another js include) and wonder why things aren't working properly.Not saying the questioner would want to prevent all default event handling, just in this case where they want explicit control over the behavior.
Tom
Hi Tom, Pointy - I don't understand preventDefault well enough to feel confident using it without some more explanation. In the example Tom provided, does preventDefault work in a different way to return false, or is this a 'belt and braces' approach?
Ashley