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

Answer

To your attention i < response.length NOT response.length > i.
And response[i].name to access the array

success: function(response) {
                for (var i = 0; i < response.length; i++) {
                    $('.platformsList').html('<li>'+response[i].name+'</li>');
                }
            }

Leave a Reply

Your email address will not be published. Required fields are marked *