1) Create MySQL Database test and populate with sample data
1.1) log into PHPMyAdmin.
1.2) Create a new database, test.
1.3) Using SQL Editor, paste the following codes and run.
--
-- Table structure for table `people`
--
CREATE TABLE IF NOT EXISTS `people` (
`id` int(11) NOT NULL,
`firstname` varchar(55) COLLATE utf8_swedish_ci NOT NULL,
`surname` varchar(55) COLLATE utf8_swedish_ci NOT NULL,
`title` varchar(55) COLLATE utf8_swedish_ci NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci AUTO_INCREMENT=3 ;
--
-- Dumping data for table `people`
--
INSERT INTO `people` (`id`, `firstname`, `surname`, `title`) VALUES
(1, 'Teter', 'Ventouris', 'Mr'),
(2, 'David ', 'Dabel', 'Mr');
|
1.4) You should be getting the following output.
2) Prepare the back end code
<?php
$link = mysql_pconnect("localhost", {username},{password}) or die("Could not connect");
mysql_select_db("test") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM people");
while($obj = mysql_fetch_object($rs)) {
$arr[] = $obj;
}
echo '{"members":'.json_encode($arr).'}';
|
3) Prepare front end code
<!DOCTYPE html>
<html>
<head>
<title>jQuery PHP Json Response</title>
<style type="text/css">
div
{
text-align:center;
padding:10px;
}
#msg {
width: 500px;
margin: 0px auto;
}
.members {
width: 500px ;
background-color: beige;
}
</style>
</head>
<body>
<div id="msg"> </div>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1/jquery.min.js">
</script>
<script type="text/javascript">
$(document).ready(function(){
var url="http://localhost/people/people.php";
$.getJSON(url,function(json){
// loop through the members here
$.each(json.members,function(i,dat){
$("#msg").append(
'<div class="members">'+
'<h1>'+dat.id+'</h1>'+
'<p>Firstname : <em>'+dat.firstname+'</em>'+
'<p>SurName : <em>'+dat.surname+'</em></p>'+
'<p>Title : <strong>'+dat.title+'</strong></p>'+
'<hr>'+
'</div>'
);
});
});
});
</script>
</body>
</html>
|
No comments:
Post a Comment