0

I am having difficulty trying to learn this concept.

I have a JSON file with a list of hospitals, their address, hours and phone.

I want to make an AJAX call from JSON data and list the data onto the screen.

I can only get the first hospital to list, when I try to list the address only the address lists.

How can I write this using a loop that will list the objects and their properties?

Can someone explain this to me, please?

Please help -- thank you in advance.

JSON --

https://api.myjson.com/bins/b29r7

JS --

var url = 'https://api.myjson.com/bins/b29r7';

$.ajax({
    url: url,
    method: 'GET',
}).done(function(result){
    var data = result.surrey;
    for(var i=0; i<data.length; i++){
        $('#data').each(function(index, ele){
            $(ele).html(data[index].hospital);
        });
    }
}).fail(function(err){
    throw err;
});

HTML --

<p id="data"></p>
4
  • I think you're just looking for a loop over a JS object. Commented Apr 11, 2017 at 16:35
  • for starters, $('#data').each( should be $.each(data, function (index, elec) {... Commented Apr 11, 2017 at 16:38
  • @Adam that doesn't work. Commented Apr 11, 2017 at 17:02
  • Please update your question to ask something more specific if these comments / answers aren't helpful; you asked "How can I write this using a loop that will list the objects and their properties?" which @jencko shows you below... Commented Apr 11, 2017 at 17:10

3 Answers 3

3

Here's a working example:

var url = 'https://api.myjson.com/bins/b29r7';

$.ajax({
  url: url,
  method: 'GET',
}).done(function(result) {
  // JSON data array
  var data = result.surrey;

  // get DOM node to be parent of child list nodes
  var $data = $('#data');

  // iterate through each object in JSON array
  data.forEach(function(item) {

    // create an unordered list node
    var $ul = $('<ul></ul>');

    // iterate through all the properties of current JSON object
    for (var field in item) {

      // append list item node to list node
      $ul.append(`<li>${field}: ${item[field]}</li>`);
    }

    // append list node to parent node
    $data.append($ul);
  });
}).fail(function(error) {
  console.error(error);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="data"></div>

JSFiddle Demo: https://jsfiddle.net/L6j8n17j/4/

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

7 Comments

Hi @MiguelMota thanks for the working example. Care to explain the set up to me? Please? For starters, I don't get why you wrote the function the way you did. Starting with-- data.forEach(function(item){...});
perfect. Thank you so much but i don't get your for loop set up. Is that new in ES2015? What is field and item as I do not see them defined. I tried to google this but wan't lucky with results.
@scrippyfingers forEach iterates through all items in an array. The parameter item is the current item it's iterating over. for..in iterates through all the properties of an object. field is just a variable name for the object key it's iterating over, item is the object, item[field] is the object property value.
@scrippyfingers those are template literals developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… . (note you have to use backticks). They allow you to interpolate variable values inside of a string. Whatever is inside a ${} gets evaluated to a value. That line is creating a list item with content and appending it the unordered list.
|
2

as per requirement please try below code

var url = 'https://api.myjson.com/bins/b29r7';

$.ajax({
    url: url,
    method: 'GET',
}).done(function(result){
    var data = result.surrey;
    var i = 0;
    var hosData = "<table border='1'>";
    hosData += "<tr>";
      
      	hosData += "<th>";
        	hosData += 'hospital';
        hosData += "</th>";
        
      	hosData += "<th>";
        	hosData += 'address';
        hosData += "</th>";
        
        hosData += "<th>";
        	hosData += 'hours';
        hosData += "</th>";
        
        hosData += "<th>";
        	hosData += 'phone';
        hosData += "</th>";
        
      hosData += "</tr>";
    for(i=0;i<data.length;i++)
    {
      hosData += "<tr>";
      
      	hosData += "<td>";
        	hosData += data[i].hospital;
        hosData += "</td>";
        
      	hosData += "<td>";
        	hosData += data[i].address;
        hosData += "</td>";
        
        hosData += "<td>";
        	hosData += data[i].hours;
        hosData += "</td>";
        
        hosData += "<td>";
        	hosData += data[i].phone;
        hosData += "</td>";
        
      hosData += "</tr>";
    }
    hosData += "</table>";
    
    $("#data").html(hosData);
}).fail(function(err){
    throw err;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

 <div id="data">
 
 </div>

Comments

2

UPDATE : This is more clear version. You can print your values in your html like this.

 
  
            $.ajax({
                type: 'ajax',
                url: 'https://api.myjson.com/bins/b29r7',
                async: false,
                dataType: 'json',
                success: function (data) {
                    data = data.surrey;
                    var html = '';
                    var i;
                    for (i = 0; i < data.length; i++) {
                       html+='<span>'+data[i].hospital+'</span>';
                       html+='<span>'+data[i].address+'</span>';
                       //so on 
                    }
                    $('#data').html(html);
                },
                error: function () {
                    alert('Could not get Data');
                }
            });
      
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div class='data'>

</div>

This should bring your values on the console and then you can use html function at the same time in the loop to display the data. Thanks!

2 Comments

im not trying to print to the console, this solution does not work.
@scrippyfingers please check now .. is it clear for you now ?

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.