-1

I know this question has been asked a million times but i just cant seem to make it work. Can someone let me know what I'm doing wrong.

Here's my code:

$('#frm').submit(function(event) {
    event.preventDefault();
    var formData = $(this).serialize();
    var email = $('input#email').val();
    if (email == '') {
        alert('Please enter your email address');
        $('input#email').focus();
        return false;
    } else {
        $.post('http://www.domain.com/', formData, function() {
            $('#frm').submit();
        });
    }
});
user2402492
  • 65
  • 1
  • 2
  • 10

3 Answers3

1

You can submit the FORM using DOM node submit method:

$.post('http://www.domain.com/', formData, function() {
    this.submit(); // 'this' not '$(this)'
}.bind(this)); // 'bind' to set relevant context, or use jq $.proxy(handler, this) to support older browsers
A. Wolff
  • 74,033
  • 9
  • 94
  • 155
  • this didn't work...the data gets posted just fine but the form doesn't submit to the action. I also meant to put $('#frm').submit() and not $(this).submit(). – user2402492 Jul 13 '15 at 17:25
  • It works for me using `bind(this)` and `this.submit();` – A. Wolff Jul 13 '15 at 17:34
0

This code does not make sense

    $.post('http://www.domain.com/', formData, function() {
        $(this).submit();
    });

you are posting and then, when the request returns with success, you are trying to call submit on the form again?

by the way, this in that context refers to the jqXHR object of the Ajax call and not to the form. See $(this) inside of AJAX success not working

Community
  • 1
  • 1
jperelli
  • 6,988
  • 5
  • 50
  • 85
0

As most of the answers said, this is not a reference to the form. Then you will need to create a reference for it as follows (see that var). HOwever that is only needed if you want to use it later in the success callback:

$('#frm').submit(function(event) {

    // Create a reference to your form
    var that = this;

    event.preventDefault();
    var formData = $(this).serialize();
    var email = $('input#email').val();
    if (email == '') {
        alert('Please enter your email address');
        $('input#email').focus();
        return false;
    } else {
        $.post('http://www.domain.com/', formData, function() {

            // On success response do your stuff here and 
            // submit to your 'own domain'  
            // In case you don't have the action attr, give a value to this var.
            var url = $(that).attr('action'); 
            $.post(url, formData, function() {
                // On success response do your stuff here
            });
        });
    }
});
leo.fcx
  • 6,137
  • 2
  • 21
  • 37