Rainieren's avatar

jQuery - Foreach html with data

I made an Ajax API call that returns an object with data. I have a HTML structure that I wish to repeat for every object that the API call returns and with the relevant data. How can I accomplish that?

Ajax call

 $.ajax({
    headers: {'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content'), 'X-Requested-With': 'XMLHttpRequest'},
    url: 'https://www.rainierlaansite.test/api/packages/get',
    type: 'GET',
    data: {},
    success: function(data) {
         $('#package-loading').fadeOut();
         $.each(data, function(index, value) {
             console.log(index);
             console.log(value)
          });
     },
    error: function(e) {
        $('#package-error').fadeIn().text("Unfortunately there was an error retrieving the packages");
    }
 });

The api call returns the following object

id: 1
name: "rainieren/visitors"
description: "The Laravel Framework."
subscription_id: 1
price: 0.99
composer_package: "rainieren/visitors"
downloaded: 8
created_at: "2020-01-28 21:48:39"
updated_at: "2020-01-28 21:48:39"

HTML Structure that needs to be repeated for every object.

<div class="row">
   <div class="col-2">
       foto
   </div>
   <div class="col-6">
        <a href=""><h6 class="m-0">Name</h6></a>
         <p class="m-0 sub-text">Description</p>
    </div>
     <div class="col-4 d-flex justify-content-end align-items-center">
          <a href="" class="badge badge-pill badge-light" style="font-size: 14px;">price</a>
      </div>
    </div>
    <hr>
0 likes
1 reply
Cronix's avatar
Cronix
Best Answer
Level 67

You could give that block of html an id and set it to hidden, to use as a template.

<div id="template" style="display:hidden">
  <div class="name"></div>
  <h1 class="subscription"></h1>
</div>

Then in your success method (in your loop), you just clone() that html block, and find() the elements where you want to insert your data, place your data where it needs to go and then insert that clone into the dom where you want it to display.

// clone the template and make it visible
let $clone = $("#template").clone( true );
$clone.css("hidden", false):

// populate the template with data from ajax request
$clone.find(".name").html(data.name);
$clone.find(".subscription").html(data.subscription);

// insert the clone into the dom somewhere
$("#some-dom-element").append($clone);

That's not a drop in replacement and you'll need to adjust for your array/loop, but should show you how to basically do what you're asking.

Please or to participate in this conversation.