Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Display json data from jQuery.ajax in HTML using loop

Hello suppose I have the following ajax call:

jQuery.ajax({
    type: "GET",
    url: "https://myurl.com",
    success: function(data)
    {
        console.log(data);
    }
});

That results in the following json data (in my console)

{
  "meta": {
    "last_updated": "2017-07-06"
  },
  "results": [
    {
      "term": "DRUG INEFFECTIVE",
      "count": 1569
    },
    {
      "term": "NAUSEA",
      "count": 1374
    },
    {
      "term": "FATIGUE",
      "count": 1371
    }
  ]
}

How can I populate a div in my HTML page with this data in a format something like:

term: x
count: xx

term: x
count: xx

term: x
count: xx

I am not interested in the "meta" stuff only the "results"

Anyone know how to use a simple loop to display this data?

Thanks!

like image 223
cup_of Avatar asked Oct 30 '22 05:10

cup_of


1 Answers

You can loop through your data.results within your "success function", like this:

jQuery.ajax({
    type: "GET",
    url: "https://myurl.com",
    success: function(data)
    {
        console.log(data);

        jQuery.each(data.results, function(i, val) {
            // here you can do your magic
            $("#yourdivid").append(document.createTextNode(val.term));
            $("#yourdivid").append(document.createTextNode(val.count));
        });
    }
});
like image 149
Chris Avatar answered Nov 09 '22 07:11

Chris