简体   繁体   中英

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?

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
});

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM