2

I want to be able to use the API from the code below to display data in a formatted way such as this example.

Job Title: Agricultural and Related Trades

Percentage of Occupancies in Area: 15.41%

You can find my poor attempt to display the data below. I am very new to Ajax, jQuery, JavaScript, etc.

<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script>
    $(function() {
        $.ajax({
        url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
        type: "get",
        dataType: "json",
        success: function(data) {
            console.log(data[0].area);

            outputString= data[0].description.percentage;
            var paragraph = $("<p />", {
                text: outputString
            });

            $("body").append(paragraph);
        }
        });
    });
</script>
jmd_dk
  • 12,125
  • 9
  • 63
  • 94
EuanM28
  • 258
  • 3
  • 14
  • 5
    Does this answer your question? [Is there a best practice for generating html with javascript](https://stackoverflow.com/questions/220603/is-there-a-best-practice-for-generating-html-with-javascript) – Eriks Klotins Nov 02 '19 at 22:21

4 Answers4

6

After successfully execute your GET request you will get your response at data variable now you can run a for loop to populate your expected outcome 'HTML' TEXT than you can append it on your HTML body

I have used here JavaScript toFixed() Method keeping only two decimals

   $(function() {
        $.ajax({
        url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
       method: "GET",
        dataType: "json",
        success: function(data) {
            var str = "";          
           for(var i= 0; i < data.jobsBreakdown.length; i++){

             str +='Job Title : '+data.jobsBreakdown[i].description+' and Related Trades <br> Percentage of Occupancies in Area : '+data.jobsBreakdown[i].percentage.toPrecision(2)+'% <br><br>';
           }
          $("body").html(str);
        }
        });
    });
 
 <!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
 <script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
</head>
<body>

<h1>This is a Heading</h1>
<p>This is a paragraph.</p>

</body>
</html>
Shakil Hossain
  • 1,701
  • 13
  • 25
1
  • You need to define a function to render a single item of description and percentage.
  • For parsing the percentage, you can use Number object
  • When you get the data back from Ajax, you need to loop on the items and pass each one of them to your render function you defined earlier (here I used forEach).
  • Generally, as rule of thumb, you have to split your code into functions each with single responsibility.

function renderItem(itemData) {
  const title = $('<p/>').text('Job Title: ' + itemData.description);
   const percentage = $('<p/>').text('Percentage of Occupancies in Area: '+ new Number(itemData.percentage).toFixed(2) + '%');
   const item = $('<li/>').append(title, percentage);
  $('#result').append(item);
}

$(function() {
 $.ajax({
 url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
 type: "get",
 dataType: "json",
 success: function(data) {
  data.jobsBreakdown.forEach(renderItem);
 }
 });
});
Job Title: Agricultural and Related Trades

Percentage of Occupancies in Area: 15.41%
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<ul id="result"></ul>
Tareq
  • 5,283
  • 2
  • 15
  • 18
0

Something like this is likely what you want:

<script>
$(function() {
    $.ajax({
        url: "http://api.lmiforall.org.uk/api/v1/census/jobs_breakdown?area=55.9895989531941,-3.796229726988194",
        type: "get",
        dataType: "json",
        success: function(data) {
            data.jobsBreakdown.forEach(function(job) {
                var job_text = "Job Title: " + job.description;
                var percentage_text = "Percentage of Occupancies in Area: " + job.percentage.toFixed(2) + "%"
                $("body").append("<div style='margin-bottom: 10px;'><div>" + job_text + "</div><div>" + percentage_text + "</div></div>")
            })
        }
    });
});
</script>
Jon Warren
  • 857
  • 6
  • 18
0

You can use string templates to create your paragraph content. Use the <br /> HTML element to make a new line in the paraghraph.

let data = [{
  area: 'Agricultural and Related Trades',
  percentage: 15.41
}]

var paragraph = document.createElement('p');
paragraph.innerHTML = `Job Title: ${data[0].area}<br/>
Percentage of Occupancies in Area: ${data[0].percentage}%"`;
document.body.appendChild(paragraph);
TheGr8_Nik
  • 3,080
  • 4
  • 18
  • 33