i have some json files which look like this:
JavaScript
x
{
"id": "id_11-08-2021",
"name": "John",
"date": "11-08-2021",
"day": "Wednesday",
"starttime": "08:30",
"endtime": "10:00",
"hours": 1.5
}
To read all the json
files in a dir i use this code (process.php):
JavaScript
$files = glob('data/*.json'); // all json files in dir data
foreach($files as $file) {
$objs[] = json_decode(file_get_contents($file),1); // all json objects in array
}
$result = [];
foreach($objs as $key => $val) {
$result['data'] = array(
'id' => $val['id'];
'date' => $val['date'];
'day' => $val['day'];
'starttime' => $val['starttime'];
'endime' => $val['endtime'];
'hours' => $val['hours']
);
}
$result['name'] = $_POST['name'];
$result['status'] = 2;
echo json_encode($result); // send back data
My jquery ajax looks like this:
JavaScript
$.ajax({
type: "POST",
url: "process.php",
data: {
name: name
},
dataType: "json",
success: function(response) {
if(response.status == 2) { // check status of data
$('tbody').html(response.data); // handle data from server; output data in tbody
$('.name').html(response.name); // name from user
}
},
});
I do not receive the data from the foreach loop. What is going wrong?
Advertisement
Answer
First of all, you’re overwriting your result in the loop constantly. You need to create a new array element within data
in the loop.
JavaScript
$result = [];
foreach ($objs as $key => $val) {
$result['data'][] = array(
'id' => $val['id'];
'date' => $val['date'];
'day' => $val['day'];
'starttime' => $val['starttime'];
'endime' => $val['endtime'];
'hours' => $val['hours']
);
}
$result['name'] = $_POST['name'];
$result['status'] = 2;
Secondly, since you’re not changing anything in your loop, you could just use your $objs
array and remove the loop. The loop doesn’t do anything in your example.
JavaScript
$result['data'] = $objs;