Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

Any way of using the data_response outside the $.post()?

This is part of the code I use:

$.post('do.php', { OP: "news_search", category: cat_id },
    function(data_response){
        var response = data_response; //I need to access this variable outside of $.post()
    }
}, "json");

console.log(response); //response is not defined, is what I get for now

UPDATE

Is there no way of getting that response available globally?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
349 views
Welcome To Ask or Share your Answers For Others

1 Answer

No; $.post executes asynchronously, so when you call console.log, the AJAX request is still running and hasn't yet yielded a response. This is the purpose of the callback function: to provide code to be run after the request has completed. If you move console.log into the callback function, it should work:

$.post('do.php', { OP: "news_search", category: cat_id },
    function(data_response){
        var response = data_response; //I need to access this variable outside of $.post()
        console.log(response);
    }
}, "json");

Update: If you want the response data to be globally available, you can declare the variable in the global scope like so:

var response = null;
$.post('do.php', { OP: "news_search", category: cat_id },
    function(data_response){
        response = data_response;
        console.log(response);
    }
}, "json");

Of course, the only context in which you can be sure that response has actually been populated with a value is in the callback function supplied to $.post after the line response = data_response;. If you want to use it at any other stage in the script then you'll have to check its value first; something like this:

if (response !== null)
{
    console.log(response);
}

Just be aware that this code won't do anything if you put it straight after the $.post call; it'll only be useful if it's executed after the POST request has finished, in some other asynchronous callback (perhaps a UI interaction event of some kind).


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...