Mustard
Mustard

Reputation: 1840

input type="submit" instead of input type="button" with AJAX?

I have an AJAX form I'm setting up, using an <input type="button"> with a jQuery .click action being set.

The problem is, because there is no <input type="submit"> in the form, the form doesn't submit in a traditional way, so form validators don't always work, and pressing the enter button does nothing.

If I DO add a submit input, when it's clicked (or enter is hit, etc.), the page reloads as if it is not an AJAX form.

What am I missing here?

Upvotes: 8

Views: 9408

Answers (2)

Robert Koritnik
Robert Koritnik

Reputation: 105029

Rather change form's submit behaviour and keep your <input type="submit"> button as well:

$("form").submit(function(e){
    e.preventDefault();
    // do ajax submition
    $.ajax({
        url: "SomeURL",
        type: "POST",
        data: $(this).serializeArray(),
        success: function(data, status, xhr) {
            // do the success stuff
        },
        error: function(xhr, status err) {
            // do the error stuff
        }
    });
});

Advantage: The good thing is this will work in all cases when you hit ENTER on any of the form's input elements or click the submit button. It will always work without exception.

Upvotes: 4

Kranu
Kranu

Reputation: 2567

Use a submit button. The submit button will be more compatible in terms of default browser behavior, such as pressing enter. Then, on the submit event, just cancel the form submission and run your AJAX code.

<form onsubmit="return false;">
<!--Blah Blah Blah-->
<input type="submit">
</form>

If you're using jQuery, you can use a more "clean" method

$('#form_id').bind('submit',function(e) {
  e.preventDefault(); //Will prevent the submit...
  //Add additional code here
});

Upvotes: 13

Related Questions