'how to loop through json response data using ajax jquery?
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
Solution 1:[1]
use response[i].name
to access the array
success: function(response) {
let buffer = '';
for (var i = 0; i < response.length; i++) {
buffer += '<li>'+response[i].name+'</li>';
}
$('.platformsList').html(buffer);
}
Solution 2:[2]
You are replacing the contents of .platformsList
in each iteration. You need to either create a buffer or use append()
.
success: function(response) {
let buffer = '';
for (var i = 0; response.length < i; i++) {
buffer += '<li>'+response[i].name+'</li>';
}
$('.platformsList').html(buffer);
}
Solution 3:[3]
- Dont use GLOBALS like that, instead pass that as a paramter to the function
- If you have no paramters to bind to the query a simple
->query()
is easier and quicker. - You want to send a
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.
function platformsList($conn){
$query = "SELECT id, name, slug, icon FROM `platforms` ORDER BY id ASC";
$result = $conn->query($query);
$data = $result->fetch_all(MYSQLI_ASSOC);
return $data;
}
if(isset($_GET['platforms']) AND $_GET['platforms'] == 'platforms'){
$platforms = platformsList($PDO);
echo json_encode($platforms);
}
And the javascript need to process that array
success: function(response) {
for(var i = 0; response.length < i; i++) {
buf += '<li>'+response[i].name+'</li>';
}
$('.platformsList').html(buf);
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | |
Solution 3 |