3
votes

How do I use AJAX to get the Next/Previous Page(s).

How to call in a browser:

page.php?page=1-1

or

page.php?page=1

The return is just text.

Should load pages in this format:

1-1 or 1

When the user clicks the next/previous page button(s) how do I pass that page number to the ajax call and display the results.

Also how do I keep track of what page the user is currently viewing? And how do I put a max min for pages, like I have 100 pages don't make call for page 101

http://jsfiddle.net/2b8gR/5/

HTML

<input id="loadPages" name="loadPages" type="button" value="Next" />
<input id="loadPages" name="loadPages" type="button" value="Previous" /> 
<div id="displayResults" name="displayResults">
</div>

JS (This is not working)

$("#loadPages").click(function(){
    $.ajax({
        url: 'page.php',
        data:{'page': '1-1'},
        error : function (){ alert('Error'); }, 
        success: function (returnData) {
            alert(returnData);
            $('#displayResults').append(returnData);
        }
    });
});
1
Your javascript has the following errors: Error: Problem at line 11 character 1: Expected ')' and instead saw ''. } Problem at line 11 character 1: Missing semicolon. } Patrick Beardmore
Sry did that fix the error? Firebug is not working in Chrome for me right now, sigh...Phill Pafford
I believe your data field is also screwy. try data: 'page=1-1' or data:{'page': '1-1'}Dutchie432

1 Answers

4
votes

Try something like this... Keep a global variable called currentPage and simply adjust the page number accordingly.

LIVE DEMO http://jsfiddle.net/Jaybles/MawSB/

HTML

<input id="next" type="button" value="Next" />
<input id="prev" type="button" value="Previous" /> 
<div id="displayResults" name="displayResults">Current Page: 1</div>

JS

var currentPage=1;
loadCurrentPage();

$("#next, #prev").click(function(){
    currentPage = 
        ($(this).attr('id')=='next') ? currentPage + 1 : currentPage - 1;

    if (currentPage==0) //Check for min
        currentPage=1;
    else if (currentPage==101) //Check for max
        currentPage=100;
    else
        loadCurrentPage();
});

function loadCurrentPage(){
    $('input').attr('disabled','disabled'); //disable buttons

    //show loading image
    $('#displayResults').html('<img src="http://blog-well.com/wp-content/uploads/2007/06/indicator-big-2.gif" />'); 

    $.ajax({
        url: '/echo/html/',
        data: 'html=Current Page: ' + currentPage+'&delay=1',
        type: 'POST',
        success: function (data) {
            $('input').attr('disabled',''); //re-enable buttons
            $('#displayResults').html(data); //Update Div
        }
    });
}

Then your php page can access $_REQUEST['page']; and return data accordingly.