shah rushabh shah rushabh - 2 months ago 10
Ajax Question

how to display data by using AJAX?

Hi everyone I am a facing one issue in ajax I want to display this data as a table in html how can I extract this data and display it in html table form it is a just dummy data otherwise it have lots of object plus nested object please help me.

JSON DATA:

{
"FullName":"shahrushabh",
"description":"this is demo person register",
"Address1":"b\/1",
"Area":"Sabarmati",
"status":"active",
"Thumb":"0",
"checkbox":
[
{"ID":"1","UniqueID":"617993","Product":"electronics","Image":"617993\/alphansomangolips.jpg"},
{"ID":"2","UniqueID":"617993","Product":"Home Decor","Image":"617993\/banana.jpg"}
]
}


AJAX CODE:

<script>
$(document).ready(function(){
$.ajax({
url:"<?php echo base_url()?>index.php/myad",
type: 'GET',
dataType:'json',
success: function(data){
var jsonobject = jQuery.parseJSON(data);
alert("hi");
$.each(jsonobject, function(key, value){
console.log(value.FullName);
$.each(value.checkbox , function(k, val){
console.log(val);
})
})
}
});
});
</script>

Answer

I assumed from your question is you have nested object, below code is to use each for nested object.

//Main loop
$.each(jsonObject, function(key, value){
  console.log(value.FullName);
  //Inner loop for check box for each user
  $.each(value.checkbox, function(k, val){
    console.log(val);
  })
});

Please make sure that you've read Official each() before using it.

EDIT

Check response is an array or not before iteration.

if (!$.isArray(jsonObject)) {
    jsonObject = [jsonObject];
}

$.each(jsonObject, function(key, value){
  console.log("FULL NAME " + value.FullName);
  $.each(value.checkbox, function(k, val){
    console.log("ID" + " " + val.ID);
  });
});

var jsonObject = [
    {
      "FullName":"shahrushabh",
      "description":"this is demo person register",  
      "Address1":"b\/1",
      "Area":"Sabarmati",
      "status":"active",
      "Thumb":"0",
      "checkbox":
      [
          {"ID":"1","UniqueID":"617993","Product":"electronics","Image":"617993\/alphansomangolips.jpg"},
          {"ID":"2","UniqueID":"617993","Product":"Home Decor","Image":"617993\/banana.jpg"}
      ]
    },
    {
      "FullName":"shahrushabh",
      "description":"this is demo person register",  
      "Address1":"b\/1",
      "Area":"Sabarmati",
      "status":"active",
      "Thumb":"0",
      "checkbox":
      [
        {"ID":"1","UniqueID":"617993","Product":"electronics","Image":"617993\/alphansomangolips.jpg"},
        {"ID":"2","UniqueID":"617993","Product":"Home Decor","Image":"617993\/banana.jpg"}
      ]
    }
 ];

//console.log(jsonObject);
$.each(jsonObject, function(key, value){
  console.log(value.FullName);
  $.each(value.checkbox, function(k, val){
    console.log(val);
  })
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>