Ajax Fetch records by php/mysql with Pagination ?


36 Votes, Rating: 4.441 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 icon smile Ajax Fetch records by php/mysql with Pagination ? so in sort im saving your money guy’s icon biggrin Ajax Fetch records by php/mysql with Pagination ?

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

 
<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="loader.gif" align="center" />';
				  }
 
				 if(HttPRequest.readyState == 4) // Return Request
				  {
		var response = HttPRequest.responseText;
 
 
				   document.getElementById("listingAJAX").innerHTML = response;
				  }
 
			}
 
 
			   }</script>
<p>
<div id="listingAJAX"></div>
</p>

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

Backend page ( SANAjax.php)

$dbhost = 'localhost';
$dbuser = 'root';
$dbpass = '';
 
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ('Error connecting to mysql');
 
$dbname = 'test';
mysql_select_db($dbname);
############# must create your db base connection
 
$strPage = $_REQUEST[Page];
if($_REQUEST[mode]=="Listing"){
 
$query = "SELECT * FROM user";
$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<=$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 Id 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
if(mysql_num_rows($result) > 0 ) {
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 : -->
<?
}
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>";
}
 } 
 
 ################ end
Share/Save/Bookmark

77 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.

  41. Ankit says:

    Hi
    If page count is 100 than, page numbers will be shown as 1 2 3 4 5 6….100. It will look so terrible. how to do like “Next 1 2 3 4 5 Prev” and rest of them (up to 100 pages) be hidden. when click on 4 or 5 it will show the hidden pagination what is the solution for it? Can you help me?

  42. shub says:

    Hi
    I found this working good by making little adjustments…thanks for the efforts taken..but then i need the preloader image to be loaded each and every time before navigating to other pages.Can you help me?

  43. Luqman says:

    Hi, Thanks for the nice code. With small fixes its working fine for me.

  44. Sopheak says:

    Thanks for useful code. It works so good and easy to rectify.

  45. James says:

    Do you need any Javascript Library Plugins for this, and also what about being able to include input from the user ?

    Thanks

  46. Sujit says:

    Can anybody post an updated download link for this script as it seems my dreamweaver giving alot of errors even though i have duplicated same as u guys have posted..thanks in advance.

  47. Rakesh says:

    Above code is not please send working code.

  48. mena says:

    hi SAN i think there are some errors in your php code. i did my db connection…but still not working. i need help can you add this msn? vodsnap@hotmail.com

  49. SAN says:

    mena, rakesh, we have tested these codes, if you make them little change as per your db connection these works

  50. SAN says:

    Guys! I have added all files to download now, try and let us know

  51. Sabbir says:

    Thanks Mr. SAN. I just download though. People like you help us in many way. I’m proud to say that your dedication just lead us bright future. Thanks a Lot. All the best. Wish you success in every step.

  52. Nag says:

    Hi This code is not working..try it as many times u can..but demo is very nice…Please email if any body can to kommuri.nagarjuna@gmail.com

  53. Mq Tontoh says:

    I managed to use it in my project - an image gallery. Slight alterations and it is brilliant. Thanks SAN.

  54. Marwa says:

    SAN please help i installed your cod is perfect but my prob that all pages was display and link not working heeeepl !! thx

  55. Marwa says:

    my DB connection work perfectly !!!

  56. Marwa says:

    finallyyyy it’s oki thx !!

  57. Jeff says:

    Hey First off all i’d like to thank you for sharing this wonderfull code

    But i have a question is it possible to set the page numbers align to the left under the results ?

  58. Samuel says:

    Hello,

    Can you please show us how to implement the pagination like 1234….10111213?

  59. JB says:

    I have got the ajax paginatoin script working but I’m having trouble getting it into my already ajaxed page

    so I have a link that loads a page into a div into my main page that page loads data from a mysql db

    the ajax pagination works if it’s on a page by itself but if I try to load it into the ajaxed div element it does not load the data

  60. jb says:

    I had to strip it down quite a bit used my existing function to create my XMLHttpRequest(); placed it all in my head and had a onclick() event on my menu that executed the ajax function to call the paggination script.

    This helped set me in the right direction

  61. ketan lathiya says:

    previous error was solved..but i have some new errors like:

    Notice: Use of undefined constant Page - assumed ‘Page’ in H:\wamp\www\Ajax-Fetch-records-by-php-mysql-with-Pagination\SANajax.php on line 12

    Notice: Use of undefined constant mode - assumed ‘mode’ in H:\wamp\www\Ajax-Fetch-records-by-php-mysql-with-Pagination\SANajax.php on line 13

  62. ketan lathiya says:

    Okk. Done…
    Thanks SAN..its working now..
    i have to make four changes in ur script..
    PAGE : SANajax.php
    1) on line 69 :- <?php instead of <?
    2) on line 13 :- $_REQUEST['Page'] instead of $_REQUEST[Page]
    3) on line 14 :- $_REQUEST['mode']==”Listing” instead of _REQUEST[mode]==”Listing”

    in HTML FIRST page:

    4) on line 154&155 :-
    var pmeters = ‘mode=’+Mode+’&Page=’+Page;
    var url = ‘SANajax.php?’+pmeters;
    you wrote :
    var url = ‘SANajax.php’;
    var pmeters = ‘mode=’+Mode+’&Page=’+Page;
    now, its ok..100% work for me..thanks again

  63. gordonek says:

    Hi,
    Is it possible to make it seo friendly? The content is not shown in page source. Is it possible that it will be shown at least in the first page? Thanks.

  64. Kashif says:

    Hellow friends. may b this script working. but i need a ajax pagination with a drop down by which any one can select to display number of record per page eg (5/10/25 rec per page)…. and complete works of without refreshing page

  65. vishal says:

    okkk

  66. soniya says:

    Parse error: syntax error, unexpected T_VARIABLE in B:\wamp\www\experiment\pagination\SANajax.php on line 68
    i`m getting this error please help me out

  67. soniya says:

    Hi
    If page count is 100 than, page numbers will be shown as 1 2 3 4 5 6….100. It will look so terrible. how to do like “Next 1 2 3 4 5 Prev” and rest of them (up to 100 pages) be hidden. when click on 4 or 5 it will show the hidden pagination what is the solution for it? Can you help me?

  68. soniya says:

    Please help me it`s quite urgent for me

  69. Elena says:

    Hi, this is working great! Thanks for sharing!

  70. Manu says:

    Hi, this is working great! But one think
    We want to paging like that 1 2 3 4 5 ——- 24 25
    If total No. of Pages is 25.
    Please help me it`s quite urgent for me.

  71. Sandeep says:

    Hi friends,
    This script helps me a lot.

  72. Antonio says:

    Hi, i’m trying to get the script working under wordpress and query only on one category (id 8). Any idea?
    this is not working
    $query = “SELECT ID, guid, post_title, post_date, post_content, post_category, FROM wp_posts WHERE category_id = ‘8′ post_type=’post’ AND post_status=’publish’”;

  73. sachin says:

    demo not working. just make it……

  74. SAN says:

    Sachin@ it works

  75. Antonio says:

    Hi this is the correct query for a selected category under wordpress:
    $query = “SELECT distinct ID, post_title, post_date, guid, post_content, post_name FROM wp_posts, wp_terms, wp_term_relationships WHERE wp_posts.id = wp_term_relationships.object_id AND wp_term_relationships.term_taxonomy_id = wp_terms.term_id AND post_type=’post’ AND post_status=’publish’ AND wp_terms.slug = ‘your-category’”;
    I also have other questions.
    How do i take a custom field named foto?
    Why the first result doesn’t take the styles i assign to elements result?

  76. Megan N. Cloutier says:

    I do not even know how I stopped up right here, however I believed this put up was once great. I don’t recognise who you might be but certainly you are going to a famous blogger if you aren’t already. Cheers!

  77. aming budirana says:

    thanks very nice Tutor, its run and work

Leave a Reply