javascript - How do I load specific data via jQuery Ajax in this Codeigniter application, instead of the entire page?

Solution:

You seem to be trying to reload the entire page with paginated data - that's a really bad practice. In the long run, you'll end up with slower pages that way.

You would be better off having a separate endpoint for your AJAX that outputs a JSON array of HTML strings, one for each post. This is still slower than using a 2-tier solution like Codeigniter and React, but it's certainly faster than constantly rerendering the entire UI.

Answer

Solution:

I got a working solution:

(function($) {

    var currentPage = 2,
        maxPage = $('#postsContainer').data('max-page'),
        posts = null;

    $('.pagination').hide();

    $(window).scroll(function() {
        var toBottom = $(window).scrollTop() >= $(document).height() - $(window).height() - 25;

        if (toBottom && currentPage <= maxPage) {
            loadMore();
        }
    });

    function loadMore() {
        $.ajax({
                url: baseUrl + '?page=' + currentPage,
                type: 'GET',
                beforeSend: function() {
                    if (typeof posts != 'undefined') {
                        $('.loader').show();
                    }
                }
            })
            .done(function(data) {
                $('.loader').hide();
                posts = $(data).find('#postsContainer').html();

                if (typeof posts != 'undefined') {
                    $('#postsContainer').append(posts);
                    currentPage = currentPage + 1;

                    if (currentPage > maxPage) {
                        $('#postsContainer').append('<p class="text-center text-muted">No more posts to load</p>');
                    }
                }
            });
    }

})(jQuery);

Source