Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 373
Jonah H. Avatar asked Nov 24 '10 06:11

Jonah H.


2 Answers

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
});
like image 90
Kranu Avatar answered Oct 12 '22 22:10

Kranu


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.

like image 43
Robert Koritnik Avatar answered Oct 12 '22 23:10

Robert Koritnik