user1929437
user1929437

Reputation: 473

Javascript\Jquery How can i detect if the function is still running? or can i hook in to return event?

So let me describe standard situation: there's a form with multiple inputs (about 60-70). Each inputs needs to be validated. If its not valid it returns false. I need to protect form from multiclicking(multisubmitting) to prevent multiple AJAX requests with graphical feedback.

My solution is to invoke custom document event before AJAX request is sent which instantly creates div with width and height 100%, z-index 9998 which contains loading gif and some message. And on completion of AJAX request invoke another, which simply removes that element from DOM.

My question is: is that a valid solution? I mean, its a lot of form inputs and validation may be slower on older computers, which means it can take some time, before shield div is appended to the body and protects form from submitting. Can I simply listen to function and detect whether it returns something or not? In case of deffer my understanding that I need to resolve every time before it returns a value, which means 60-70 new lines of code, which is messy and undesirable.

Is there someone, who faced this problem before and resolve it with 100% accuracy and grace?

Upvotes: 3

Views: 1340

Answers (2)

zafus_coder
zafus_coder

Reputation: 4591

you first need to stop default behaviour on form submit then u have to check whether form input is valid , if yes then it goes to ajax call .

    $('#form').submit(    function(e){     

        e.preventDefault();
        var $form = $(this);

      // check if the input is valid
        if(! $form.valid()) return false;

       $.ajax({
            type: 'POST',
            url: 'add.php',
            data: $('#form').serialize(),
            success: function(response) {
                $("#answers").html(response);
            }

        });
    });

Upvotes: 0

Matthew Cox
Matthew Cox

Reputation: 13672

Don't rely on a "shielding div" to prevent muliple submits. Just hook into the submit event of the form check before submitting:

$('#myForm').submit(function() {
    if (!stillValidating())
       //submit form
    else
       //handle however you deem necessary.
});

Upvotes: 4

Related Questions