I am having a problem with the scope of my variables after having retrieved them from a back-end PHP script as a 2-dimensional JSON array. Here is my code:
var qns, qis, ncs, nzs, tps;
function get_questions() {
var url = "php/pytania.php";
$.ajax({
cache: false,
type: "GET",
dataType: "text",
url: url,
success: function(response) {
data = jQuery.parseJSON(response);
qns = data.qns;
qis = data.qis;
ncs = data.ncs;
nzs = data.nzs;
tps = data.tps;
}
});
}
$(document).ready(function() {
var index = 0;
get_questions();
$("#question_no").text(qns[index]);
});
When I try to reference my qns array in the end, it displays a variable undefined error. It works however within the ajax statement – no problems there…
Thanks and take care! 🙂
Piotr.
The problem is the success method is being called asynchronously – meaning after you have called $().ajax and you try and reference the variable, it has not been assigned yet as the success callback methods hasn’t been executed.
This can be solved by setting the async option to false like so:
This means that nothing else after the ajax call will be executed until you get your response. The alternative to this is placing the code where you need to use the array IN the success callback method itself.