vendredi 23 octobre 2015

jQuery AJAX queue checkbox filters and send request to server

Hi I am creating a site using Laravel, jQuery & AJAX. I have multiple checkbox filters on a page that is sent to the server using AJAX and the results are filtered on the front end of the website. Now the problem I have is that everything a checkbox is changed a request is sent to the server; which I want to amend. I want to instead queue this in an array or something similar so that I can send it to the server every minute or perhaps when the last request has finished. But I'm not entirely sure how I would do this.

This is the code I have so far;

$('#filters input[type=checkbox]').click(function(e) {
        console.info('Thank you for selecting "' + $(this).attr('value') + '"');
filters.update('/index/filter',$('#scrum-filters :input').serialize(), '&offset=0', true);
    });

a typical filter looks as follows;

<input type="checkbox" id="tag_982" name="region[]" class="essex checkbox form-filters" value="Essex" data-name="Essex">

and the request is sent as follows;

var filters = {
    update: function(url, data, offset, reset) {
        var count = '&count=40';
        if (typeof offset === 'undefined') {
            data = data + count;
        } else {
            data = data + count + offset;
        }
        $('.loading-icon').fadeIn();
        $('#adverts').addClass('loading');


        $.ajax({
            url: url,
            async: true,
            dataType: 'json',
            data: data,
            type: 'POST',
            success: function(json) {
                console.log('Adverts successfully loaded');
                $('.loading-icon').fadeOut();
                $('.append-data').html(json.data.viewData);

                $('#adverts').removeClass('loading');

                $('.info-num').html(json.data.offset + ' of ' + json.data.total + ' adverts');


                if (json.data.offset >= json.data.total) {
                    $('#load-more').children('a').text('All adverts loaded').contents().unwrap();
                } else {
                    $('#load-more').children('a').text('Show more adverts');
                    $('#load-more').children('a').attr('href', json.data.offset);
                }

            } // end success
        }).done(function() {


        }); //end ajax
    }, //end update function
} //end var filters

Does anyone have any ideas how this can be achieved? I'm looking for some basic examples.




Aucun commentaire:

Enregistrer un commentaire