O
O
ObehanProger2019-05-04 17:48:28
AJAX
ObehanProger, 2019-05-04 17:48:28

Why is the numeric variable received via Ajax not printed?

function getAjaxResult(url,data=null){
  var res;
  $.get(
        url,
        {data:data},
        function (result) {
            res=result;
        },
        "json"
    );
    return res;
}
$('.btn').click(function(){
alert(getAjaxResult('/get_products_select_count',null));
    });

outputs undefined or NaN if you insert + before getAjaxResult, even though the script at '/get_products_select_count' actually returns the number 2. What's the problem here?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
I
Ihor Bratukh, 2019-05-04
@ObehanProger

function getAjaxResult(url, data = null) {
    return $.get(url, { data });
}

$('.btn').click(function () {
    getAjaxResult('/get_products_select_count').then(function (data) {
        alert(data);
    });
});

$('.btn').click(async function () {
    const data = await getAjaxResult('/get_products_select_count');
    alert(data);
});

R
Rsa97, 2019-05-04
@Rsa97

Asynchrony. The $.get function finishes executing as soon as the request is sent to the server. An anonymous callback is called after the response to the request has arrived.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question