Petruza
Petruza

Reputation: 12256

Submitting an HTML form with jQuery doesn't work

TL;DR: I try to submit the form with jQuery but it doesn't work.

I need to do an ajax call when a user submits a form. The action of the form is outside my site, so I need to trap the form submission at this point before it's actually submitted.
This did work at some point, but now it doesn't, for some reason I can't figure out, I compared the commits before and after it stopped working and there was no code change so I don't know what it may be.
The form is a regular one, with POST method, an action, nothing strange.
Any ideas?

The idea is that when the user submits the form the submit handler prevents the regular submit and does the Ajax call.
When the AJAX call returns, the submit event is called again, this time the handler does nothing and doesn't prevent the regular submit, returns true, so it should submit the form to its action URL, but it doesn't happen.

<script>
var do_ajax_submit = true;

function manual_submit() {
    do_ajax_submit = false;
    $("form#lead_subscribe").submit();
}

$(function(){
    $("form#lead_subscribe").submit( function( ev )
    {
        var das = do_ajax_submit;
        if( do_ajax_submit )
        {
            do_ajax_submit = false;
            ev.preventDefault();

            $.ajax({
                url: "/someAjaxCall",
                method: "POST",
            })
            .always( function() {
                manual_submit();
            });
            return false;
        }
        return true;
    });
});
</script>

Upvotes: 0

Views: 72

Answers (1)

Roamer-1888
Roamer-1888

Reputation: 19298

It's not clear why the code should have worked, then stopped working.

One thing is for certain. By triggering form submission with the native formNode.submit instead of jQuery's $("form#lead_subscribe").submit();, the submission will not be re-intercepted by the event handler. Therefore the do_ajax_submit flag is unnecessary and the javascript cleans up significantly.

$(function() {
    $("form#lead_subscribe").on('submit', function(ev) {
        ev.preventDefault();
        var formNode = this;
        $.ajax({
            url: "/someAjaxCall",
            method: "POST"
        })
        .always(function() {
            formNode.submit(); // native .submit() will not be re-intercepted by this submit handler.
        });
    });
});

There's a chance that this clean-up will also fix the problem. Hard to say.

Upvotes: 1

Related Questions