I need to send data from html form in my yii2 app. I need to use ajax to send data from this form and get the response from server to output it. In yii 1.0 i was using very useful helper ajaxSubmitButton and i can't find how to send data from form with ajax in yii2. Could you tell me how to do it? Is there any article about it?
Thank you.
Yii ActiveForm supports JavaScript events in many stages of its life cycle. You can use beforeSubmit
event for achieving 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 submission of the form by returning false
from the event callback.
reload the form when the submit fails for a 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;
})