5

Is it possible to stop a form from submitting and then resubmitting the same form from within the success of an ajax call?

At the moment it gets to the success bit but it doesn't resubmit the form which should submit and redirect the user to the http://example.com website.

Thank you very much for any help in advance

If it's not possible to do it this way, is there another way of getting it to work?

$(document).ready(function() {
    $('form').submit(function(e) {
        e.preventDefault();

        $.ajax({
            url: $('form').attr('action'),
            type: 'post',
            data: $('form').serialize(),
            success: function(data) {
                if (data == 'true')
                {
                    $('form').attr('action', 'http://example.com');
                    $('form').unbind('submit').submit(); // mistake: changed $(this) to $('form') - Problem still persists though it does not resubmit and redirect to http://example.com
                }
                else
                {
                    alert('Your username/password are incorrect');
                }
            },
            error: function() {
                alert('There has been an error, please alert us immediately');
            }
        });
    });
});

Edit:

Stackoverflow posts checked out for the code below:

I just thought I'd mention I have also tried this code without avail.

var ajaxSent = false;
$(document).ready(function() {
    $('form').submit(function(e) {

        if ( !ajaxSent)
            e.preventDefault();

        $.ajax({
            url: $('form').attr('action'),
            type: 'post',
            data: $('form').serialize(),
            success: function(data) {
                if (data == 'true')
                {
                    alert('submit form');
                    ajaxSent = true;
                    $('form').attr('action', 'http://example.com');
                    $('form').submit();
                    return true;
                }
                else
                {
                    alert('Your username/password are incorrect');
                    return false;
                }
            },
            error: function() {
                alert('There has been an error, please alert us immediately');
                return false;
            }
        });
    });
});

I have also tried this code without any luck as well.

$(document).ready(function() {
    $('form').submit(function(e) {
        e.preventDefault();

        $.ajax({
            url: $('form').attr('action'),
            type: 'post',
            data: $('form').serialize(),
            success: function(data) {
                if (data == 'true')
                {
                    $('form').attr('action', 'http://example.com');
                    $('form').unbind('submit').submit();
                    return true;
                }
                else
                {
                    alert('Your username/password are incorrect');
                    return false;
                }
            },
            error: function() {
                alert('There has been an error, please alert us immediately');
                return false;
            }
        });
    });
});
Community
  • 1
  • 1
adamj
  • 4,672
  • 5
  • 49
  • 60
  • 1
    this will most probably submit form infinitely. At first ajax submits form, on success it again goes through same ajax and on success again .. then again.. then again. – SachinGutte May 07 '13 at 09:39
  • @SachinG Why? They're removing (well, attempting to remove) the `submit` event handler before submitting the form the second time. – Anthony Grist May 07 '13 at 09:40
  • @AnthonyGrist but after unbinding, same handler is getting called because submit is followed by it. Won't it? Or i'm wrong ? – SachinGutte May 07 '13 at 09:42
  • @SachinG You're wrong. When the event handler is unbound, it's gone - it can't then be called by anything. – Anthony Grist May 07 '13 at 09:46
  • @adamj Can you provide details about what *is* happening after the first submit. I'd expect the first submit to be prevented, an AJAX call to be made, then a second submit to occur. Is that second submit occurring but triggering another AJAX call? Is it not happening at all? – Anthony Grist May 07 '13 at 09:49
  • @Anthony Grist It gets to the success without a hitch (tested it by using alerts) but then when it gets to the submit you'd expect it to submit the form which would lead it to http://example.com but nothing happens at all edit: By nothing at all I mean it doesn't run the .submit() or anything at all, nothing happens period – adamj May 07 '13 at 09:58
  • 1
    You can post your own answer, but as an answer, not by editing your original question! – enb081 May 07 '13 at 11:06

3 Answers3

15

Solution was quite simple and involved adding and setting async to false in .ajax(). In addition, I have re-worked the code to work of the submit button instead which submits the form when the AJAX passes successfully.

Here is my working code:

$(document).ready(function() {
    var testing = false;
    $('#btn-login').on('click', function() {
        $.ajax({
            url: $('form').attr('action'),
            type: 'post',
            data: $('form').serialize(),
            async: false,
            success: function(data) {
                if (data == 'true')
                {
                    testing = true;
                    $('form').attr('action', 'https://example.com');
                    $('form').submit();
                }
                else
                {
                    alert('Your username/password are incorrect');
                }
            },
            error: function() {
                alert('There has been an error, please alert us immediately');
            }
        });

        return testing;
    });
});
adamj
  • 4,672
  • 5
  • 49
  • 60
8

It's no good practice to reselect all form tags throughout your code, what if you have multiple forms on the page? Also you'd better use .on() and .off() with jQuery.

$(document).ready(function() {
    $('form').on('submit', function(e) {
        e.preventDefault();

        // cache the current form so you make sure to only have data from this one
        var form = this,
            $form = $(form);

        $.ajax({
            url: form.action,
            type: form.method,
            data: $form.serialize(),
            success: function(data) {
                if (data == 'true')
                {
                    $form.attr('action', 'http://example.com').off('submit').submit();
                }
                else
                {
                    alert('Your username/password are incorrect');
                }
            },
            error: function() {
                alert('There has been an error, please alert us immediately');
            }
        });
    });
});
Simon
  • 7,182
  • 2
  • 26
  • 42
  • I'll give the .on() a shot see if that helps it. Regards not using the form tag, you're right, but in this case there will always be only the single form on the page. If it were any other case I would have slapped an ID attribute on the form and targeted it on that. – adamj May 07 '13 at 10:08
  • Even if you add an ID I'd still cache the object, simply for performance and code consistency. – Simon May 07 '13 at 11:25
3

In one line you use $('form') to select the form to change its action, but then you use $(this) to try to select that same form. I would guess that this inside the callback function isn't what you expect it to be, and is something other than your form (possibly the window object).

Just chain the calls:

$('form').attr('action', 'http://example.com').unbind('submit').submit();
Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
  • $(this) was actually supposed to be $('form'), this was a mistake which i had corrected in the code forgot to edit it in the stackoverflow post before i posted. Do'h. Regards the chaining, yea i know i can do it all in one go, I just prefer doing it separately for better overview – adamj May 07 '13 at 09:50
  • @adamj Honestly, the code looks correct to me with that change. You'll probably have to debug it, see what's being returned by the AJAX request, see what parts of the code are firing, etc. – Anthony Grist May 07 '13 at 09:53
  • AJAX is fine no problems there. When it runs the .submit() for the first time it hits the AJAX it gets back the data and hits the success. It should then .unbind() the form from the submit and resubmit the form but the resubmit never occurs. By default you would instantly know whether it worked by it submitting the form which would lead to http://example.com, but this doesn't happen. – adamj May 07 '13 at 10:04