简体   繁体   中英

jQuery ajax request only returns value on second call

I'm trying to get data from a php using jQuery's $.ajax method.

This is my code right now:

var ajaxresult = null;
function myFunc() {
    $.ajax('ajaxtest.php',{
    type: 'get',
    data: '',
    success: function(data) {
        ajaxresult = data;
    }
    });
    console.log(ajaxresult);
}

$('button').click(function(){
myFunc();
})

My problem is this:

The first time I call myFunc() (when I click the button) it logs null to the console, after that if I click again it returns the expected value.

What could cause this and how could I fix it to return the expected value the first time it's called?

Ajax is asynchronous, so the first time you click, the console log happens before the ajax call has completed, and it logs null .

The second time you click, the same thing happens, but the variable is global, so it now holds the value from the previous ajax call, and that's what's logged, the value from the previous call, not the value from the current call.

It should look more like this, the data is only available inside the callback

function myFunc() {
    $.ajax({
        url  : 'ajaxtest.php',
        type : 'GET',
        data : '',
        success: function(data) {
            var ajaxresult = data;
            console.log(ajaxresult);
        }
    });
}

$('button').click(myFunc);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM