nb_ck
nb_ck

Reputation: 205

ajax Load 2 records each time "load more" button is clicked

I want to load 2 records each time "load more" button is clicked using ajax call and JSON data.

So far I was able to load one record at a time.

Here is my code:

var loadMoreBtn = $('.load_more');
    function loadData() {
        var xmlhttp = new XMLHttpRequest();
        var url = "jsondata.php";
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var obj = JSON.parse(xmlhttp.responseText);
                var counter = 0;
                loadMoreBtn.on('click', function () {
                    if (counter <= obj.length) {
                        var out = '';
                        out += '<ul>';
                        out += '<li>' + obj[counter]['firtsname'] + ' ' + obj[counter]['lastname'] + '</li>';
                        $("#results").append(out + '<br/><br/>');
                        counter++;
                    }
                    if (counter >= obj.length) {
                        loadMoreBtn.attr('disabled', 'disabled')
                    }
                });
            }
        };

        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

    loadData();

I will appreciate any help!

Upvotes: 0

Views: 105

Answers (1)

Omidam81
Omidam81

Reputation: 1917

var loadMoreBtn = $('.load_more');
    function loadData() {
        var xmlhttp = new XMLHttpRequest();
        var url = "jsondata.php";
        xmlhttp.onreadystatechange = function () {
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                var obj = JSON.parse(xmlhttp.responseText);
                var counter = 0;
                loadMoreBtn.on('click', function () {
                  //repeat load 'one' two times :) it will load two item if item exists.   
                  for(i =0; i<2; i ++){
                      if (counter <= obj.length) {
                        out = '';
                        out += '<ul>';
                        out += '<li>' + obj[counter]['firtsname'] + ' ' + obj[counter]['lastname'] + '</li>';
                        $("#results").append(out + '<br/><br/>');
                        counter++;
                      }
                      if (counter >= obj.length) {
                        loadMoreBtn.attr('disabled', 'disabled')
                      }
                    }
                });
            }
        };

        xmlhttp.open("GET", url, true);
        xmlhttp.send();
    }

    loadData();

Upvotes: 1

Related Questions