javascriptjqueryjsoncodeigniter

How to iterate over json objects and bind with html elemnts.?


I need to iterate over the JSON objects coming from my controller and bind the data to the html elements. When I alert I am getting objects. How can I iterate over these objects to get access to individual data, so that I can append it to the html elements?

I have tried the following codes. I just have a few items here for a demo, the actual array is very big.

My controller:

     public function grid_view_ajax_function()
            {       
                $contacts_details="";
                $this->load->model('contact_model');
                $contacts_details= $this->contact_model->get_all_contacts();
                $result = array();
                $data   = array();
                foreach ($contacts_details as $row_data){
                $data['id']                  =$row_data['contact_id'];
                $data['image']               =$row_data['image'];
                $data['name']                =$row_data['first_name'];
                $data['last_name']           =$row_data['last_name'];    
                array_push($result, $data);

                }
                echo json_encode(array('data' => $result));
            }

main.js file to iterate over the objects in jquery:

         $.getJSON(global_base_url + "contact/grid_view_ajax_function",function(data)
            {
            var div_data = ''; 
                $.each(data,function(i,data)
                {       

    div_data +='<div class="col-xl-15" data-id="'+data.index+'"><div class="panel"><div class="panel-heading"><img src="../asset/'+data.picture+'" class="img-responsive desaturate" /></div><div class="panel-body"><div class="name">'+data.name+'</div><div class="email">'+data.email+'</div><div>';
                });

JSON data:

{
  "data":[
   {
    "id":"1",
    "image":"4.jpg",
    "name":"Mack ",
    "last_name":"Jack",
    "title":"Adminstration",
    "city":"London"
   },
  {
    "id":"2",
    "image":"person-list.png",
    "name":"Renia",
    "last_name":"Jack",
    "title":"Archetectuer"
  }
 ]
}

Solution

  • You can iterate like

    //here ajax response object is assigned to data variable
    var data = {"data":[{"id":"1","image":"4.jpg","name":"Mack ","last_name":"Jack","title":"Adminstration","city":"London"},{"id":"2","image":"person-list.png","name":"Renia","last_name":"Jack","title":"Archetectuer"}]};
    
    var div_data = '';
    $.each(data.data,function(i,data) {
    
      div_data += "<li>"+data.name+"</li>";
      
    });
    $("ul").html(div_data);
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
    <ul></ul>