A simple Dynamic Website with PHP and AJAX

A simple Dynamic Website with PHP and AJAX

Introduction

This time we are going to create a simple dynamic website with ajax and the right amount of PHP & CSS. It is going to have a few pages loaded by AJAX from the PHP back-end, and a complete support of the browser history .

First We Create a Database called ajaxwebsite:


CREATE DATABASE ajaxwebsite ;

Second We Create sample table in our database:


CREATE TABLE pages(
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY,
page_name VARCHAR(100) NOT NULL,
page_content TEXT NOT NULL
) ENGINE = InnoDB;

And finally we insert some sample data to our pages table:


INSERT INTO `pages` (`id`, `page_name`, `page_content`) VALUES

(1, 'Page 1', 'It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout. The point of using Lorem Ipsum is that it has a more-or-less normal distribution of letters, as opposed to using ''Content here, content here'', making it look like readable English. Many desktop publishing packages and web page editors now use Lorem Ipsum as their default model text, and a search for ''lorem ipsum'' will uncover many web sites still in their infancy. Various versions have evolved over the years, sometimes by accident, sometimes on purpose (injected humour and the like).'),

(2, 'Page 2', 'Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old. Richard McClintock, a Latin professor at Hampden-Sydney College in Virginia, looked up one of the more obscure Latin words, consectetur, from a Lorem Ipsum passage, and going through the cites of the word in classical literature, discovered the undoubtable source. Lorem Ipsum comes from sections 1.10.32 and 1.10.33 of "de Finibus Bonorum et Malorum" (The Extremes of Good and Evil) by Cicero, written in 45 BC. This book is a treatise on the theory of ethics, very popular during the Renaissance. The first line of Lorem Ipsum, "Lorem ipsum dolor sit amet..", comes from a line in section 1.10.32.'),

(3, 'Page 3', 'There are many variations of passages of Lorem Ipsum available, but the majority have suffered alteration in some form, by injected humour, or randomised words which don''t look even slightly believable. If you are going to use a passage of Lorem Ipsum, you need to be sure there isn''t anything embarrassing hidden in the middle of text. All the Lorem Ipsum generators on the Internet tend to repeat predefined chunks as necessary, making this the first true generator on the Internet. It uses a dictionary of over 200 Latin words, combined with a handful of model sentence structures, to generate Lorem Ipsum which looks reasonable. The generated Lorem Ipsum is therefore always free from repetition, injected humour, or non-characteristic words etc.'),

(4, 'Page 4', '"But I must explain to you how all this mistaken idea of denouncing pleasure and praising pain was born and I will give you a complete account of the system, and expound the actual teachings of the great explorer of the truth, the master-builder of human happiness. No one rejects, dislikes, or avoids pleasure itself, because it is pleasure, but because those who do not know how to pursue pleasure rationally encounter consequences that are extremely painful. Nor again is there anyone who loves or pursues or desires to obtain pain of itself, because it is pain, but because occasionally circumstances occur in which toil and pain can procure him some great pleasure. To take a trivial example, which of us ever undertakes laborious physical exercise, except to obtain some advantage from it? But who has any right to find fault with a man who chooses to enjoy a pleasure that has no annoying consequences, or one who avoids a pain that produces no resultant pleasure?"');

The Database Connectivity file

Now we create Our Database Connectivity File

connection.php

</pre>
<?php
$conn=mysqli_connect("localhost","root","","ajaxwebsite");
?>
<pre>

The XHTML and PHP

Now, we create our XHTML and PHP backbone of the site and show pages name as menu and home page content from database.
demo.php

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>A simple Dynamic Website with PHP and AJAX</title>
<link rel="stylesheet" type="text/css" href="demo.css" />
<script src="ajax.js" type="text/javascript" language="javascript"></script>
</head>

</pre>
<body>

<div id="rounded">
<div id="main" class="container">
 <h1>A simple Dynamic Website with PHP and AJAX</h1>
 <h2>Because simpler is better</h2>

<ul id="navigation">
 <?php
 include('connection.php');
 $query=mysqli_query($conn,"SELECT * FROM pages");
 while($rows=mysqli_fetch_array($query)){
 ?>
 <li><a onclick="callPage('<?php echo $rows['id']; ?>')" href="#"><?php echo $rows['page_name']; ?></a></li>
 <?php
 }
 ?>

</ul>

<div class="clear"></div>

<div id="pageContent">
<?php
$query2=mysqli_query($conn,"SELECT page_content FROM pages WHERE id=1");
$rows2=mysqli_fetch_array($query2);

echo $rows2['page_content'];
?>

</div>
 <div class="clear"></div>
</div>

<div align="center" class="demo">
this is a <a href="http://www.w3programmers.com/" target="_blank">simple dynamic website with php and ajax</a> </div>
</div>
</body>
<pre>
</html>

Its main purpose is to serve as a front-end to the php back-end, with ajax handling all the communication in between.

Here onclick event we call function callPage() and also send different page id as a function argument to ajax.js file

Note the addresses of the navigation links =”#<?php echo $rows[‘page_name’]; ?> – show you as #your_page_name from your database. This part, called a hash, is included in the current URL without a page refresh, creating an entry in the browser’s history. By monitoring this hash with javascript, we can change the loaded page by AJAX and provide a seamless browsing experience.

The CSS

Lets take a look at our style sheet.

demo.css


@charset "utf-8";

/* CSS Document */

/* Page styles */

body,h1,h2,h3,p,td,quote,small,form,input,ul,li,ol,label{

margin:0px;

padding:0px;

font-family:Arial, Helvetica, sans-serif;

}

body{

margin-top:20px;

color:#51555C;

font-size:13px;

background-color:#123456;

text-align:center;

}

.clear{

clear:both;

}

a, a:visited {

color:#007bc4;

text-decoration:none;

outline:none;

}

a:hover{

text-decoration:underline;

}

#rounded{

width:800px;

margin:20px auto;

text-align:left;

}

.container{

background-color:#FFFFFF;

padding:10px 20px 20px 20px;

-moz-border-radius: 5px;

-khtml-border-radius: 5px;

-webkit-border-radius: 5px;

border-radius: 5px;

}

h1{

font-size:28px;

font-weight:bold;

font-family:"Trebuchet MS",Arial, Helvetica, sans-serif;

}

h2{

font-weight:normal;

font-size:20px;

color:#999999;

}

ul{

margin:30px 0px;

}
li{

list-style:none;

display:block;

float:left;

width:80px;

}

li a,li a:visited{

padding:5px 10px;

text-align:center;

background-color:#000033;

color:white;

-moz-border-radius:5px;

-khtml-border-radius: 5px;

-webkit-border-radius: 5px;

border-radius:5px;

display:block;

margin-right:10px;

}

li a:hover{

background-color:#666666;

text-decoration:none;

}

#pageContent{

margin-top:20px;

border:1px dashed #cccccc;

padding:10px;

-moz-border-radius: 5px;

-khtml-border-radius: 5px;

-webkit-border-radius: 5px;

border-radius: 5px;

}

#loading{

visibility:hidden;

}

.demo{

color:white;

}

An important reminder would be to note that rounding corners with CSS is only supported in the latest versions of Firefox, Safari and Chrome.

Simple Ajax Websit With PHP

The Ajax source

To complement the front-end, here is the script that drives the site.

ajax.js


// JavaScript Document

function callPage(id)

{

var xmlhttp;

if (window.XMLHttpRequest)

{// code for IE7+, Firefox, Chrome, Opera, Safari

xmlhttp=new XMLHttpRequest();

}

else

{// code for IE6, IE5

xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");

}

xmlhttp.onreadystatechange=function()

{

if (xmlhttp.readyState==4 && xmlhttp.status==200)

{

document.getElementById("pageContent").innerHTML=xmlhttp.responseText;

}

}

xmlhttp.open("GET","content.php?id="+id,true);

xmlhttp.send();

}

content.php File


<?php</pre>
<?php

include('connection.php');
$id=$_REQUEST['id'];
$query=mysqli_query($conn,"SELECT page_content FROM pages WHERE id=$id");
$rows=mysqli_fetch_assoc($query);
echo $rows['page_content'];
?>
<pre>

It basically receive the variable $_ REQUEST [‘id’] , and if it is, it called page_content data from our table pages.

You can improve upon this by fetching data from a database, by using sessions, or displaying a folder of images – anything you might have on your mind.
Conclusion

Today we created a simple, customization-ready, AJAX enabled web site. Feel free to use the code and the techniques that were demonstrated in any of your projects.

Hi, My name is Masud Alam, love to work with Open Source Technologies, living in Dhaka, Bangladesh. I graduated in 2009 with a bachelor’s degree in Engineering from State University Of Bangladesh, I’m also a Certified Engineer on ZEND PHP 5.3, I served my first five years a number of leadership positions at Winux Soft Ltd, SSL Wireless Ltd, CIDA and MAX Group where I worked on ERP software and web development., but now i’m a co-founder and Chief Executive Officer and Managing Director of TechBeeo Software Consultancy Services Ltd. I’m also a Course Instructor of ZCPE PHP 7 Certification and professional web development course at w3programmers Training Institute – a leading Training Institute in the country.
11 comments on “A simple Dynamic Website with PHP and AJAX
  1. Nice, stumbled onto your site, being a beginner in the arts of PHP and the like have been overly impressed with the examples and explanations thereof. Great stuff sir, hope to see many more.

    Regarding this one though; would it work with Javascript disabled? If not what sort of changes would we need to do to get this to work without the AJAX functionality?

  2. Now all you need to do is re-vamp the script to use PDO not mysql_query.
    As of PHP 6.5 any mysql query will be have to be done with PDO.

  3. Seems to be nice and easy, but i suggest to convert $id to int – or else there is potential security hole… (sql-injections)

    $id=(int)$_REQUEST[‘id’];

Leave a Reply

Your email address will not be published. Required fields are marked *