'Load More' button duplicates or does not work AJAX/JSON

Asked

Viewed 804 times

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?

1 answer

1


Assuming that the ids that are in the JSON that comes from PHP are in ascending order (which makes more sense), I think you need to track which was the last id needs. It is also good to find a way to ensure that the loopTable read only two records. For this:

  1. Add a variable, lastId:

    $(document).ready(function() {
        var url = "data/results.json";
        var lastId = -1;
    
  2. Remove the test from loopTable and trace the lastId there. It is also important to initialize the variable write adequately:

        function loopTable(index, table){
            var write = '';
            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);
            lastId = table.id;
        }; //end function
    
  3. We have to ensure that when the loopTable is first called, that he will read the first two records, no matter what the ids, after all it has to work even if the elements with ids 0 and 1 have been removed:

        $.getJSON(url, function (response) {
            var carregados = 0;
            $.each (response, function (index, table) {
                loopTable(index, table);
                carregados++;
                if (carregados == 2) return false;
            }); //end each
        }); //end getJSON
    
  4. Don’t use the galleryLength. Instead, use the lastId:

        $('.more').on('click', function(event){
            event.preventDefault();
            $.ajax(url, {
    
                    var lastLoaded = lastId;
                    var carregados = 0;
                    $.each(data, function(index, table) {
                        if (table.id <= lastLoaded) return true;
                        loopTable(index, table);
                        carregados++;
                        if (carregados == 2) return false;
                    });
    
  5. I think this stretch is wrong, and it shouldn’t even be there, at least I don’t see any sense of it being inside the $.each(...):

                        if ( table.id.length == galleryLength ) {
                            $('.more').hide();
                        };
    

In addition, there is an important observation to be made. PHP is bringing all the records, converting all of them into JSON, everything is being transmitted over the network/internet and javascript is receiving all this only to filter. It would be much better if you filtered on the PHP side, where you would be sent by AJAX the id of the last loaded record and the number of records to load, and then PHP would send only the requested records.

  • The ID that comes from PHP is yes in ascending order, but not ordered. As there was deletion of some records, it is type 1,2,4,5,7,9... As for the changes, I did, but nothing happens. It just keeps giving eternal loading. I reversed the signs of '>' and '<=' for '<' and '>=' and it loads. However it loads only 1 record and is a duplicate record of the last displayed.

  • @celsomtrindade I edited my answer. See if it works now.

  • It’s starting to work, but it stopped pressing ID 9. Press ID 9, at the time of charging from 10 onwards, it no longer loads. Ps.: I am new with ajax/jquery, tried to change some numbers and signals, but could not get the result.

  • 1

    @celsomtrindade Are you sure that the id is a number and not a string? If you show a bit of what your JSON looks like it should be clear.

  • I didn’t know this detail of JSON, I did the fix and it worked. Now, apparently, everything is perfect! I’m going to run some more tests, but from what I’ve seen so far, it’s okay! Thank you so much for your help!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.