How to await the ajax request?

后端 未结 3 1106
终归单人心
终归单人心 2020-12-15 17:45

I am trying to write a JS code that will cancel the \"btn_submit\" buttons .onclick event if the given number already exists in the database. I use AJAX to query the DB for

3条回答
  •  独厮守ぢ
    2020-12-15 18:24

    Using async: false is an extremely bad idea, and defeats the whole purpose of using AJAX at the first place — AJAX is meant to be asynchronous. If you want to wait for a response from your script when you make the AJAX call, simply use deferred objects and promises:

    var validation = function () {
        var numberCheck = $.ajax({
            url: 'php/SeeIfNumberExists?number=' + $('#number_inp').val(),
            type: "GET"
        });
    
        // Listen to AJAX completion
        numberCheck.done(function(html) {
            var numOfRows = parseInt(html),
                textAreaList = $('.text_input'),
                finished = false;
    
            // Rest of your code starts here
            try {
                document.getElementById('failure').hidden = true;
            }
            catch(e) {
                console.log(e.message);
            }
    
            // ... and the rest
        });
    
    }
    
    // Bind events using jQuery
    $('#btn_submit').click(validation);
    

    I see in your code that you are using a mixture of both native JS and jQuery — it helps if you stick to one :)

提交回复
热议问题