1

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
5
  • In what way does this fail? When you debug, what is the content of the response variable? Commented Mar 15, 2021 at 18:07
  • I've edited the post Commented Mar 15, 2021 at 18:10
  • Might need to check the proper formation of an unordered list <ul class="platformsList"></li> ?? Commented Mar 15, 2021 at 18:11
  • lol, just a typo Commented Mar 15, 2021 at 18:12
  • the probleme here is that I can't display the result in html page Commented Mar 15, 2021 at 18:13

3 Answers 3

3

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);

}
Sign up to request clarification or add additional context in comments.

2 Comments

still same problem. Can't display anything
@RichardBranson response seems to be an array. I edited the example code.
2

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);
            }

3 Comments

Thank you! It works but instead of .html() I used .append()
@RichardBranson note that using jquery's append() will update the DOM multiple times unnecessarily. This operation is resource intensive and may render your page slow with large datasets. Using a buffer is advisable.
append() and buffer is recommended, I tried to stick to the source
1
  1. Dont use GLOBALS like that, instead pass that as a paramter to the function
  2. If you have no paramters to bind to the query a simple ->query() is easier and quicker.
  3. 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 a print_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);
}

1 Comment

and how about the jquery loop? is it correct? because I still get no result!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.