Wednesday, April 2, 2014

AJAX 101

-----
AJAX 101

INTRODUCTION

What is AJAX?
AJAX = Asynchronous JavaScript and XML. AJAX is a technique for creating fast and dynamic web pages. AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) must reload the entire page if the content should change. Examples of applications using AJAX: Google Maps, Gmail, Youtube, and Facebook tabs.
AJAX was made popular in 2005 by Google, with Google Suggest. Google Suggest is using AJAX to create a very dynamic web interface: When you start typing in Google's search box, a JavaScript sends the letters off to a server and the server returns a list of suggestions.

STEPS

0) Pre-requisite:
1) In Notepad++ Project, create Project201.
2) Create an html file, ajax101.html
2.1) Add the following codes to ajax101.html:
<!DOCTYPE html>
<html>
<body>
<div id="myDiv"><h2>Let AJAX change this text</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>

2.1.1) Take note that the Line No. says <!DOCTYPE html> which means this is HTML 5 document.
2.2) Browse the file.
- At the moment, clicking the Change Content button will not give any effect. Refer Line No. 6 in Step 2.1, function loadXMLDoc() doesn’t exist.
3) Adding function loadXMLDoc()
3.1) Insert the <head> element to ajax101.html by adding the following codes in between the tag <html> and <body>
<head>
<script>
function loadXMLDoc()
{
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("myDiv").innerHTML=xmlhttp.responseText;
    }
  }
xmlhttp.open("GET","ajax_info.txt",true);
xmlhttp.send();
}
</script>
</head>
- Take note that since this is HTML 5 document (refer Step 2.1.1) by default <script> refers to JavaScript.
3.2) Run AJAX.
3.2.1) Activate Chrome Developer Tools.
3.2.3) Click Change Content.
3.2.4) Observe that:
a) Chrome is requesting the file ajax_info.txt from the directory /php201.
b) GET request is used.
c) Status is 404 Not Found
4) Add AJAX resource file.
4.1) Create a file ajax_info.txt . Add the following codes:
<p>AJAX is not a new programming language.</p>
<p>AJAX is a technique for creating fast and dynamic web pages.</p>
4.3) This time, the server returns Status 200 (OK) and you see the output as above.
5) Change resource file to PHP script.
5.1) create ajax_info.php. Add the following codes:
<?php
echo "<p>AJAX is not a new programming language.</p>";
echo "<p>AJAX is a technique for creating fast and dynamic web pages.</p>";
?>
5.2) Edit ajax101.html. Change ajax_info.txt to ajax_info.php:

SUMMARY

With AJAX, the JavaScript does not have to wait for the server response, but can instead:
- execute other scripts while waiting for server response
- deal with the response when the response ready
Important keywords used:
- XMLHttpRequest()
- xmlhttp.onreadystatechange
- xmlhttp.readyState
- xmlhttp.responseText
- xmlhttp.open
- xmlhttp.send

FURTHER EXERCISE

Kickstart PHP101 project with UwAmp


-----
Kickstart PHP101 project with UwAmp        

INTRODUCTION

UwAmp is a great tool for beginners to quickly kick-start their 101 (introductory) projects.

STEPS

0) PRE-REQUISITE:
1) Start UwAmp.
- Check that both Apache and MySQL servers are running.
- Check that PHP, Apache and MySQL Configuration is right.
https://docs.google.com/document/d/16NEFk2q7JkY9az2bpK9E-k_NWJKJ9gEISBrRAP6uKgg/pubimage?id=16NEFk2q7JkY9az2bpK9E-k_NWJKJ9gEISBrRAP6uKgg&image_id=1MOKJfCYfCYeRaNbeixovc_Zszg-_jtpI1Le0QA
Apache “Offline Mode” means that the server is available for local machine only and will not be accessible from other network clients.
2) www Site Page.
- Check that your www Site is working. (Click the www Site button. Your Default Web Browser should open the UwAmp Start Web Page. It is recommended that you use Chrome Web Browser as your Default Web Browser. Bear in mind that Chrome hides the text http:// so you just see word localhost only in the URL box.)
- Additionally, you may want to click PHPMyAdmin and PHP Info links just to see that they are alive.
- Notice that the section Projects shows “No project found” message.
3) www Folder.
- Close the Web Browser and switch back to UwAmp Control Panel.
- Click the www Folder button. (File Explorer will run and automatically show the content of www Folder)
- At the moment, there is only one file ie the script file that outputs the web page in Step 2.
4) Create new folder “php101”.
- While in the www folder, right-click and choose New/Folder.
- Rename the new folder as “php101”.
5) Viewing projects directory in UwAmp Start Web Page.
- Switch to UwAmp Control Panel and click www Site button.
- Notice that the folder name “php101” now appears under the Projects Section in UwAmp Start Web Page.
- If you click the link, you will be forwarded to the php101 directory.
- Since you haven’t put any file in this directory (and the Apache Server allows “Option Indexes” directive), you will get an auto-generated page with empty file listing.
6) Test index.php
- Using your Text Editor, create an index.php file in php101 folder containing the following codes: <?php echo “hello 101”; ?>
- Browse http://localhost/php101 again.
- From this observation we know that:
---- Apache is running.
----- Apache automatically recognizes php file extension.
----- PHP interpreter correctly interprets the script.

Monday, March 31, 2014

SMARTY BASIC CONCEPT

-----
SMARTY BASIC CONCEPT

INTRODUCTION

STEPS

WITHOUT SMARTY

1) Create Directory Structure.

2) Edit Codes.

2.1) index.php
<HTML>
<HEAD>
<TITLE>User Registration using Smarty application</TITLE>
<style type="text/css">
body{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
color:#333333;
}
</style>
</HEAD>
<BODY >
<form method="post" action="register.php">      
<div>
<div>Name : <input type="text" name="fullname" id="fullname"></div>
<div>User Name : <input type="text" name="user_name" id="user_name"></div>
<div>Password : <input type="text" name="password" id="password"></div>
<div><input type="submit" name="submit" value="submit" ></div>
</div>
</form>
</BODY>
</HTML>
2.2) register.php
<?php
include("config.php");
if(isset($_POST))
{
$query = "INSERT INTO USERS(fullname,user_name,password)   VALUES (' ".mysql_escape_string($_POST['fullname'])."', '".mysql_escape_string($_POST['user_name'])."','".md5($_POST['password'])."')";
$result =  mysql_query($query);
if($result)
{
echo "<script>window.location='index.php?msg=successfully inserted ';</script>";
}
}
?>
2.3) config.php
<?php
$dbHost = "localhost";
$dbUser = "root";
$dbPassword="root";
$dbName="smarter1";
$con = mysql_connect($dbHost,$dbUser,$dbPassword);
$sel = mysql_select_db($dbName,$con) or mysql_error();
?>

3) Prepare Database

3.1) Create a new database “smarter1”.
CREATE DATABASE `smarter1`;


3.2) Create table “users”.
CREATE TABLE USERS (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
fullname VARCHAR( 255 ) NOT NULL ,
user_name VARCHAR( 255 ) NOT NULL ,
password VARCHAR( 255 ) NOT NULL ,
created_on TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
NOT NULL DEFAULT CURRENT_TIMESTAMP
);

4) Test Website.

WITH SMARTY

Download Smart Package from http://www.smarty.net/download and extract into webroot as smarter2.

1) Directory Structure

Add the following files:
But the content will slightly differ from the previous steps.

2) Edit Codes.

2.1) index.php (different from previous codes)
<?php
include("libs/Smarty.class.php");
include("config.php");
$smarty = new Smarty;
$smarty->debugging = true;
$smarty->caching = true;
$smarty->cache_lifetime = 120;
$smarty->assign("title", "User Registration using Smarty application");
$smarty->display('index.tpl');
?>
2.2) register.php (same as previous codes)
<?php
include("config.php");
if(isset($_POST))
{
$query = "INSERT INTO USERS(fullname,user_name,password)   VALUES (' ".mysql_escape_string($_POST['fullname'])."', '".mysql_escape_string($_POST['user_name'])."','".md5($_POST['password'])."')";
$result =  mysql_query($query);
if($result)
{
echo "<script>window.location='index.php?msg=successfully inserted ';</script>";
}
}
?>
2.3) config.php (same as previous codes)
<?php
$dbHost = "localhost";
$dbUser = "root";
$dbPassword="root";
$dbName="smarter1";
$con = mysql_connect($dbHost,$dbUser,$dbPassword);
$sel = mysql_select_db($dbName,$con) or mysql_error();
?>
Add new template files in smarter2/templates/…
2.4) header.tpl
<HTML>
<HEAD>
<TITLE>{$title}</TITLE>
{literal}
<style type="text/css">
body{
font-family:Arial, Helvetica, sans-serif;
font-size:12px;
color:#333333;
}
</style>
{/literal}
</HEAD>
<BODY >
2.5) index.tpl
{include file="header.tpl" title={$title}}  
<form method="post" action="register.php">      
<div>
<div>Name : <input type="text" name="fullname" id="fullname"></div>
<div>User Name : <input type="text" name="user_name" id="user_name"></div>
<div>Password : <input type="text" name="password" id="password"></div>
<div><input type="submit" name="submit" value="submit" ></div>
</div>
</form>
{include file="footer.tpl"}
2.6) footer.tpl
</BODY>
</HTML>

3) Prepare Database

3.1) Create a new database “smarter2”.
CREATE DATABASE `smarter2`;


3.2) Create table “users”.
CREATE TABLE USERS (
id INT NOT NULL AUTO_INCREMENT PRIMARY KEY ,
fullname VARCHAR( 255 ) NOT NULL ,
user_name VARCHAR( 255 ) NOT NULL ,
password VARCHAR( 255 ) NOT NULL ,
created_on TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
NOT NULL DEFAULT CURRENT_TIMESTAMP
);

4) Test Website.

PHP FRONT CONTROLLER BASIC CONCEPT

-----
FRONT CONTROLLER BASIC CONCEPT

STEPS

1) Create Directory Structure.

[webroot]\frontcontroller1\
----------index.php
----------pages\
--------------------home.php
--------------------account.php

2) Codes

2.1) index.php

<?php
  session_start();
  $redirect = !empty($_GET["page"])? $_GET["page"] : "home";
  switch($redirect){
   case "home":
      include "pages/home.php";
      break;
   case "account":
      include "pages/account.php";
      break;    
  }
?>
2.2) home.php

<?php
echo "this is home";
?>
2.3) account.php

<?php
echo "this is account";
?>

Labels