B
B
BuBux2020-05-04 03:09:20
JavaScript
BuBux, 2020-05-04 03:09:20

Why does it return undefined on a post request?

let email = document.querySelector('#email');

function checkNoExist(em, check) {
    $.post("/user/checkemail", {
        email: em,
        check: check
    }, onAjaxSuccess
    );
}

function onAjaxSuccess(data) {
    if (data == 0) return false;
    return true;
}

let re = checkNoExist(email.value, 1);
console.log(re);

In the onAjaxSuccess function, data returns the correct result. But when deriving a variable, re is always undefined. What could be wrong? I read that it seems like console.log displays the result before the response of the post request. But I did not understand how to solve this problem.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
F
FTOH, 2020-05-04
@BuBux

In JavaScript, requests are asynchronous. The result of the request is available inside the callback, which will be executed after the request.

let email = document.querySelector('#email');

function checkNoExist(em, check) {
    return $.post("/user/checkemail", {
        email: em,
        check: check
    });
}

console.log('Вывод до запроса');
const promise = checkNoExist(email.value, 1);
console.log('Запрос отправлен, результата ещё нет');
promise.then(data => {
    console.log('Запрос выполнен успешно');

    const result = data !== 0
    console.log(result);
}).catch(error => {
   console.log('Получили ошибку', error)
})
console.log('Результата все ещё нет...');

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question