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.
Variables have a global or local "scope". For example, variables declared within either the setup() or draw() functions may be only used in these functions. Global variables, variables declared outside of setup() and draw(), may be used anywhere within the program.
In simple terms, scope of a variable is its lifetime in the program. This means that the scope of a variable is the block of code in the entire program where the variable is declared, used, and can be modified.
The scope is the binding part between the HTML (view) and the JavaScript (controller). The scope is an object with the available properties and methods. The scope is available for both the view and the controller. You have more detailed explanation here.
PHP has three different variable scopes: local. global. static.
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:
$.ajax(
{
/* this option */
async: false,
cache: false,
type: "GET",
dataType: "text",
url: url,
...
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.
Your problem is that you are trying to use the data before it has arrived.
You can add a callback function that you call after the data has come from the server:
var qns, qis, ncs, nzs, tps;
function get_questions(callback) {
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;
callback();
}
} );
}
$(document).ready(function() {
var index = 0;
get_questions(function(){
$("#question_no").text(qns[index]);
});
});
Note: You can use dataType: "json"
, then the response will be parsed automatically, and you don't have to use parseJSON
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With