How to submit ajax form in yii2

I need to send data from an html form to my yii2 application. I need to use ajax to send data from this form and receive a response from the server to output it. In yii 1.0, I used the very useful ajaxSubmitButton helper, and I cannot find how to submit form data using ajax in yii2. Could you tell me how to do this? Is there an article about this?

Thanks.

+8
yii2
source share
2 answers

Yii ActiveForm supports JavaScript events at many stages of its life cycle. You can use the beforeSubmit event to achieve what you are looking for. In JavaScript:

 $(document).ready( $('#myform').on('beforeSubmit', function(event, jqXHR, settings) { var form = $(this); if(form.find('.has-error').length) { return false; } $.ajax({ url: form.attr('action'), type: 'post', data: form.serialize(), success: function(data) { // do something ... } }); return false; }), ); 

Note that you can stop the normal presentation of the form by returning false from the event callback.

+10
source share

reload form when submit fails for server validation rule

 $form.on('beforeSubmit', function (event, jqXHR, settings) { if ($form.find('.has-error').length) { return false; } $.ajax({ url: $form.attr('action'), type: 'post', data: $form.serialize(), success: function (datos, status, xhr) { var ct = xhr.getResponseHeader("content-type") || ""; //fail server validation if (ct.indexOf('html') > -1) { if ($(datos).find(".has-error").length) { modal.modal('show'); modal.find(".modal-body").html(datos); } } //real success if (ct === "" || ct.indexOf('json') > -1) { modal.modal('hide'); } }, error: function (datos) { alert(datos.responseText); }, complete: function (datos) { console.log(datos); } }); return false; }) 
0
source share

All Articles