Eric Pearson
Eric Pearson

Reputation: 23

Repeating appended html with json data included

This is a bit of a learning exercise for me so please excuse the code I am about to present. I am sure it could be better. In the following code you will see that I have successfully created a variable that is pulling in properly formatted JSON data. I am then, creating a function that appends a block of html. Within that append, I am referencing specific pieces of JSON data to be displayed.

HTML

<table id="jobSearchResults" bgcolor="white" style="border: 1px solid #ddd;width:100%;">
  <tbody>  
  </tbody> 
</table>

Javascript

var json = (function () {
            var json = null;
            $.ajax({
                'async': false,
                'global': false,
                'url': "../data/jobSearchResults.json",
                'dataType': "json",
                'success': function (data) {
                    json = data;
                }
            });
            return json;
        })(); 

$(jobSearchResults).each(function(index, element){
  $('#jobSearchResults').append('<tr><th><div style="background-color:#ddd;height:55px;width:80px;"><img src="" style="height:55px;width:80px;"></div></th><td><h4 style="margin-top: 0;margin-bottom: 2px;font-size: 16px;"> '+json[0].job_header+' </h4> '+json[0].specialty_name+', '+json[0].facility_name+' </td><td><h4 style="margin-top: 0;margin-bottom: 2px;font-size: 16px;"> '+json[0].city+',  '+json[0].state_name+' </h4> United States </td><td class="text-right"></td></tr>');       
});

Now, I need to complicate matters by making that table row repeat X number of times and have the JSON record number increment with each new row. In this case, I am both interested in how to take what I have written and expand on it to include this new functionality and I am also interested in what a more concise way to approach this problem would have been had I written this more efficiently.

Upvotes: 2

Views: 1444

Answers (2)

bryan60
bryan60

Reputation: 29325

The answer given definitely shows the right way to do what you're asking. But I would've approached this differently if you are controlling the server as well. Instead of sending JSON data back, I'd send formatted HTML back and use:

$('#jobSearchResults tbody').load('../data/jobSearchResults/')

Upvotes: 0

showdev
showdev

Reputation: 29168

The callback function for jQuery's each is passed two values. They represent the index and value of the current iteration, respectively. You can use either of these to reference your original JSON data and output each row accordingly.

The $.each() function can be used to iterate over any collection, whether it is an object or an array. In the case of an array, the callback is passed an array index and a corresponding array value each time.

$.each( obj, function( key, value ) {
  alert( key + ": " + value );
});

In my example below, I'm iterating over the json variable, which contains the JSON data returned from your AJAX call. In this context, you could use the index to reference the current iteration (e.g. json[index].job_header) or use the value directly (e.g. job.job_header).

function displayData(json) {
  
  var $resultDisplay = jQuery('#jobSearchResults tbody');
  
  if (!json) {        
    // variable is false. there was an ajax error.
    $resultDisplay.html('<tr><td>There was an error.</td></tr>');        
  } else if (jQuery.isEmptyObject(json)) {        
    // variable is an empty object. no records were returned.
    $resultDisplay.html('<tr><td>No data to display.</td></tr>');        
  } else {
    
    // display the returned records.
    $resultDisplay.empty();
    jQuery.each(json, function(index, job) {
      $resultDisplay.append('<tr>' +
        '<td><div class="row-img"><img src="" alt=""></div></td>' +
        '<td><h4>' + job.job_header + '</h4>' + job.specialty_name + ', ' + job.facility_name + '</td>' +
        '<td><h4>' + job.city + ',  ' + job.state_name + ' </h4>United States</td>' +
        '</tr>');
    });
    
  }
  
}

jQuery.ajax({
    'url': "https://epearson001.github.io/prototype-web-application/assets/data/jobSearchResults.json",
    'dataType': "json"
  })
  .done(function(data) {
    displayData(data);
  })
  .fail(function() {
    displayData(false);
  });
#jobSearchResults {
  border: 1px solid #ddd;
  width: 100%;
  background-color: white;
}
div.row-img {
  background-color: #ddd;
  height: 55px;
  width: 80px;
}
div.row-img img {
  height: 55px;
  width: 80px;
}
h4 {
  margin-top: 0;
  margin-bottom: 2px;
  font-size: 16px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table id="jobSearchResults">
  <tbody>
    <tr>
      <td>Loading data...</td>
    </tr>
  </tbody>
</table>


Edit

I also notice that you're setting async to false in your AJAX call. This defeats the asynchronous functionality of AJAX and, unless there's a particular reason to do so, I advise against it. I've restructured my example to use a callback function, so that data will be displayed after it is returned from your asynchronous AJAX call. I also added a bit of error handling. I acknowledge that this might not be appropriate for your particular context, but I thought I'd offer the idea.

Upvotes: 1

Related Questions