Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to send an ajax form in yii2

Tags:

yii2

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.

like image 770
Samat Zhanbekov Avatar asked Jan 24 '15 16:01

Samat Zhanbekov


People also ask

How do I use Ajax with Yii?

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.

How does the action create an entryform in Yii?

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.

How to validate and submit form via AJAX with JavaScript?

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. });

What should I do before and after submitting Form with Ajax?

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.


1 Answers

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.

like image 115
Saranga A Avatar answered Oct 04 '22 09:10

Saranga A