Ajax Form Submit

Framework7 allows automatically send form data using Ajax.

It could be done in two ways

  • when user submits it (when he clicks on "submit" button) or when "submit" event triggered on form programmatically
  • when user change any form field or when "change" event triggered on form (or form field) programmatically

Send form data on submit

To enable Ajax form and send data automatically on submit, we just need to add "ajax-submit" class to form:

     <form action="send-here.html" method="GET" class="ajax-submit">
    ...
</form> 

And when user will submit this form, it automatically will be sended using Ajax with the following rules:

  • Form data will be sended to the file/url specified in form's "action" attribute

  • Request method will be the same as specified in form's "method" attribute

  • Content type will be the same as specified in form's "enctype" attribute. By default (if not specified), it is application/x-www-form-urlencoded

Send form data on input change

Mostly we don't use "submit" buttons in apps, so in this cases we need to submit form data when user changes any form fields. For this case we need to use "ajax-submit-onchange" class:

     <form action="send-here.html" method="GET" class="ajax-submit-onchange">
    ...
</form> 

And when user will change any form filed, form data automatically will be sended using Ajax with the same rules as in previous case.

Ajax submit event

Sometimes we need to get actual XHR repsonse from the file/url where we send form data with Ajax. We can use special event for that:

Event Target Description
form:success Form Element<form class="ajax-submit"> Event will be triggered after successful Ajax request
form:beforesend Form Element<form class="ajax-submit"> Event will be triggered right before Ajax request
form:error Form Element<form class="ajax-submit"> Event will be triggered on Ajax request error
var myApp = new Framework7();
 
var $$ = Dom7;
 
$$('form.ajax-submit').on('form:success', function (e) {
  var xhr = e.detail.xhr; // actual XHR object
 
  var data = e.detail.data; // Ajax response from action file
  // do something with response data
});