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?
$dataarray each time through the loop. It should make a 2-dimensional array with a row for each object. Then you can loop over this array in the JavaScript.$result[] = $data;in the loop, thenecho json_encode($result);after the loop.