I’m trying to loop through a json response with ajax jquery but I can’t display the result.
Here is the code Im using:
data.php
function platformsList(){
$query = "SELECT id, name, slug, icon FROM `platforms` ORDER BY id ASC";
$statement = $GLOBALS['PDO']->prepare($query);
$statement->execute();
$data = array();
while ($row = $statement->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
return json_encode($data);
}
if(isset($_GET['platforms']) AND $_GET['platforms'] == 'platforms'){
$platforms = platformsList();
$response = json_decode($platforms);
print_r($response);
}
jquery :
$(document).ready(function(){
$.ajax({
url: "core/data.php",
method: "GET",
data :'platforms=platforms',
dataType: 'json',
contentType: false,
cache: false,
processData: false,
success: function(response) {
for(var i = 0; response.length < i; i++) {
$('.platformsList').html('<li>'+response.name+'</li>');
}
}
})
});
What I want is to display the result in the div below:
<div>
<ul class="platformsList"></ul>
</div>
EDIT:
WHen I debug I get this result :
Array
(
[0] => stdClass Object
(
[id] => 1
[name] => Platform 1
[slug] => dates
[icon] => dates.webp
)
[1] => stdClass Object
(
[id] => 2
[name] => Platform 2
[slug] => honey
[icon] => honey.webp
)
.
.
... etc
3
Answers
->query()
is easier and quicker.json_encode()
JSON String to the AJAX call, your are decoding it back to a PHP array and then sending aprint_r()
Javascript wont understand that.And the javascript need to process that array
You are replacing the contents of
.platformsList
in each iteration. You need to either create a buffer or useappend()
.use
response[i].name
to access the array