How to wait for ajax request?

I am trying to write a JS code that cancels the "btn_submit" .onclick buttons if the given number already exists in the database. I use AJAX to query the database for a given number and determine if data should be sent to the .php site, which will ask a question. To determine this, I need the value of the numOfRows variable, but since I set it to AJAX, it will remain at 0. The validation () function will exit before my AJAX request completes, and this will cause a problem that will always indicate that the given number do not exist in the database (numOfRows will always remain at 0). How can I wait for the AJAX request to complete before comparing numOfRows with 0 in my final line of the validation () function? If the number already exists in the database, I need to return false to this line:

document.getElementById ("btn_submit"). onclick = validation;

Thank!

var textAreaList;
var numOfRows = 0;
var finished = false;

document.getElementById("btn_submit").onclick = validation;

textAreaList = document.getElementsByClassName("text_input");

function validation() {
    loadNumRows();

    try {
        document.getElementById('failure').hidden = true;
    }
     catch(e) {
         console.log(e.message);
     }
    textAreaList = document.getElementsByClassName("text_input");
    var failValidation = false;
    for (var i = 0; i < textAreaList.length; i++) {
        console.log(textAreaList[i]);
        if (textAreaList[i].value == "") {
            textAreaList[i].style.border = "2px solid #ff0000";
            failValidation = true;
        } else {
            textAreaList[i].style.border = "2px solid #286C2B";
        }
    }

    return !(failValidation || numOfRows != 0);
}

function loadNumRows(){
    $.ajax({
        url: 'php/SeeIfNumberExists?number=' + document.getElementById('number_inp').value,
        type: "GET",
        cache: false,
        success: function (html) {
           numOfRows = parseInt(html);               
        }
    });
}
+9
source share
3 answers

Using async: falseis a very bad idea , and first of all it strikes the goal of using AJAX in the first place - AJAX should be asynchronous. If you want to wait for a response from your script when making an AJAX call, just 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 - this helps if you stick with one :)

+11
source

( , , , . , , numOfRows, Ajax. , ...):

async : false $.ajax. A Ajax . , , . (.. ). , .

$.ajax({
        url: 'php/SeeIfNumberExists?number=' + document.getElementById('number_inp').value,
        type: "GET",
        async: false,
        cache: false,
        success: function (html) {
           numOfRows = parseInt(html);               
        }
    });

$. ajax:

dataType: "jsonp" . , , , . jQuery 1.8, async: false jqXHR ($.Deferred) ; // jqXHR, jqXHR.done() jqXHR.success().

0

async/await , Babel, . Babel npm: npm -D babel-preset-env babel-polyfill.

function getData(ajaxurl) { 
  return $.ajax({
    url: ajaxurl,
    type: 'GET',
  });
};

async test() {
  try {
    const res = await getData('https://api.icndb.com/jokes/random')
    console.log(res)
  } catch(err) {
    console.log(err);
  }
}

test();

.then - .

getData(ajaxurl).then(function(res) {
    console.log(res)
}
0

Source: https://habr.com/ru/post/1568685/


All Articles