3
Whoa, everybody, all right?
Next, I have a table that is fed with content from an external JSON file (created from PHP with data coming from DB). When opening the site, the table comes with only 2 records and when clicking 'Load more' 2 more records are added to the table.
The way I sort the array is through the unique ID of the DB, so if there is a record deletion, it gets leaked (eg: 0|1|3|6|7|8) which makes the 'load more' not work or duplicate the data.
I did a fix, but I need to create a new ID in JSON to sort everything again, keeping the count constant. So I would like to know how to optimize or fix my code to be able to work WITHOUT fix, ie using ID, in ascending order, even if it is not sequential, as in the example mentioned above.
This is my jQuery code:
$(document).ready(function() {
var url = "data/results.json";
$.getJSON(url, function (response){
$.each (response, function (index, table) {
loopTable(index <= 1, index, table);
}); //end each
}); //end getJSON
function loopTable(test, index, table){
var write;
if(test){
write += '<tr class="count">';
write += '<td>' + table.name + '</td>';
write += '<td>' + table.data + '</td>';
if (table.status === true) {
write += '<td class="ap">Aprovado</td>';
} else {
write += '<td class="ng">Negado</td>';
}
write += '<td>' + table.id + '</td>';
write += '<td><button class="bt_delete">Deletar</button></td>';
write += '</tr>';
$('#mytable').append(write);
}
}; //end function
$('.more').on('click', function(event){
event.preventDefault();
var galleryLength = $('.count').length;
$.ajax(url, {
cache: false,
success: function(data){
if(data){
var jsonLength = data.length;
}
$.each(data, function(index, table){
loopTable(table.id >= galleryLength && table.id < galleryLength + 2, index, table);
if ( table.id.length == galleryLength ) {
$('.more').hide();
};
});
},
error: function(){
$('#myerro').append('<h3>Desculpe, houve um problema.</h3>');
},
beforeSend: function(){
$('.more').hide();
$('.spinner').fadeIn();
},
complete: function(){
$('.spinner').hide();
$('.more').fadeIn();
}
}); //end ajax
}); //end click
}); //end ready
JSON ids coming from PHP are always in ascending order?
– Victor Stafusa