0

Consider the following code:

$('.saveCheck').on('click',function()
   {
        var frm = $(this).parents('form');
        frm.submit(function (ev)
        {   
            $.ajax
                ({
                    type: frm.attr('method'),
                    url: frm.attr('action'),
                    data: frm.serialize(),
                    success: function (data)
                    {alert("hooray!");}
            });
            ev.preventDefault();
        });  
   });

This will not submit my form, however:

frm.submit();

On its own works fine, but wont have any of the AJAX goodness.

Is there any glaringly obvious reason for this?

Aphire
  • 1,479
  • 22
  • 50
  • 1
    http://stackoverflow.com/questions/1960240/jquery-ajax-submit-form – Xavjer Sep 23 '15 at 11:20
  • Wouldn't say this is a duplicate, because that link may have great examples for the future, but doesn't explain why the issue happend – Aphire Sep 23 '15 at 11:28

1 Answers1

3

You code is set up so that when saveCheck is clicked it will bind a submit handler so that when the form is later submitted, it will call the Ajax function.

It sounds like what you want to do is to just run the Ajax function when saveCheck is clicked. Get rid of your submit handler binding entirely.

$('.saveCheck').on('click', function(ev) {
    var frm = $(this).parents('form');
    $.ajax({
        type: frm.attr('method'),
        url: frm.attr('action'),
        data: frm.serialize(),
        success: function(data) {
            alert("hooray!");
        }
    });
    ev.preventDefault();
});

That said, you should probably be using a submit handler on the form instead of a click handler on a button.

Quentin
  • 800,325
  • 104
  • 1,079
  • 1,205