Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submit a HTML 5 Form with AJAX?

I got some trouble submitting a form with ajax.

Since HTML5 Form already have "required" validation within the input tag, there is no need for javascript validation check. However, because of that, I don't know how to use javascript(jQUERY) to submit a form AFTER those validation checks have been passed. In other words, how do I know whether the validations checks has passed or not?

e.g : ??condition?? (What condition should I put before loading the submitted page)? ("div").load(finishSubmittingForm.html) )};

Any idea?

Thanks

like image 603
Victorgalaxy Avatar asked May 06 '11 23:05

Victorgalaxy


Video Answer


2 Answers

There are some API methods available. See developer.mozilla.org.

However, I would strongly advise you think carefully before relying on HTML5 validation. It definitely has some major drawbacks at this point in time, as it is still "in its infancy". I would say that for now, you would be better off using a JS validation library; jQuery Validation is excellent.

like image 129
simshaun Avatar answered Sep 26 '22 06:09

simshaun


from specification:

If the user presses the submit button. The browser has to first validate the form and if the form is valid, the submit event is fired.

This means, that you can simply hook into the form's submit event and start your ajax.

$('form').bind('submit', function(){
    //Ajax implementation here
});

But, Opera has a really nasty bug here. Opera first fires the submit event and then validates the form.

You can workaround this, by using the validation methods of HTML5. This would look like this:

$('form').bind('submit', function(){
    if(!this.checkValidity || this.checkValidity()){
        //Ajax implementation here
    }
});

About the current state of the HTML5 form spec. There are some parts, that should extend the form spec. The features, which are currently implemented in FF4 and others (FF4 has less form features than Opera and Chrome, but very good implementation) are stable enough for production.

If you want to use HTML5 forms in all browsers, I would suggest the webshims HTML5 forms polyfill. It not only polyfills the incapable browsers, but also fixes some bugs in browsers, which haven't implemented the form feature according to the spec. For example, the Opera bug mentioned above will be automatically fixed.

like image 36
alexander farkas Avatar answered Sep 23 '22 06:09

alexander farkas