how to get values from php arrays using ajax

i am making an ajax call to a php page. the php selects from the database between 2 dates.

this is the php:

if(isset($_POST['fromdate'])){
         
 $fromdate = $_POST['fromdate'];
        
 $todate = $_POST['todate'];
        
 $sql = "SELECT * FROM expenses WHERE date BETWEEN '$fromdate' AND '$todate' ";
            
 $result = mysqli_query($connection, $sql);
        
 while($row = mysqli_fetch_array($result)){
            
   $data['amount'] = $row['amount'];
            
   $data['date'] = $row['date'];
            
   $data['description'] = $row['description'];
            
   }
        
   echo json_encode($data);
        
}

my ajax call looks like this:

$('#new_report').click(function() {
                    
  var fromdate = $('#fromdate').val();
    
  var todate = $('#todate').val();
    
  $.ajax({
                        
    url: 'new_report.php',
                        
    method:'POST',
                        
    dataType: 'JSON',
                        
    data: { 
                            
    'fromdate' : fromdate,
                            
    'todate' : todate
    
    },
                                
  success:function (data){
    
  }
                        
});
                    
                    
});

this works great when selecting by id and only getting one row. i can simply:

success:function (data){

var amount = data.amount;

var date = data.date; //etc..

  }

but since it is a date range, and i get multiple rows, how do i work with the data and display it where i need it? i know i could go to a new page and loop through the php results, but i am forcing myself to work with javascript objects. what is the right way to think about this process?


Solution 1:

the question was answered by Barmar but here is the proper php code:

 while($row = mysqli_fetch_array($result)){
        
        $results[] = $row;
        
    }
    
    echo json_encode($results);

then, in javascript i can display it and (hopefully) work with it. something like this:

success:function (data){
                        
    var text = JSON.stringify(data);
                        
    $('#view').html(text);

    }