0

I have pretty much the same Ajax Request call but I need to expand it to be more generic

See example Code: http://jsfiddle.net/2b8gR/6/

I have it working for Page A and want to use it for Page B, C, D, etc... but don't want to rewrite the function for every new Ajax request.

Most of the code will remain the same except:

  • input next/prev (page_a_next becomes page_b_next)
  • display page div (display_page_a_page becomes display_page_b_page)
  • display page number div (display_page_a_number becomes display_page_b_number)
  • ajax request url page name (url: 'page_a.php?page='+currentPageA, becomes url: 'page_b.php?page='+currentPageB,)

and so forth.

How do I make the Ajax call and elements more generic so I don't have to write this request multiple times?

NOTE: I need to be able to keep track of each page (A, B, C, etc...) it's currently displaying. And yes all of these are on the same page

HTML:

<!-- Page A -->
<div>
    <span>Page A</span>
    <input id="page_a_next" name="page_a_next" type="button" value="Next" data-inline="true" />
    <input id="page_a_prev" name="page_a_prev" type="button" value="Previous" data-inline="true" /> 
</div>   
<div id="display_page_a_page" name="display_page_a_page">
</div>
<div id="display_page_a_number" name="display_page_a_number">
</div>

<!-- Page B -->
<div>
    <span>Page B</span>
    <input id="page_b_next" name="page_b_next" type="button" value="Next" data-inline="true" />
    <input id="page_b_prev" name="page_b_prev" type="button" value="Previous" data-inline="true" /> 
</div>   
<div id="display_page_b_page" name="display_page_b_page">
</div>
<div id="display_page_b_number" name="display_page_b_number">
</div>

JS:

var currentPageA=1;
var totalPageA=113;
loadPageA();

$("#page_a_next, #page_a_prev").click(function(){
    currentPageA = ($(this).attr('id')=='page_a_next') ? currentPageA + 1 : currentPageA - 1;

    if(currentPageA<=0) {
        currentPageA=1;                
        $('#page_a_prev').attr('disabled','disabled');
    } else if(currentPageA==114) {
        currentPageA=113;
        $('#page_a_next').attr('disabled','disabled');
    } else {
        loadPageA();
    }                
});

function loadPageA(){
    $('#page_a_next').attr('disabled','disabled');
    $('#page_a_prev').attr('disabled','disabled');

    $.ajax({
        url: 'page_a.php?page='+currentPageA,
        type: 'POST',
        error : function (){ alert('Error'); }, 
        success: function (data) {
            $('#display_page_a_number').html(currentPageA + ' of ' + totalPageA);
            $('#display_page_a_page').html(data);
            $('#page_a_next').attr('disabled','');
            $('#page_a_prev').attr('disabled','');
        }
    });
}
Phill Pafford
  • 83,471
  • 91
  • 263
  • 383

3 Answers3

1

I would add classes to your html elements prev, next, page, number. And then create a jQuery plugin.

HTML

<div data-page="a" data-total="113">
    <span>Page A</span>
    <input id="page_a_next" name="page_a_next" type="button" value="Next" data-inline="true" class="next" />
    <input id="page_a_prev" name="page_a_prev" type="button" value="Previous" data-inline="true" class="prev" /> 
</div>
<div id="display_page_a_page" name="display_page_a_page" class="page"></div>
<div id="display_page_a_number" name="display_page_a_number" class="number"></div>

jQuery Plugin

(function($) {
    $.fn.customAjaxPager = function() {
        var state = {
            page = "",
            current = 1,
            total = 0
        };

        return this.each(function() {
            $this = $(this);

            state.page = $this.attr("data-page");
            state.total = $this.attr("data-total");

            $(".next", this).click(next);
            $(".prev", this).click(prev);
        });

        function next() {
            state.current++;
            if (state.current >= state.total) {
                state.current = state.total;
                $(".next", this).attr("disabled", "disabled");
                return;
            }
            load();
        };

        function prev() {
            state.current--;
            if (state.current <= 0) {
                state.current = 0;
                $(".prev", this).attr("disabled", "disabled");
                return;
            }
            load();
        };

        function load() {
            $('.next,.prev').attr('disabled','disabled');
            $.ajax({
                url: 'page_"+ state.page +".php?page='+ state.current,
                type: 'POST',
                error : function (){ alert('Error'); }, 
                success: function (data) {
                    $('.number', this).html(state.current + ' of ' + state.total);
                    $('.page', this).html(data);
                    $('.next,.prev', this).removeAttr('disabled','');
                }
            });
        };
    };

})(jQuery);

Usage

$("div[data-page='a']").customAjaxPager();
jessegavin
  • 74,067
  • 28
  • 136
  • 164
  • would the variables 'current' and 'total' in the success() function in pager.load() be available since 'success' is a function called after the ajax request comes back? – jwatts1980 Mar 15 '11 at 15:38
1

Maybe you could write your code as a jquery plugin and just pass in the currentPageA and totalPageA variables into the plugin. You can find information on making a jquery plugin here.

mwgriffith
  • 550
  • 3
  • 6
  • Thanks, I thought about doing a plugin but that might mean more work than what is needed. Are there any performance benefits with using a plugin? – Phill Pafford Mar 15 '11 at 15:45
  • I don't think there is a performance benefit in doing it has a plugin, but you would get a performance benefit if you put it in an external js file and loaded it from each page. Most browsers these days will cache the file, so you'll get a performance boast from loading the js file after the file is cached. Putting it in a plugin would benefit you from the code reuse standpoint though. – mwgriffith Mar 15 '11 at 17:24
  • I'm using the JQM (jQueryMobile) lib as this is on a mobile device. Caching is not really a concern as this is used as a sign up page so multiple visits are rarely going to happen. I do like the idea of it being modular though but as far as it being used again, not sure about that. – Phill Pafford Mar 15 '11 at 18:26
1

The key here is not just to generalize your JS, but to also generalize your HTML. You must also change your currentPageA and totalPageA variables to array so they can hold more than one value.

See my Demo: http://jsfiddle.net/Jaybles/b2uRd/

HTML

<!-- Page A -->
<div>
    <span>Page A</span>
    <input class='pageButton' id="page_a_next" name="page_a_next" type="button" value="Next" data-inline="true"/>
    <input class='pageButton' id="page_a_prev" name="page_a_prev" type="button" value="Previous" data-inline="true" /> 
</div>   
<div id="display_page_a_page" name="display_page_a_page">
</div>
<div id="display_page_a_number" name="display_page_a_number">
</div>

<!-- Page B -->
<div>
    <span>Page B</span>
    <input class='pageButton' id="page_b_next" name="page_b_next" type="button" value="Next" data-inline="true" />
    <input class='pageButton' id="page_b_prev" name="page_b_prev" type="button" value="Previous" data-inline="true" /> 
</div>   
<div id="display_page_b_page" name="display_page_b_page">
</div>
<div id="display_page_b_number" name="display_page_b_number">
</div>

JS

var currentPage = {'a':1, 'b':1}; //Should go from A to Z
var totalPage = {'a':113, 'b':115}; //Should go from A to Z

$(".pageButton").click(function(){
    var a = $(this).attr('name').split("_");
    var page = a[1];
    var dir = a[2];
    currentPage[page]  = (dir=='next') ? currentPage[page] + 1 : currentPage[page] - 1;

    if(currentPage[page]<=0) {
        currentPage[page]=1;                
        $('#page_' + page + '_prev').attr('disabled','disabled');
    } else if(currentPage[page] > totalPage[page]) {
        currentPage[page]=totalPage[page];
        $('#page_' + page + '_next').attr('disabled','disabled');
    } else {
        loadPage(page);
    }                
});

loadPage('a');

function loadPage(page){
    $('#page_' + page + '_next').attr('disabled','disabled');
    $('#page_' + page + '_prev').attr('disabled','disabled');

    $.ajax({
        url: 'page_' + page + '.php?page='+currentPage[page],
        type: 'POST',
        error : function (){ document.title='error'; }, 
        success: function (data) {
            $('#display_page_' + page + '_number').html(currentPage[page]+ ' of ' + totalPage[page]);
            $('#display_page_' + page + '_page').html(data);
            $('#page_' + page + '_next').attr('disabled','');
            $('#page_' + page + '_prev').attr('disabled','');
        }
    });
}
Dutchie432
  • 28,798
  • 20
  • 92
  • 109
  • I like this concept except I have a couple follow up questions: 1- the url will change, instead of page_ + page it will be something like prices or colors. 2- instead of using letters could I use names like: instead of a I would like to use prices and instead of b I would like to use colors? – Phill Pafford Mar 15 '11 at 15:44
  • 1
    Absolutely! The array keys (which is essentially what we're talking about) do not have to be 'a' or 'b', they can certainly be 'prices', 'color', or virtually any other string you want. Just stay away from spaces and punctuation. – Dutchie432 Mar 15 '11 at 15:52
  • 1
    `var currentPage = {'prices':1, 'color':1};` and `var totalPage = {'prices':113, 'color':115}` ..... Also, I may be mis-reading your follow-up comment, but if the url changes (and the url is not the same as the key), you can do another array like this.... `var urls = {'prices':'getPrices.php', 'color': 'doColorGet.php'};` or something to that effect. – Dutchie432 Mar 15 '11 at 16:07
  • one small note: var page = a[1]; var dir = a[2]; should be var page = a[0]; var dir = a[1]; – Phill Pafford Mar 15 '11 at 16:45
  • Actually, no... a[0] will contain the text `page` since the name is `page_a_next` ...ie... `0_1_2` – Dutchie432 Mar 15 '11 at 16:47
  • oops sorry, the naming convension in my production script is a little different. I used index 0 and 1 instead. Again thanks for the efforts – Phill Pafford Mar 15 '11 at 16:49
  • Also, on a side note, this code can easily be changed into a jQuery Plugin without changing much code at all. http://docs.jquery.com/Plugins/Authoring – Dutchie432 Mar 15 '11 at 16:50