This question already has an answer here:
I have a global array
which I want to console.log(array_name)
but I get undefined error following is my code:
<script type="text/javascript">
var profit = [];
$(document).ready(function(e) {
$.ajax({
url : "/php/get-inflow.php",
dataType: "json",
type: "POST",
success: function(data){
for(var i =0; i<data.length; i++){
if(data[i] == null){
profit[i] = 0; // logging profit[i] here gives me correct value
}else{
profit[i] = parseInt(data[i]); // logging profit[i] here gives me correct value
}
}
}
});
console.log(profit);
//some other functions.......
});
</script>
when I look at the console I get the output as [ ]
which means a blank array....
Is the profit array correctly set as global (new to jquery) how do I access this array globally and into other functions thanks!
</div>
An example of what John Green says ( mark John Green as correct !) - this was just too big for a comment .
var profit =[];
function logresults(data) { console.log(data); }
$(document).ready(function(e) {
function _ajax(callback) {
$.ajax({
url : "/php/get-inflow.php",
dataType: "json",
type: "POST",
success: function(data){
for(var i =0; i<data.length; i++){
if(data[i] == null){
profit[i] = 0;
}else{
profit[i] = parseInt(data[i]);
}
}
callback(profit);
}
});
}
/* run */
_ajax(logresults);
});
The AJAX is running asynchronously. 'profit
' will have a value inside of your 'success' closure, but not immediately following the call.
You can also run your AJAX call synchronously (add an option for async:false), if you really need to. This will block your page from doing anything until the transaction is complete.