Php ajax pagination, please help

I have used a pagination script before when building sites but not when the data is being called via ajax.

Below is the php script which is called via ajax to return the data.


//Set limit script for stock
if(!isset($_GET['page'])){
    $page = 1;
} else {
    $page = $_GET['page'];
}
$max_results = 6;
$from = (($page * $max_results) - $max_results); 
	
$model = $_GET['model'];


//build query
$query = "SELECT * FROM MyTable WHERE Type = '6'";
if($model != '')
	$query .= " AND Model LIKE '%$model%'";
$query .=" ORDER BY Price ASC LIMIT $from, $max_results";

	//Execute query
$qry_result = mysql_query($query) or die(mysql_error());

$display_string = "";
	// show each returned value
while($row = mysql_fetch_array($qry_result)){
	$display_string .= "$row[Model]";
}
echo "Query: " . $query . "<br />";
echo $display_string;

This is the script I would usually use for the pagination, I would just echo $pagination on the page where I wanted the links to appear.


function pagination_four($total_pages,$page){

    global $webpage;
  
    $pagination='
                  ';
                  
        //if more than one page              
                  
    if($total_pages!=1){
    
        //change these for links per page
        //
        //  $max is the visible links
        // $shift is the page the links start to shift on
        //
        // e.g. $max-$shift+1 = shifting page
    
        $max = 6;
        $shift = 3;
        
        
        //used in the loop
        
        $max_links = $max+1;
        $h=1;  
        
            //if more pages than max links
        
        if($total_pages>=$max_links){
        
                //if page is greater than shifing page and the last page is not there
        
            if(($page>=$max_links-$shift)&&($page<=$total_pages-$shift)){  
            
                //set the loop values based on the current page
            
                $max_links = $page+$shift;
                $h=$max_links-$max;
            }
            
            //if the last link is visible then set the top of the loop to
            // the total_pages
            // otherwise we get links to pages with no results
            
            if($page>=$total_pages-$shift+1){
                $max_links = $total_pages+1;
                $h=$max_links-$max;
            } 
        }
        
        //if less pages than max links then set the top of the loop to total pages
        
        else{
            $h=1;
            $max_links = $total_pages+1;
        }

            //first and prev buttons
        if($page>'1'){
            $pagination.= '<a href="'.$webpage.'?page='.($page-1).'&pagesubmitted=1&model='.$_REQUEST[model].'">Prev</a>';
        }
        
        //loop through the results;
        
        for ($i=$h;$i<$max_links;$i++){
        
                //if current page no link
        
            if($i==$page){
                $pagination.='<a class="current">'.$i.'</a>&nbsp; ';
            }
            
                //else provide a link
            
            else{
                $pagination.= '<a href="'.$webpage.'?page='.$i.'&pagesubmitted=1&model='.$_REQUEST[model].'">'.$i.'</a>&nbsp;';
            }
        }
        //next and last buttons
        if(($page >='1')&&($page!=$total_pages)){
           $pagination.= '<a href="'.$webpage.'?page='.($page+1).'&pagesubmitted=1&model='.$_REQUEST[model].'">Next</a>';
			$pagination.= 'of&nbsp;<a href="'.$webpage.'?page='.$total_pages.'&pagesubmitted=1&model='.$_REQUEST[model].'">'.$total_pages.'</a>&nbsp;&nbsp;&nbsp;';
        }

//return first page link
if($page>'1'){
            $pagination.= '<a href="'.$webpage.'?page=1&pagesubmitted=1&model='.$_REQUEST[model].'">Return to 1st Page</a>';
        }
				
    }
    //one page of results
    else{
        $pagination.='<a href="" class="current">1</a>';
    }
    $pagination.='
              ';
    return($pagination);
}

Can anyone please help me in putting this together so it will work from the ajax called script?

I’d be very greatful of some help with this.

Can anyone help me with this please?
Even tell me a better way to do the pagination than I’m trying to?

Have your PHP (that AJAX calls) generate the HTML as normal, then use javascript to receive that HTML and put it into a container (DIV or such)

Hi StarLion!
Thanks for the reply but I don’t follow. I can get the php script to limit the number of returned rows from the db inside the ajax script but how do I then set up the pagination links on my page so that they will work correctly?

right.

two pages; page 1 is the ‘holder’, page 2 is the ‘records’.

holder has a blank <div id=‘moo’></div> tag.
Somewhere in holder you have a predefined initial state (or default parameters)

Your AJAX is inside Holder. That AJAX call calls for records.php?page=X&whatever=other&variables=youwant

records.php returns a paginated record set, with the links set to call the AJAX function passing it the new page num, so that it can in turn put it onto the new AJAX url…

the AJAX receiver (the thing that responds when AJAX retrieves the page) takes what it returns and puts it into that div (document.getElementById(‘moo’).innerHTML = return , or something along that line)

Right I’ll have a go at that, I thinkk I understand what you mean now. I’ve been struggling most of the day with what I think should be an easy js function to fix but no-one on the js forum is replying to me. Thanks very much for taking the time to help me with this it really is appreciated.

Don’t suppose your as good at js as you are wit php? lol :wink:

Not as-good, no. It’s not hard to do what you’re doing though.

Give it a whack, and if it doesnt work, come back, and show us:
Your AJAX functions (both calling and receiving)
Your PHP that that AJAX calls.

Right sorry but I’m needing somemore help with this please.
I can’t get this to work at all, can you have a look and tell me where I’m going wrong with this please?

Here’s the coding of my start page:


<?php 
//Set limit script for stock
if(!isset($_GET['page'])){
    $page = 1;
} else {
    $page = $_GET['page'];
}
$max_results = 6;
$from = (($page * $max_results) - $max_results); 

$myquery = "SELECT COUNT(*) as Num FROM MYTable WHERE Type ='6' ORDER BY Price ASC";
$total_results = mysql_result(mysql_query("$myquery"),0);
// Figure out the total number of pages. Always round up using ceil()
$total_pages = ceil($total_results / $max_results);
$yourquery = "SELECT * FROM MYTable WHERE Type='6' ORDER BY Price ASC $limit";


?>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script language="javascript" type="text/javascript">
<!-- 
//Browser Support Code
function ajaxFunction(){
	var ajaxRequest;  // The variable that makes Ajax possible!
	
	try{
		// Opera 8.0+, Firefox, Safari
		ajaxRequest = new XMLHttpRequest();
	} catch (e){
		// Internet Explorer Browsers
		try{
			ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");
		} catch (e) {
			try{
				ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");
			} catch (e){
				// Something went wrong
				alert("Your browser broke!");
				return false;
			}
		}
	}
	// Create a function that will receive data sent from the server
	ajaxRequest.onreadystatechange = function(){
		if(ajaxRequest.readyState == 4){
			var ajaxDisplay = document.getElementById('ajaxDiv');
			ajaxDisplay.innerHTML = ajaxRequest.responseText;
		}
	}
	var drop_1 = document.getElementById('drop_1').value;
	
	/*if (document.myForm.model[i].selected) {
	var model = document.getElementById('model').value;
	}*/ 
	
	var model = document.getElementById('model').value;
	var mileage = document.getElementById('mileage').value;
	var colour = document.getElementById('colour').value;
	var age = document.getElementById('age').value;
	var min_price = document.getElementById('min_price').value;
	var max_price = document.getElementById('max_price').value;
	var min_engine_size = document.getElementById('min_engine_size').value;
	var max_engine_size = document.getElementById('max_engine_size').value;
	var pics = document.getElementById('pics').value;
	var keywords = document.getElementById('keywords').value;
	var queryString = "?drop_1=" + drop_1 + "&model=" + model + "&mileage=" + mileage + "&colour=" + colour + "&age=" + age + "&min_price=" + min_price + "&max_price=" + max_price + "&min_engine_size=" + min_engine_size + "&max_engine_size=" + max_engine_size + "&pics=" + pics + "&keywords=" + keywords;
	ajaxRequest.open("GET", "filtered.php" + queryString, true);
	ajaxRequest.send(null); 
}
</script>
</head>
<body>

<div id='ajaxDiv'>
<?php
$query = "SELECT * FROM Used_Stock WHERE Type='6' ORDER BY Price ASC LIMIT $from, $max_results";
echo "query : $query<br />";
$sql = mysql_query($query) or die(mysql_error());
while($row_stock = mysql_fetch_array($sql)){
    // Build your formatted results here.			
?>
        <?php include("../includes/used-bike-display.php"); ?>
        <?php 
		};
		?>
        <div id="pagination"><ul>
		<?php
		//Show page links
		for($i=1; $i<=$pages; $i++)
		{
			echo '<li id="'.$i.'">'.$i.'</li>';
		}?>
		</ul></div></div>
       
</body>
</html>

Here’s the coding of my filtered.php page, which receives the data and returns it to the ajaxDiv in my start page:


<?php include("../includes/config.php");
//Set limit script for stock
if(!isset($_GET['page'])){
    $page = 1;
} else {
    $page = $_GET['page'];
}
$max_results = 6;
$from = (($page * $max_results) - $max_results); 
	
$thisYear = date("Y");

$drop_1 = $_GET['drop_1'];
$model = $_GET['model'];
$mileage = $_GET['mileage'];
$colour = $_GET['colour'];
$age = $_GET['age'];
$min_price = $_GET['min_price'];
$max_price = $_GET['max_price'];
$min_engine_size = $_GET['min_engine_size'];
$max_engine_size = $_GET['max_engine_size'];
$pics = $_GET['pics'];
$keywords = $_GET['keywords'];
$MyYear = ($thisYear - $age);


//build query
$query = "SELECT * FROM MYTABLE WHERE Type = '6'";
if($drop_1 != '')
	$query .= " AND Make = '$drop_1'";
if($model != '')
	$query .= " AND Model LIKE '%$model%'";
if($mileage != '')
	$query .= " AND Mileage <= $mileage";
if($colour != '')
	$query .= " AND Colour LIKE '%$colour%'";
if($age != '')
	$query .= " AND Year >= $MyYear";
if($min_price != '')
	$query .= " AND Price >= $min_price";
if($max_price != '')
	$query .= " AND Price <= $max_price";
if($min_engine_size != '')
	$query .= " AND Engine_Size >= $min_engine_size";
if($max_engine_size != '')
	$query .= " AND Engine_Size <= $max_engine_size";
if($pics != '')
	$query .= " AND Picture_Refs!=''";
if ($keywords != '' && $keywords != 'Keywords e.g. TDi') {
	$query .= " AND Options LIKE '%$keywords%'";//keywords from spec
	}
$query .=" ORDER BY Price ASC LIMIT $from, $max_results";
	//Execute query
$qry_result = mysql_query($query) or die(mysql_error());

$display_string = "";
	// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
	$display_string .= "<div class='individual-cars'>";
	$display_string .= "<h1>$row[Year] $row[Make] $row[Model] $row[Engine_Size]cc <span class='price'>&pound;$row[Price]</span></h1>";
	$images = explode(',', $row[Picture_Refs]);
    $src = "http://www.easternwestern.co.uk/admin/Stock//".$images[0];
    $display_string .= "<img src='".$src."' alt='$row[Make] $row[Model]' for sale' width='150'>";
	$minText = substr($row[Options],0,150); 
	$display_string .= "<p><span>$row[Mileage]mls, $row[Colour]</span> ".$minText." ...</p>";
	$display_string .= "</div>";
}
echo "Query: " . $query . "<br />";
//$display_string .= "</table>";
echo $display_string;
?>

There is a form on the start page also which uses select elements to call the ajaxFunction()

Really appreciate the help with this.

Okay. First thing’s first. I’m using the following definitions:
Caller: The page containing the javascript that the person actually visits.
Catcher: The PHP page that AJAX gets its info from.

Step 1:


$max_results = 6;
$from = (($page * $max_results) - $max_results); 

$myquery = "SELECT COUNT(*) as Num FROM MYTable WHERE Type ='6' ORDER BY Price ASC";
$total_results = mysql_result(mysql_query("$myquery"),0);
// Figure out the total number of pages. Always round up using ceil()
$total_pages = ceil($total_results / $max_results);
$yourquery = "SELECT * FROM MYTable WHERE Type='6' ORDER BY Price ASC $limit";

This stuff belongs in your catcher, not your caller. Get rid of it.

Step 2:


function ajaxFunction(){

lets make this


function ajaxFunction(pagenum){

and add to your queryString the “&page=”+pagenum

Step 3:
ajaxDiv should have nothing in it to begin with. Empty div.

Step 4:
Add:


onload="ajaxFunction(<?php echo $page; ?>)"

to your Body tag.

Now, your Caller is ready; and when it first starts up, it will pull up the relevant results.

On to the Catcher!

You really shouldnt need to check $_GET[‘page’], but it doesnt necessarily hurt.

At the bottom of your catcher, you need to put the paginate HTML generating stuff, and the link code would look something like
<a href=‘#’ onclick=‘return false;’ onmousedown=‘ajaxFunction(<thepagenumbertodisplaygoesherewithPHP>)’>

Thanks for the help, I’ve got it set up like you said. The data pulls into the page initially when the page is loaded. The part that is falling over just now is the pagination. I just can’t get it to show. Initially there should be 40 results pulling in paginated at 6 per page.

Here’s the full code in the catcher page. Can you please tell me whats wrong with it?


<?php include("../includes/config.php");
//Set limit script for stock
if(!isset($_GET['page'])){
    $page = 1;
} else {
    $page = $_GET['page'];
}
$max_results = 6;
$from = (($page * $max_results) - $max_results); 
	
$thisYear = date("Y");

$drop_1 = $_GET['drop_1'];
$model = $_GET['model'];
$mileage = $_GET['mileage'];
$colour = $_GET['colour'];
$age = $_GET['age'];
$min_price = $_GET['min_price'];
$max_price = $_GET['max_price'];
$min_engine_size = $_GET['min_engine_size'];
$max_engine_size = $_GET['max_engine_size'];
$pics = $_GET['pics'];
$keywords = $_GET['keywords'];
$MyYear = ($thisYear - $age);


//build query

$howmanyquery = "SELECT COUNT(*) as NUM FROM Used_Stock WHERE Type = '6'";
if($drop_1 != ''){
	$howmanyquery .= " AND Make = '$drop_1'";
	}
if($model != ''){
	$howmanyquery .= " AND Model LIKE '%$model%'";
	}
if($mileage != ''){
	$howmanyquery .= " AND Mileage <= $mileage";
	}
if($colour != ''){
	$howmanyquery .= " AND Colour LIKE '%$colour%'";
	}
if($age != ''){
	$howmanyquery .= " AND Year >= $MyYear";
}
if($min_price != ''){
	$howmanyquery .= " AND Price >= $min_price";
}
if($max_price != ''){
	$howmanyquery .= " AND Price <= $max_price";
}
if($min_engine_size != ''){
	$howmanyquery .= " AND Engine_Size >= $min_engine_size";
}
if($max_engine_size != ''){
	$howmanyquery .= " AND Engine_Size <= $max_engine_size";
}
if($pics != ''){
	$howmanyquery .= " AND Picture_Refs != ''";
}
if ($keywords != '' && $keywords != 'Keywords e.g. TDi') {
	$howmanyquery .= " AND Options LIKE '%$keywords%'";//keywords from spec
	}
	//Execute query
$total_results = mysql_result(mysql_query("$howmanyquery"),0);


$query = "SELECT * FROM Used_Stock WHERE Type = '6'";
if($drop_1 != '')
	$query .= " AND Make = '$drop_1'";
if($model != '')
	$query .= " AND Model LIKE '%$model%'";
if($mileage != '')
	$query .= " AND Mileage <= $mileage";
if($colour != '')
	$query .= " AND Colour LIKE '%$colour%'";
if($age != '')
	$query .= " AND Year >= $MyYear";
if($min_price != '')
	$query .= " AND Price >= $min_price";
if($max_price != '')
	$query .= " AND Price <= $max_price";
if($min_engine_size != '')
	$query .= " AND Engine_Size >= $min_engine_size";
if($max_engine_size != '')
	$query .= " AND Engine_Size <= $max_engine_size";
if($pics != '')
	$query .= " AND Picture_Refs!=''";
if ($keywords != '' && $keywords != 'Keywords e.g. TDi') {
	$query .= " AND Options LIKE '%$keywords%'";//keywords from spec
	}
$query .=" ORDER BY Price ASC LIMIT $from, $max_results";
	//Execute query
$qry_result = mysql_query($query) or die(mysql_error());

$display_string = "";
	// Insert a new row in the table for each person returned
while($row = mysql_fetch_array($qry_result)){
	$display_string .= "<div class='individual-cars'>";
	$display_string .= "<h1>$row[Year] $row[Make] $row[Model] $row[Engine_Size]cc <span class='price'>&pound;$row[Price]</span></h1>";
	$images = explode(',', $row[Picture_Refs]);
    $src = "http://www.easternwestern.co.uk/admin/Stock/HDEdinburgh_media/".$images[0];
    $display_string .= "<img src='".$src."' alt='$row[Make] $row[Model]' for sale' width='150'>";
	$minText = substr($row[Options],0,150); 
	$display_string .= "<p><span>$row[Mileage]mls, $row[Colour]</span> ".$minText." ...</p>";
	$display_string .= "</div>";
}
echo "Query: " . $query . "<br />";
//$display_string .= "</table>";
echo $display_string;
//echo "<a href='#' onclick='return false;' onmousedown='ajaxFunction(".$page.")'>Page</a>"



/*Pagination Stuff*/
function pagination_four($total_pages,$page){

    global $webpage;
  
    $pagination='';
                  
        //if more than one page              
                  
    if($total_pages!=1){
    
        //change these for links per page
        //
        //  $max is the visible links
        // $shirt is the page the links start to shift on
        //
        // e.g. $max-$shirt+1 = shifting page
    
        $max = 6;
        $shift = 3;
        
        
        //used in the loop
        
        $max_links = $max+1;
        $h=1;  
        
            //if more pages than max links
        
        if($total_pages>=$max_links){
        
                //if page is greater than shifing page and the last page is not there
        
            if(($page>=$max_links-$shift)&&($page<=$total_pages-$shift)){  
            
                //set the loop values based on the current page
            
                $max_links = $page+$shift;
                $h=$max_links-$max;
            }
            
            //if the last link is visible then set the top of the loop to
            // the total_pages
            // otherwise we get links to pages with no results
            
            if($page>=$total_pages-$shift+1){
                $max_links = $total_pages+1;
                $h=$max_links-$max;
            } 
        }
        
        //if less pages than max links then set the top of the loop to total pages
        
        else{
            $h=1;
            $max_links = $total_pages+1;
        }

            //first and prev buttons
        if($page>'1'){
            $pagination.= '<a href="'.$webpage.'?page='.($page-1).'&pagesubmitted=1&make='.$_REQUEST[make].'&model='.$_REQUEST[model].'&variant='.$_REQUEST[variant].'&min='.$_REQUEST[min].'&max='.$_REQUEST[max].'">Prev</a>';
        }
        
        //loop through the results;
        
        for ($i=$h;$i<$max_links;$i++){
        
                //if current page no link
        
            if($i==$page){
                $pagination.='<a class="current">'.$i.'</a>&nbsp;';
            }
            
                //else provide a link
            
            else{
                $pagination.= '<a href="'.$webpage.'?page='.$i.'&pagesubmitted=1&cat='.$_REQUEST[cat].'&subcat='.$_REQUEST[subcat].'&subcat3='.$_REQUEST[subcat3].'&min='.$_REQUEST[min].'&max='.$_REQUEST[max].'">'.$i.'</a>&nbsp;';
            }
        }
        //next and last buttons
        if(($page >='1')&&($page!=$total_pages)){
           $pagination.= '<a href="'.$webpage.'?page='.($page+1).'&pagesubmitted=1&cat='.$_REQUEST[cat].'&subcat='.$_REQUEST[subcat].'&subcat3='.$_REQUEST[subcat3].'&min='.$_REQUEST[min].'&max='.$_REQUEST[max].'">Next</a>';
			$pagination.= 'of&nbsp;<a href="'.$webpage.'?page='.$total_pages.'&pagesubmitted=1&cat='.$_REQUEST[cat].'&subcat='.$_REQUEST[subcat].'&subcat3='.$_REQUEST[subcat3].'&min='.$_REQUEST[min].'&max='.$_REQUEST[max].'">'.$total_pages.'</a>&nbsp;&nbsp;&nbsp;';
        }

//return first page link
if($page>'1'){
            $pagination.= '<a href="'.$webpage.'?page=1&pagesubmitted=1&cat='.$_REQUEST[cat].'&subcat='.$_REQUEST[subcat].'&subcat3='.$_REQUEST[subcat3].'&min='.$_REQUEST[min].'&max='.$_REQUEST[max].'">Return to 1st Page</a>';
        }
				
    }
    //one page of results
    else{
        $pagination.='<a href="" class="current">1</a>';
    }
    $pagination.='';
    return($pagination);
}


echo "<div id='pagination'><ul>";
		//Show page links
		for($i=1; $i<=$pages; $i++)
		{
			echo "<li id=".$i."><a href='#' onclick='return false;' onmousedown='ajaxFunction(".$page.")'>".$i."</li>";
		}
echo "</ul></div>".$total_results."</div>";
echo $pagination;

?>

Making progress with this I think, got a few bugs to sort out but I’ve now managed to get some of the pagination script to work.