article

Sunday, November 20, 2011

Load Records Using Jquery Json and Mysql

Load Records Using Jquery Json and Mysql

Table

CREATE TABLE `tbljson` (
`id` int(11) NOT NULL auto_increment,
`title` varchar(255) NOT NULL default '',
`description` varchar(255) NOT NULL default '',
`image` varchar(255) NOT NULL default '',
PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=7 DEFAULT CHARSET=latin1;


index.php
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
<script type="text/javascript">
$("document").ready(function () {
$.getJSON('json.php?callback=?', function (data) {
$("#content").html('');
$.each(data, function (i, item) {
$("#content").append('<div class="product"><img src="images/' + item.image + '" width="135" height="138"/><div class="title">' + item.title + '</div><div class="description">' + item.description + '</div><div class="clear"></div></div>');
});
});
$("#content").fadeIn(2000);
});
</script>
<style>
.main{
width:900px;
margin:0 auto;
}
.product{
width:300px;
float:left;
margin:10px;
border:1px #dedede solid;
padding:5px;
background-image:url(images/corner.jpg);
background-position:bottom right;
background-repeat:no-repeat;
}
.product .title{
margin-bottom:6px;}
.product img{
float:left;
margin-right:10px;
border:1px solid #dedede;}
.product .description{font-size:10px; font-family:Geneva, Arial, Helvetica, sans-serif}
</style>
<div class="main">
<div id="content"><img src="images/ajax-loader.gif" alt="Loading..." /></div>
</div>
<div class="clear"></div>



jason.php
<?php
include('connect.php');
$sql = "SELECT title, image, description FROM tbljson LIMIT 4";
$result = mysql_query($sql);
while($row = mysql_fetch_array($result))
{
$rows[] = array(
"title" => $row['title'],
"image" => $row['image'],
"description" => $row['description']);
}

$json = json_encode($rows);
$callback = $_GET['callback'];
echo $callback.'('. $json . ')';
?>


connect.php
<?php
$dbhost = "localhost";
$dbuser = "root";
$dbpass = "ednalan";
$dbname = "test";
$conn = mysql_connect($dbhost, $dbuser, $dbpass) or die ("Error connecting to database");
mysql_select_db($dbname);
?>

Related Post