简体   繁体   中英

How to prevent form from submitting with AJAX validation

How to prevent form from submit when I am using ajax to validate it. The problem is that the ajax is asynchronous and the real result ( which is false in my case ) comming later. Is making Ajax to sync is the right way? This is my piece of code:

$('#w0').on('beforeSubmit', function(e){
        let loadDate = $('#dstrequest-load_date').val()
        let shippingDate = $('#dstrequest-shipping_date').val()
        let requestId = '".($model->isNewRecord ? 0 : $model->id)."'
        let trucks = $('.container-items_truck').find('.truck-item')
        let ids = []
        let result = true
        $.each(trucks, function(){
            let id = $(this).find('select').first().val()
            if(ids.indexOf(id) === -1)
                ids.push(id)
        })
        $.ajax({
            method: 'post',
            url: '/erp/distribution/dst-vehicle/check-truck-engage-date',
            data: {
                load_date: loadDate,
                shipping_date: shippingDate,
                trucks: ids,
                request_id: requestId
            }
        })
        .done(function(data){
            let selects = $('select[name$=\"[truck_id]\"]')
            $.each(selects, function(){
                let val = $(this).val()
                if(data.indexOf(val) !== -1){
                    $('#w0').yiiActiveForm('updateAttribute', $(this).attr('id'), ['".Yii::t('distribution', 'distributionCore.busy_truck')."'])
                    result = false
                }                   
            })
        })
        .always(function(data){
            let transfer_wrapper = $('.transfer-wrapper')
            $.each(transfer_wrapper, function(){
                if($(this).is(':visible')){
                    let fields = $(this).find('input, select')
                    $.each(fields, function(){                  
                        if($(this).val() == ''){
                            let id = $(this).attr('id')
                            $('#w0').yiiActiveForm('updateAttribute', id, ['" . Yii::t('distribution', 'distributionCore.please_fill_the_field') . "'])
                            result = false
                        }
                    })   
                }
            })      
        })
        // HERE THE RESULT SHOULD BE FALSE BECAUSE OF THE AJAX VALIDATION BUT IT'S TRUE BECAUSE OF THE ASYNC BEHAVIOUR.
        return result
    })

Is making Ajax to sync is the right way?

No. Synchronous HTTP requests from JS are deprecated. Never use them.

You need to either:

Always halt

Always prevent normal form submission.

After you have validated the input, using Ajax, use JS to resubmit the form (without repeating validation).

Validate in advance

Do the validation as the data is entered, field by field.

Hopefully, the Ajax will be finished by the time the last field is completed and the form submitted.

That at that point, if the Ajax isn't finished, you either have to risk submitting the form without knowing the result of the Ajax validation or fall back to the first option I suggested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM