Ajax Fetch records by php/mysql with Pagination ?


12 Votes, Rating: 4.831 Star2 Stars3 Stars4 Stars5 Stars

Tags: ,

How to fetch records by ajax/php/mysql with pagination ?

Some time i think why i spare my time to add my codes here for all, but really im telling from my heart i want any other guy not waste his/her time to search about these simple things as i did. I juat want to save other time and time is money :) so in sort im saving your money guy’s :D

If you like my post please leave comments, subscribe rss feed

How to Ajax fetch records by php mysql?

Here is the very simple example to fetch records from mysql by php and ajax. In this post i will show you how to make a list without refresh a page. To develop this type of program you just need 2 pages 1 for display list (we can it frontend) and 2nd for coding (call backend ).

we will send request to backend from frontend by ajax and ajax create list.

ajax listing page

<code>
<script>
window.onload = function() {
SANAjax('Listing','1');
};
////////////////////// AJAX
 
var HttPRequest = false;
 
	   function SANAjax(Mode,Page) {
 
		  HttPRequest = false;
		  if (window.XMLHttpRequest) { // Mozilla, Safari,...
			 HttPRequest = new XMLHttpRequest();
			 if (HttPRequest.overrideMimeType) {
				HttPRequest.overrideMimeType('text/html');
			 }
		  } else if (window.ActiveXObject) { // IE
			 try {
				HttPRequest = new ActiveXObject("Msxml2.XMLHTTP");
			 } catch (e) {
				try {
				   HttPRequest = new ActiveXObject("Microsoft.XMLHTTP");
				} catch (e) {}
			 }
		  } 
 
		  if (!HttPRequest) {
			 alert('Cannot create XMLHTTP instance');
			 return false;
		  }
 
			var url = 'SANajax.php';
			var pmeters = 'mode='+Mode+'&Page='+Page;
			HttPRequest.open('POST',url,true);
 
			HttPRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
			HttPRequest.setRequestHeader("Content-length", pmeters.length);
			HttPRequest.setRequestHeader("Connection", "close");
			HttPRequest.send(pmeters);
 
 
			HttPRequest.onreadystatechange = function()
			{
 
			if(HttPRequest.readyState == 3)  // Loading Request
				  {
	document.getElementById("listingAJAX").innerHTML = '<img src="loading.gif" align="center" />';
				  }
 
				 if(HttPRequest.readyState == 4) // Return Request
				  {
		var response = HttPRequest.responseText;
 
 
				   document.getElementById("listingAJAX").innerHTML = response;
				  }
 
			}
 
 
			   }</script>
<p>
<div id="listingAJAX"></div>
</code>

Add this div on your page where you want to display all list

Backend page ( SANAjax.php)

<code>
############# must create your db base connection
 
$strPage = $_REQUEST[Page]
if($_REQUEST[mode]=="Listing"){
$query = "SELECT * FROM Ajax_php_example";
$result = mysql_query($query) or die(mysql_error());
 
$Num_Rows = mysql_num_rows ($result);
 
########### pagins
$Per_Page = 5;   // Records Per Page
 
$Page = $strPage;
if(!$strPage)
{
	$Page=1;
}
 
$Prev_Page = $Page-1;
$Next_Page = $Page+1;
 
$Page_Start = (($Per_Page*$Page)-$Per_Page);
if($Num_Rows&lt;=$Per_Page)
{
	$Num_Pages =1;
}
else if(($Num_Rows % $Per_Page)==0)
{
	$Num_Pages =($Num_Rows/$Per_Page) ;
}
else
{
	$Num_Pages =($Num_Rows/$Per_Page)+1;
	$Num_Pages = (int)$Num_Pages;
}
 
$query.=" order  by CustomerID ASC LIMIT $Page_Start , $Per_Page";
$result = mysql_query($query) or die(mysql_error());
?>
<table border="0">
<tbody>
<tr>
<td>Name</td>
<td>Email</td>
</tr>
<?php
// Insert a new row in the table for each person returned
while($data= mysql_fetch_array($result)){ ?>
<tr>
<td><?php echo $data['Name'] ?></td>
<td><?php echo $data['Email'] ?></td>
</tr>
<div class="resultbg pagination">
<!--Total <?php //echo $Num_Rows;?> Record : -->
<?php
if($Prev_Page) 
{
	echo " <li><a href=\"JavaScript:SANAjax('Listing','$Prev_Page')\"> << Back</a> </li>";
}
 
for($i=1; $i<=$Num_Pages; $i++){
	if($i != $Page)
	{
		echo " <li><a href=\"JavaScript:SANAjax('Listing','$i')\">$i</a> </li>";
	}
	else
	{
		echo "<li class='currentpage'><b> $i </b></li>";
	}
}
if($Page!=$Num_Pages)
{
	echo " <li><a href=\"JavaScript:SANAjax('Listing','$Next_Page')\">Next >></a> </li>";
}
?>
</div>
<?php
############
}else{
echo "<div class='error'>No Records Found!</div>";
}
 } 
 
 ?>
</tbody></table>
</code>
Share/Save/Bookmark

40 Responses to “Ajax Fetch records by php/mysql with Pagination ?”

  1. elancheran says:

    hi thanks for sharing but i am not yet use ur script ..just just now copy the code.

  2. UncleBob says:
  3. SAN says:

    Bob, i have seen your codes, it has some problems.
    1. like function name it should be

    function SANAjax(Mode,page) {

    2. where is the php page ( SANAjax.php ) please add it

    3. <div id="listingAJAX"></div>
    you need to add this div in your html page where all records will display

  4. Canser says:

    Not working… Your codes seems to be need help.

  5. SAN says:

    have you created db connection.. ???
    without db connection it not fetch any records. send us url.

  6. Malik says:

    not checked yet ……. :)

  7. SAN says:

    Please check working demo now

  8. Jamie says:

    I have copied your script from above but it still doesn’t work. As well as updating the demo did you update the script?

  9. SAN says:

    Jamie, Post is updated already, but if you check, you need to add your database connection codes yourself. above codes not included that.

  10. SAN says:

    jamie, or you can give me your website url, so i can check and let you know exactly that problem

  11. Amiya says:

    Thank you so much.
    I have implemented ur code with little change according to my requirement.

  12. margaret says:

    This doesn’t work. Can you please post the php file? I have revised the php file, found some errors and still doesn’t work.

  13. Lee says:

    Your script is full of errors! unexpexted T_Else.. having a else on a while.. whats with the ? Most of the php is displayed on the page along with "invalid mysql_query" codes.. please email me about it

  14. SAN says:

    you guys need to know.. that this codes need your db connection, and your table names etc. in sort this just a example.. if you change all php codes as per you, it will work well

  15. Lio says:

    wow..i have test these codes…nice..very nice..i’ll waiting for your next post..thank you, you solve my problem guys..

  16. jeebsion says:

    SAN .. by any chance, could you release the exact code for the demo page you made? thank you :-)

  17. SAN says:

    Jeepsion, the codes are exact as on demo page, just we had different database connected to show you working

  18. Emadz says:

    ITs great and very helpful

  19. jeebsion says:

    oh nevermind SAN, actually I got it working just after I posted the comment .. :-) .. thanx by the way

  20. Gulfam Mustafa says:

    I tried to implement your code but getting following error.

    Parse error: syntax error, unexpected T_ELSE in C:\AppServ\www\radio\files\includes\staffrequestline.php on line 81

    I have connected database etc. But still same error. Please help me.

  21. SAN says:

    Gulfam, please send me url of those pages so we can check that out

  22. venkat says:

    hi san, is it possible to fetch posts from my blog(local wordpress) and place them in a div. as the above post helps me to create a sidebar, i want those post fetched act as links and display on the main column. I mean one post displayed at a time..

    here is my link. http://www.ead09.org.uk/nars. that my website and planning to use your code for (tubelog). please do help. this site(www.madebysofa.com/#blog) is doing what i’m looking for..!! within the blog link!!

  23. SAN says:

    Vemkat, yes its possible, if you check “demo link” http://www.w3cgallery.com/examples/Ajax-Fetch-records-by-php-mysql-with-Pagination.php
    we also fetching blogs by same technique. you also can fetch that.

  24. venkat says:

    san, i’ve seen the demo link and its so cool!! Am even looking forward to assign those title of posts to their content. but, dont get to see.. how to create it.!! i’ve managed to pull the first post from database using this(http://www.jamischarles.com/blog/how-to-add-5-full-wordpress-posts-on-an-external-html-page/). but, i want to use the fetching of all posts in a side bar and the recent most one on the content place holder. any help appreciated..!

  25. venkat says:

    parse error: syntax error, unexpected T_IF in /Library/WebServer/Documents/nars/SANAjax.php on line 14

    any help please,,,!!

  26. sankar says:

    your code has been nothing display

  27. SAN says:

    Sankar, creat you db conntion your self with your codes, then it will work out

  28. kamalkant says:

    hi San this code is using in jsp then how it is work and what is the file in front end and back end.

    thanks
    kamal

  29. SAN says:

    Kamal, it will be so simple. just change Php codes in JSP on SANAjax.php page.

    rest all are ajax codes, can be used in JSP codes too

  30. Md. Ashraf Jahan says:

    Its nice. But is it possible to show page number as 1 2 3 4 5….100 Next

  31. SAN says:

    yes.. its possible.. need some changes in php file

  32. Alfred Antoine says:

    Thanks, you really saved my money(time)

  33. Cialis says:

    K7BvaU Thank you for the material. Do you mind if I posted it in her blog, of course, with reference to your site?

  34. Cialis says:

    Rcsp9v Excellent article, I will take note. Many thanks for the story!

  35. Ronald says:

    This line is giving me an error.

    Parse error: parse error in C:\htdocs\mywebsite\SANAjax.php on line 9

    if($_REQUEST[mode]==”Listing”){

  36. taru says:

    /////a lot error but finally solved ——thx

    //////////////////////////code start (SANAjax.php)//////////////
    <?php

    define(’DB_HOST’, ‘localhost’);
    define(’DB_USER’, ‘root’);
    define(’DB_PASSWORD’, ”);
    define(’DB_DATABASE’, ‘carhaat_db’);

    //Array to store validation errors

    $errmsg_arr = array();

    //Validation error flag

    $errflag = false;

    //Connect to mysql server

    $link = mysql_connect(DB_HOST, DB_USER, DB_PASSWORD);

    if(!$link) {

    die(’Failed to connect to server: ‘ . mysql_error());

    }

    //Select database

    $db = mysql_select_db(DB_DATABASE);

    if(!$db) {

    die(”Unable to select database”);

    }

    $strPage = $_REQUEST[Page]; //got error
    if($_REQUEST[mode]==”Listing”){
    $query = “SELECT * FROM members”;
    $result = mysql_query($query) or die(mysql_error());

    $Num_Rows = mysql_num_rows ($result);

    ########### pagins
    $Per_Page = 5; // Records Per Page

    $Page = $strPage;
    if(!$strPage)
    {
    $Page=1;
    }

    $Prev_Page = $Page-1;
    $Next_Page = $Page+1;

    $Page_Start = (($Per_Page*$Page)-$Per_Page);
    if($Num_Rows

    Name
    Email

    <!–Total Record : –>
    <?php
    if($Prev_Page)
    {
    echo ” << Back “;
    }

    for($i=1; $i<=$Num_Pages; $i++){
    if($i != $Page)
    {
    echo ” $i “;
    }
    else
    {
    echo “ $i “;
    }
    }

    if($Page!=$Num_Pages)
    {
    echo ” Next >> “;
    }
    ?>

    <?php
    ############
    }else{
    echo “No Records Found!”;
    }
    //} eror

    ?>

    ////////////////////////code end SANAjax.php//////////////////////

  37. minh says:

    Love the demo but the script does not work. Can someone email me the html and php that is working to minhkhoa@hotmail.com. thanks.

  38. Nooranium says:

    SANajax.php code — working
    just replate the connection command with your connection settings
    the below code reads from table called ‘randoms’ and displays one field ‘val’

    Backend

    <?php

    require(’connect.php’);
    include ‘library/config.php’;
    include ‘library/opendb.php’;

    $strPage = $_REQUEST[Page];
    if($_REQUEST[mode]==”Listing”){
    $query = “SELECT * FROM randoms”;
    $result = mysql_query($query) or die(mysql_error());

    $Num_Rows = mysql_num_rows ($result);

    ########### pagins
    $Per_Page = 5; // Records Per Page

    $Page = $strPage;
    if(!$strPage)
    {
    $Page=1;
    }

    $offset = ($Page - 1) * $Per_Page;

    $Prev_Page = $Page-1;
    $Next_Page = $Page+1;

    $Page_Start = (($Per_Page*$Page)-$Per_Page);

    $query.=” order by val ASC LIMIT $Page_Start , $Per_Page”;
    $result = mysql_query($query) or die(mysql_error());

    if($Num_Rows<=$Per_Page)
    {
    $Num_Pages =1;
    }
    else if(($Num_Rows % $Per_Page)==0)
    {
    $Num_Pages =($Num_Rows/$Per_Page) ;
    }
    else
    {
    $Num_Pages =($Num_Rows/$Per_Page)+1;
    $Num_Pages = (int)$Num_Pages;
    }

    while($data = mysql_fetch_array($result))
    {
    echo $data['val'] . ”;
    }

    $query = “SELECT COUNT(val) AS numrows FROM randoms”;
    $result = mysql_query($query) or die(’Error, query failed’);
    $row = mysql_fetch_array($result, MYSQL_ASSOC);
    $numrows = $row['numrows'];
    $maxPage = ceil($numrows/$Per_Page);
    ?>

    $maxPage?$maxPage:$pagetotal;
    if ($pagenum - $pagelimit =1 && $pagenum + $pagelimit =1 && $pagenum + $pagelimit > $maxPage) {
    $pagemin = ($maxPage-$pagetotal+1) $maxPage) {
    $pagemax = $maxPage;
    }
    for($ppage = 1; $ppage <= $pagemax; $ppage++)
    {
    if ($ppage == $pagenum)
    {
    $nav .= ” $ppage “; // no need to create a link to current page
    }
    else
    {
    $nav .= ” “.floor($ppage).” “;
    }
    }

    if ($pagenum > 1)
    {
    $ppage = $pagenum - 1;
    $prev = ” [Prev] “;

    $first = ” [First Page] “;
    }
    else
    {
    $prev = ‘ ’; // we’re on page one, don’t print previous link
    $first = ‘ ’; // nor the first page link
    }

    if ($pagenum < $maxPage)
    {
    $ppage = $pagenum + 1;
    $next = ” [Next] “;

    $last = ” [Last Page] “;
    }
    else
    {
    $next = ‘ ’; // we’re on the last page, don’t print next link
    $last = ‘ ’; // nor the last page link
    }

    // print the navigation link
    echo $first . $prev . $nav . $next . $last;

    include ‘../library/closedb.php’;

    }else{
    echo “No Records Found!”;
    }

    ?>

  39. design web london says:

    your code is working fine i used it on my new website for populating data like twitter thanks allot for sharing i donno its optimised in terms of bandwidth or not but who cares ;) its working so hurrey …

  40. Renjith says:

    Great work. Thanks. I have implemented the same in my website…
    Thanks again.

Leave a Reply


CSS (Design) - TOP.ORG