Shackrock
Shackrock

Reputation: 4701

Call a function after a form is submitted using jquery

I'm trying to call a function after any form with the class shown below is submitted. However, this doesn't seem to be working for me (the form submits, but the submit button remains active and the loading image is not shown).

$(document).ready(function() {
    $('.uniForm').submit(function() {
      $('#loadingImage').show();
      $(':submit',this).attr('disabled','disabled');
      return true;
    });
});

Here's some HTML:

<form class="uniForm" id="formABC">
//...form.... here
</form>

<img src="loadimage.gif" style="display: none;" id="loadingImage">

does anyone see anything inherently wrong with this that would be preventing things from working correctly?

I have a feeling it's just not being called correctly. Can I call it myself via some HTML like this?

<button type="button" class="primaryAction" alt="Submit Form" onclick="$('#formABC').submit();">Submit Form</button>

Upvotes: 3

Views: 30820

Answers (4)

Mojtaba Rezaeian
Mojtaba Rezaeian

Reputation: 8736

There is a jQuery plugin named jQuery Form Plugin which helps to submit your form from ajax without refresh and then you can do the rest of actions on its success (which occurs exactly after successful form submission):

    jQuery(document).ready(function () {
        jQuery('#my_submit_button').click(function (e) {
            jQuery(this.form).ajaxSubmit({
                target: false,
                success: function ()
                {
                    your_other_stuff();
                },
            });
        });
    });
    function your_other_stuff(){
        // rest of things
    }

Upvotes: 1

TomekBrzyn
TomekBrzyn

Reputation: 1

Try something else:

$('.uniForm input[type=submit]').click(function(){
    $('.uniForm').submit();
    //doStuffafterSubmit
});

Upvotes: 0

Boaz
Boaz

Reputation: 20230

Following your comment, it seems the binding of the handler function to the submit event might be taking place before the form element has been loaded into the DOM.

Ideally, you should bind event handlers only after the DOM has finished loading.

For example:

$(document).ready(function() {
    $('.uniForm').submit(function() {
        ...
    });
});

Upvotes: 5

user1236048
user1236048

Reputation: 5602

Put an id on the submit input/button and try this:

$('#mySubmitButton').click(function(e) {
    e.preventDefault();
    e.stopPropagation();
    $(this).attr('disabled','disabled');
    $('#loadingImage').show(function() {
        $(this.form).submit();
    });

});

Upvotes: 1

Related Questions