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.
Using Ajax With Yii. If you're just beginning with Ajax and want to start slow, the Yii Playground has two simple examples of Ajax that may be helpful for you to review. One changes text on a page via Ajax, and another loads the response to a form on the same page, both without refreshing, and each includes detailed code samples.
The action first creates an EntryForm object. It then tries to populate the model with the data from $_POST, provided in Yii by yii\web\Request::post () . If the model is successfully populated (i.e., if the user has submitted the HTML form), the action will call validate () to make sure the values entered are valid.
This code will validate your form in actionValidate () and. For submitting your form via AJAX use beforeSubmit event. In your javascript file write: $ (document).on ("beforeSubmit", "#my-form-id", function () { // send data to actionSave by ajax request. return false; // Cancel form submitting. });
Before submitting with ajax: Check if error exits. After submitting: Display error of field under field's input if the server responses unsuccess saving result. Show activity on this post. This is your form in view. I prefer use different actions for validation and saving. You can join them into single method. In validation action you should write.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With