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>
1

4 Answers 4

8

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>

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

2 Comments

Thank you very much! This works perfectly, your demonstration and explanation is top quality.
I am very glad to know that it helps you @user12200628
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>

Comments

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>

Comments

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

Comments

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.