How to send an ajax form in yii2

2019-04-06 19:22发布

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.

标签: yii2
2条回答
叼着烟拽天下
2楼-- · 2019-04-06 19:24

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;
    })
查看更多
祖国的老花朵
3楼-- · 2019-04-06 19:26

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.

查看更多
登录 后发表回答