0

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!

n1k1ch
  • 2,594
  • 3
  • 31
  • 35
user2933671
  • 273
  • 3
  • 5
  • 19

2 Answers2

1

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.

John Green
  • 13,241
  • 3
  • 29
  • 51
0

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

 });
Rob Sedgwick
  • 5,216
  • 4
  • 20
  • 36