Cooolranjan Cooolranjan - 5 months ago 18x
PHP Question

My jQuery each function is displaying an extra row as undefined

I am displaying jason data into html div using

and each function . my alert is displaying right data but after posting it to html home page it is displaying an extra div as undefined value.

here is screen shots,


html div

here is my code,

$.getJSON(url,function(data) {

alert("hey got the data"+JSON.stringify(data));
var arr = data.length;

//for(var i=0 ;i<arr; i++){

$.each(data, function(i,element) {
'<div id="''">'

else {

// once we've loaded
// kill the loading stuff
loading = false;


$(function() {

if ($(window).scrollTop() == $(document).height() - $(window).height()){
// add the loading box
if(loading == false){
loading = true;
$("#postjson").append("<div class='loading'>Loading...</div>");



<div class="grid" id="postjson">

How is this caused and how can I fix it?


As per the data shown in image there is two elements in the array. While iterating using $.each() the second iteration takes the second element, which doesn't have those properties defined, so it will append second div values as undefined.

If you just want to append the first element from the arraythen no need to use $.each() here, just get the first element and based on that object.

var element = data[0];

  '<div id="' + + '">' + '<p>' + 'FirstName:' + element.FirstName + '<br/>' + 'MiddleName:' + element.MiddleName + '<br/>' + 'LastName:' + element.LastName + '<br/>' + 'Gender:' + element.Gender + '<br/>' + 'Location:' + element.Location + '<br/>' + 'Email:' + element.Email + '<br/>' + 'Mobile:' + element.Mobile + '<br/>' + '</p>' + '</div>'

Or in case you want to append multiple element from array then add an if condition to check that those properties are defined.