Ajax Next / Previous Picture (jQuery / PHP)

If you are looking for a simple script to navigate next / previous image without refreshing page, this example will do exactly that using jQuery Ajax and PHP.

SQL Tabe

Following SQL code creates a table named “pictures” with 3 columns (id, PictureTitle, PictureName) and inserts pictures data into the table.

 
1
2
3
4
5
6
7
8
9
10
11
12
CREATE TABLE IF NOT EXISTS `pictures` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `PictureTitle` varchar(60) NOT NULL,
  `PictureName` varchar(60) NOT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=6 ;
INSERT INTO `pictures` (`id`, `PictureTitle`, `PictureName`) VALUES
(1, 'Benjamin Button', 'benjamin_button.jpg'),
(2, 'Liv Taylor', 'liv-taylor.jpg'),
(3, 'Macro Shot 1', 'pic1.jpg'),
(4, 'Macro Shot 2', 'pic2.jpg'),
(5, 'Sweets', 'mysweets.jpg');

Index.php

A picture will be loaded primarily, and then user can navigate to next / previous images without refreshing the page. File completely relies on ”getpicture.php”.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<html>
<head>
<!-- load jquery -->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("body").on("click",".getPicButton", function(e){
    var myPictureId = $(this).attr('id');
    var getImgId =  myPictureId.split("-");
    getPicture(getImgId[1]);
    return false;
});
});

function getPicture(myPicId)
{
$('#picture').html('<div style="margin-top:50px;width:500px;" align="center" ><img src="loader.gif" /></div>');

var myData = 'picID='+myPicId;
jQuery.ajax({
    url: "getpicture.php",
    type: "GET",
    dataType:'html',
    data:myData,
    success:function(response)
    {
        $('#picture').html(response);
    }
    });
}
</script>
<title>Ajax Pictures</title>
</head>

<body>
<div id="picture">
<?php
$getPicture = file_get_contents("http://localhost/pictures/getpicture.php");
echo $getPicture;

?>
</div>
</body>
</html>

getpicture.php

File gets image id from index.php, and gets image information from database, creates next/previous button returns image data back to index.php. Replace xxxxx with your MySQL username, password and database name.

 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
########## MySql details (Replace with yours) #############
$username = "xxxx"; //mysql username
$password = "xxxx"; //mysql password
$hostname = "localhost"; //hostname
$databasename = 'xxxx'; //databasename

if(isset($_GET["picID"]) && is_numeric($_GET["picID"]))
{
    $curPicId = $_GET["picID"];
}else{
    $curPicId =1;
}

//Connect to Database
$connecDB = mysql_connect($hostname, $username, $password)or die();
mysql_select_db($databasename,$connecDB);

//Get the Picture
$Result = mysql_query("SELECT PictureTitle,PictureName FROM pictures WHERE id=$curPicId");
$row = mysql_fetch_row($Result);
if(!empty($row))
{
    //empty variables, just incase
    $picTitle=''; $picName=''; $PrvLink='';$NextLink='';

    $picTitle = $row[0];
    $picName = $row[1];

    //Get previous Picture
    $PrvResult = mysql_query("SELECT id,PictureTitle FROM pictures WHERE id<$curPicId ORDER BY id DESC");
    $PrvPic = mysql_fetch_row($PrvResult);
    if($PrvPic)
    {
        $PrvLink = '<a href="#" id="getPic-'.$PrvPic[0].'" title="'.$PrvPic[1].'" class="getPicButton"><img src="prev.png" border="0" /></a>';
    }

    //Get next Picture
    $NxtResult = mysql_query("SELECT id,PictureTitle FROM pictures WHERE id>$curPicId ORDER BY id ASC");
    $NxtPic = mysql_fetch_row($NxtResult);
    if($NxtPic)
    {
        $NextLink = '<a href="#" id="getPic-'.$NxtPic[0].'" title="'.$NxtPic[1].'" class="getPicButton"><img src="next.png" border="0" /></a>';
    }

    //$picdata = array('pic'=>$picName,'pictitle'=>$picTitle,'prvid'=>$PrvPicID,'prvtitle'=>$PrvPicTitle,'nxtid'=>$NxtPicID,'nxttitle'=>$NxtPicTitle);

    echo '<table width="500" border="0" cellpadding="5" cellspacing="0">
          <tr>
            <td><table width="100%" border="0" cellpadding="5" cellspacing="0">
              <tr>
                <td width="10%">'
.$PrvLink.'</td>
                <td width="80%" align="center"><h3>'
.$picTitle.'</h3></td>
                <td width="10%">'
.$NextLink.'</td>
              </tr>
            </table></td>
          </tr>
          <tr>
            <td align="center"><img src="pictures/'
.$picName.'" /></td>
          </tr>
        </table>'
;

    //json data
    //echo json_encode($picdata);

}
//Close db connection
mysql_close($connecDB);

Download Demo

Related Articles:

Article by on June 17, 2012 Tagged under Tagged under , , . If you like this article, please consider sharing it.

6 Thoughts

  1. Nice tut! But I got a problem. The index.php page displays the following (onload):

     
    1
    2
    ';} //Get next Picture
    // code omitted

Leave a Comment

Get your comment picture from Gravatar.com.
Your email address will not be published. Required fields are marked *