dedi wibisono dedi wibisono - 2 months ago 6
Ajax Question

Can't rendering JSON to HTML by AJAX

I want to ask about JSON,
here is the JSON

{
"city":[
{
"city":"Jakarta",
"count":"747"
},

{
"city":"Bali",
"count":"600"
}
]
}


And my JavaScript

var $content = $(".wrapper");
$.ajax({
url : "//htlsearch.pegipegi.com/HotelSearchAPI/v1/autocomplete/",
type : "GET",
dataType : "json",
success : function(data){
$.each(data, function(i, data){
$content.append("<div class='city'>"+ data.city +"</div><div class='jumlah'>"+ data.count +"</div>");});
},
error:function(){
alert('error');
}
});


My HTML Page

<div class="wrapper">
<div class="city"></div>
<div class="jumlah"></div>
</div>


I want to show 'city and count' but the result is 'undefined undefined'. Anybody can help me? Thank you

Answer

Change this:

   $.each(data, function(i, data){

to this:

   $.each(data.city, function(i, data){

The data variable that is the argument of your success function refers to the whole object, but what you actually seem to want to iterate over is that object's city property, which is an array of objects.

Comments