skip to Main Content

I have a problem in using loop since i didn’t know what kind of loop to use in this case (sorry i’m still learning jquery & js!). In the result page I have created card to separate each data from json, but i’m stuck on how to display the data inside each card.Here is the breakdown:

result example

result_example

code

<!doctype html>
<html lang="en">

<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css"
    integrity="sha384-TX8t27EcRE3e/ihU7zmQxVncDAy5uIKz4rEkgIXeMed4M0jlfIDPvg6uqKI2xXr2" crossorigin="anonymous">

<title>Display data json into cards</title>
</head>

<body>
<div class="container">
    <div class="card bg-light border-dark mb-3" style="max-width: 70rem;">

        <div class="card-header"></div>

        <div class="card-body">

            <h5 class="card-title"></h5>

            <p class="card-text"></p>
        </div>
    </div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"</script>
<script>
    $(function () {
        $.ajax({
            url: "https://jsonplaceholder.typicode.com/posts",
            success: function (result) {

                $.each(result, function (index, item) {
                    var userId = item.userId; //this should be in div class = "card-header"
                    var typeId = item.id; //this should be in div class = "card-header"
                    var titleId = item.title; //this should be in h5 class = "card-title"
                    var bodyId = item.body; //this should be in p class = "card-text"

                    var html = '<div class="card bg-light border-dark mb-3" style="max-width: 70rem;">';
                        html += '<div class="card-header"></div>';
                        html += '<div class="card-body">';
                        html += '<h5 class="card-title"></h5>';
                        html += '<p class="card-text"></p>';
                        html += '</div>';
                        html += '</div>';
                        html += '</div>';

                    //use loop below here and inject to div.container    

                    $(".container").html(html); //using .html() will display one card,use loop to display each card

                });
                // console.log('success', result);
                // console.log(result[0].body);
                // console.log($(result).length);
            }
        });
    });
</script>
</body>

</html>

Sorry for asking a bit much, and thank you for the help!

2

Answers


    • You already have a loop by using .each the problem is you didn’t pass/concatenate the variables in your js/html
    • And about but the first div below div.container still display empty data while the div that created from var html being added you can use css or/and js to hide/remove it

    [1] Using css,js .append()

    $(function () {
        $('.container > div').remove();
        $.ajax({
            url: "https://jsonplaceholder.typicode.com/posts",
            success: function (result) {
                $.each(result, function (index, item) {
                    var userId = item.userId; //this should be in div class = "card-header"
                    var typeId = item.id; //this should be in div class = "card-header"
                    var titleId = item.title; //this should be in h5 class = "card-title"
                    var bodyId = item.body; //this should be in p class = "card-text"
    
                    var html = '<div class="card bg-light border-dark mb-3" style="max-width: 70rem;">';
                        html += '<div class="card-header">user: ' + userId +' typeId: '+ typeId +'</div>';
                        html += '<div class="card-body">';
                        html += '<h5 class="card-title">'+ titleId +'</h5>';
                        html += '<p class="card-text">'+ bodyId +'</p>';
                        html += '</div>';
                        html += '</div>';
                        html += '</div>';
    
                    //use loop below here and inject to div.container    
    
                    $(".container").append(html);
    
                });
                // console.log('success', result);
                // console.log(result[0].body);
                // console.log($(result).length);
            }
        });
    });
    .card:nth-child(1){
      display : none;
    }
    .card{
      margin : 20px;
      padding : 20px;
      background : #eee;
      border : 1px solid #333;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="container">
        <div class="card bg-light border-dark mb-3" style="max-width: 70rem;">
    
            <div class="card-header"></div>
    
            <div class="card-body">
    
                <h5 class="card-title"></h5>
    
                <p class="card-text"></p>
            </div>
        </div>
    </div>

    [2] If you want to use .html() you need to define the var html before the each() then let the .each update the html += value then use the .html() after the .each() I still prefer the first solution

    $(function () {
        $.ajax({
            url: "https://jsonplaceholder.typicode.com/posts",
            success: function (result) {
                var html = '';
                $.each(result, function (index, item) {
                    var userId = item.userId; //this should be in div class = "card-header"
                    var typeId = item.id; //this should be in div class = "card-header"
                    var titleId = item.title; //this should be in h5 class = "card-title"
                    var bodyId = item.body; //this should be in p class = "card-text"
    
                    html += '<div class="card bg-light border-dark mb-3" style="max-width: 70rem;">';
                        html += '<div class="card-header">user: ' + userId +' typeId: '+ typeId +'</div>';
                        html += '<div class="card-body">';
                        html += '<h5 class="card-title">'+ titleId +'</h5>';
                        html += '<p class="card-text">'+ bodyId +'</p>';
                        html += '</div>';
                        html += '</div>';
                        html += '</div>';
    
                    //use loop below here and inject to div.container    
    
                    
                });
                $(".container").html(html);
    
                // console.log('success', result);
                // console.log(result[0].body);
                // console.log($(result).length);
            }
        });
    });
    .card{
      margin : 20px;
      padding : 20px;
      background : #eee;
      border : 1px solid #333;
    }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <div class="container">
        <div class="card bg-light border-dark mb-3" style="max-width: 70rem;">
    
            <div class="card-header"></div>
    
            <div class="card-body">
    
                <h5 class="card-title"></h5>
    
                <p class="card-text"></p>
            </div>
        </div>
    </div>
    Login or Signup to reply.
  1. Try using the following solution:

    To bind the variable inside the string use

    $(function() {
      var html = "";
      $.ajax({
        url: "https://jsonplaceholder.typicode.com/posts",
        success: function(result) {
          $.each(result, function(index, item) {
            html +=
              '<div class="card bg-light border-dark mb-3" style="max-width: 70rem;">';
            html += `<div class="card-header">userid: ${item.userId} - id: ${item.id}</div>`;
            html += '<div class="card-body">';
            html += `<h5 class="card-title">${item.title}</h5>`;
            html += `<p class="card-text">${item.body}</p>`;
            html += "</div>";
            html += "</div>";
            html += "</div>";
            //using .html() will display one card,use loop to display each card
          });
          $(".container").html(html);
        }
      });
    });
    

    And see the following in the stackblitz demo:

    https://stackblitz.com/edit/js-xfs15o?file=index.html

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search