Trying to save an array retrieved from ajax into a global variable such that I may use it later on but keep getting undefined error
<script>
var items = [];
function add(value){
items.push(value);
}
$(document).ready( function() {
$.ajax({
type: 'POST',
url: 'xxxx.php',
dataType: 'json',
cache: false,
success: function(result) {
for(i=0; i < result.length; i++){
add(result[i]);
}
},
});
});
document.write(items[1])
</script>
This is an asynchronous AJAX call. The call to add will be done at a later time than the execution of document.write(items[1]);
So this is the right way to do it:
<script>
var items = [];
function add(value){
items.push(value);
}
$(document).ready( function() {
$.ajax({
type: 'POST',
url: 'xxxx.php',
dataType: 'json',
cache: false,
success: function(result) {
for(i=0; i < result.length; i++){
add(result[i]);
}
document.write(items[1])
},
});
});
</script>
This way the function that uses the result, will be executed when the result function is executed.
Think it this way: you said: Here is this lemon basket. Then you asked someone to go somewhere and get the lemons and before he returned you tried to count the lemons. Got it ?
You can use ajaxstop to call the method after the ajax request has completed. Place the following function in document ready:
$(document).ajaxStop(function () {
document.write(items[1]);
});
The above solution works but this is another option I used when waiting for multiple ajax functions to complete. This will call every time you complete an ajax request but there is a way to limit to one call if need be.