I have a PHP API file whichs encodes an array in JSON and then I retrieve the JSON data in my jQuery file to dynamically create elements.
I need to create an array from the JSON I received, so I can acces the received data whenever I want instead of making a new API call and then iterate trough the results....
How would I create a jQuery array to acces the data anywhere in the jQuery code?
My PHP array: if(mysqli_num_rows($run_query) > 0){
$ids = array();
$namen = array();
$brouwerijen = array();
$types = array();
$gistingen = array();
$percs = array();
$inkoop_prijzen = array();
$biertjes = array();
while($row = mysqli_fetch_assoc($run_query)) {
$id = $row['id'];
$naam = $row['naam'];
$brouwerij = $row['bouwerij'];
$type = $row['type'];
$gisting = $row['gisting'];
$perc = $row['perc'];
$inkoop_prijs = $row['inkoop_prijs'];
$ids[] = $id;
$namen[] = $naam;
$brouwerijen[] = $brouwerij;
$types[] = $type;
$gistingen[] = $gisting;
$percs[] = $perc;
$inkoop_prijzen[] = $inkoop_prijs;
}
for($i=0; $i < count($ids); $i++){
$biertjes[] = array("id"=>$ids[$i], "naam"=>$namen[$i], "brouwerij"=>$brouwerijen[$i], "type"=>$types[$i], "gisting"=>$gistingen[$i], "perc"=>$percs[$i], "inkoop_prijs"=>$inkoop_prijzen[$i]);
}
echo json_encode($biertjes);
}
What I tried to do in jQuery but didn't work (the biertjes.push line):
var biertjes = [];
$.ajax({
url : "action-api.php",
method: "GET",
dataType: 'json',
success : function(data){
console.log(data);
var html = '<table style="width:100%"> <tr> <th>Edit</th> <th>Info</th> <th>Delete</th> <th>Naam</th> <th>Percentage</th> </tr>';
$.each(data, function(i, item) {
html+='<tr><td><div class="edit"><img src="img/edit.png"/></div></td>';
html+='<td><div class="info"><img src="img/info.png"/></div></td>';
html+='<td><div class="delete"><img src="img/delete.png"/></div></td>';
html+='<td>'+item.naam+'</td>';
html+='<td>'+item.perc+'</td></tr>';
biertjes.push(["id", item.id]);
});
html+='</table>'
container.append(html).css(tableCss());
},
});
biertjes.push({"id": item.id});, Why can'tbiertjes = data?