How to prevent form from submitting with AJAX validation

Toma Tomov

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
    })
Quentin

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.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

Prevent form from submitting until validation

AJAX not submitting the form after validation

How do prevent page reload/refresh from submitting ajax called form and get the texts and uploaded file/image?

How to get Ajax to use CSS form validation before submitting

Prevent form from submitting jQuery

Form validation is not working in Ajax form submitting

How to prevent the modal from closing after submitting form

Angular 2: How to prevent a form from submitting on keypress enter?

how to prevent form from submitting only if it catches error

IE - How to disable validation detection from input after submitting the form?

Prevent form from submitting if form is empty

prevent input from submitting when empty (not in form)

jQuery, prevent form from submitting, then continue

Prevent users from submitting a form by hitting Enter

prevent form from submitting if invalid on css class

Prevent Ajax form double submitting using form tokens with php

How to prevent form validation errors to be removed from the DOM with Parsleyjs

How to prevent fake form validation

jQuery Validation and submitting a form

How to prevent enter key from submitting a form but still allow enter to work?

In AngularJS, how can I prevent a nested <button> from submitting the form that it's in?

How to clean form after submitting ajax?

Prevent enter from submitting from without it being in a form

Form not submitting after form validation

Angular 2 prevent enter from submitting in template-driven form

submitting form with ajax and php

Submitting a form with ajax in Wordpress

Submitting a form with ajax and laravel

Prevent an input from submitting

TOP Ranking

  1. 1

    Failed to listen on localhost:8000 (reason: Cannot assign requested address)

  2. 2

    How to import an asset in swift using Bundle.main.path() in a react-native native module

  3. 3

    Loopback Error: connect ECONNREFUSED 127.0.0.1:3306 (MAMP)

  4. 4

    pump.io port in URL

  5. 5

    Spring Boot JPA PostgreSQL Web App - Internal Authentication Error

  6. 6

    BigQuery - concatenate ignoring NULL

  7. 7

    ngClass error (Can't bind ngClass since it isn't a known property of div) in Angular 11.0.3

  8. 8

    Do Idle Snowflake Connections Use Cloud Services Credits?

  9. 9

    maven-jaxb2-plugin cannot generate classes due to two declarations cause a collision in ObjectFactory class

  10. 10

    Compiler error CS0246 (type or namespace not found) on using Ninject in ASP.NET vNext

  11. 11

    Can't pre-populate phone number and message body in SMS link on iPhones when SMS app is not running in the background

  12. 12

    Generate random UUIDv4 with Elm

  13. 13

    Jquery different data trapped from direct mousedown event and simulation via $(this).trigger('mousedown');

  14. 14

    Is it possible to Redo commits removed by GitHub Desktop's Undo on a Mac?

  15. 15

    flutter: dropdown item programmatically unselect problem

  16. 16

    Change dd-mm-yyyy date format of dataframe date column to yyyy-mm-dd

  17. 17

    EXCEL: Find sum of values in one column with criteria from other column

  18. 18

    Pandas - check if dataframe has negative value in any column

  19. 19

    How to use merge windows unallocated space into Ubuntu using GParted?

  20. 20

    Make a B+ Tree concurrent thread safe

  21. 21

    ggplotly no applicable method for 'plotly_build' applied to an object of class "NULL" if statements

HotTag

Archive