Alex Alex - 5 days ago 6
Javascript Question

Is it posible to use ajax respone outside of it?

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?

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).

Comments