You are on page 1of 29

AJAX in a few

minutes
Brought to you by s.M.r.a.E

1
AJAX according to w3schools.com

2
What is AJAX?
• A - Asynchronous
• J -JavaScript
• A -And
• X -XML
3
Synchronous?
• Synchronous
–Give me a pen!
–I stand and wait for you
–You give me pen
–Now I continue my work
4
Asynchronous?
• Synchronous
–Give me a pen!
–I continue other works
–You give me pen
–I take pen and do whatever I wanted
to do with it happily 
–If you don’t give me pen, I don’t really
care...My other works will continue
5
AJAX step 1
Create an envelop Create XMLHttpRequest
Object

envelop=new XMLHttpRequest();

6
AJAX step 2
Open envelop Use open method on
XMLHttpRequest Object

envelop.open();

7
AJAX step 3
Put content + Address + Use open method on
stamp(by postal service) XMLHttpRequest Object
How to send
Destination

envelop.open(“GET”, “destination.php?
mark=85& name=roushdat”, true);

Data/Content Asynchronous

8
AJAX step 4
Address of sender (to
receive replies)

From:
Rita Ramjoey
Royal Road,Curepipe,
Mauritius
Put a value (a function to handle
replies) for the property
onreadystatechange
envelop. onreadystatechange=displayresult;

A function9
AJAX step 5
Poster lettre la!

Use the send method to send the


request

envelop. send(null);
10
AJAX step 6
When reply arrives, you will
be notified
Inside function displayresult()

function displayresult(){
if (envelop.readyState==4 &&
envelop.status==200)
{
alert(“answer is:”
+envelop.responseText);
}
}
11
AJAX All JS Codes
function ajax(){ Using GET
envelop=new XMLHttpRequest();
envelop.open(“GET”, “destination.php? mark=85&
name=roushdat”, true);
envelop. onreadystatechange=displayresult;
envelop. send(null);
}
function displayresult(){
if (envelop.readyState==4 && envelop.status==200){
alert(“answer is:” +envelop.responseText);
}
} 12
AJAX All JS Codes
function ajax(){ Using POST
envelop=new XMLHttpRequest();
envelop.open(“POST”, “destination.php”, true);
envelop. onreadystatechange=displayresult;
envelop.setRequestHeader("Content-
type","application/x-www-form-urlencoded");
envelop. send(mark=85&name=roushdat);
}
function displayresult(){
if (envelop.readyState==4 && envelop.status==200){
alert(“answer is:” +envelop.responseText);
} 13
}
Some more explications
(w3schools.com)

14
AJAX: Registration
Case Study (RCS)

15
RCS: Step 1 <html>
<head>
1.1 Create the form below in <title>Registration</title>
an HTML page </head>
<body>
<form name="regform" method=“POST" action="processregister.php">
<table border=1>
<tr>
<td>User Name</td>
<td><input type="text" name="txtuname" /></td>
</tr>
<tr>
<td>Name</td>
<td><input type="text" name="txtname"/></td>
</tr>
1.2 Save the page as <tr>
register.html <td>Password</td><td><input type="password" name="pws"/></td>
</tr>
<tr>
<td></td>
<td><input type="submit" value="register"/></td>
</tr>
</table>
</form>
</body> 16
</html>
RCS: Step 2a
Create the PHP file named processregister.php
which will perform the following tasks:
1. Establish a connection to the database server and
select the appropriate database

2. Extract the data sent by the form found in


register.html

3. Check whether the username entered already exists in


the database; if it exists, display an error message,
else, insert the new username and other data into the
database, displaying a success message.

17
RCS: Step 2b
1. Establish a connection to the database
server and select the appropriate database
<?php
$con=mysql_connect("127.0.0.1","root","");
if(!$con){
echo "problem to connect"; You can either
} (i) write the code in processregister.php
else{ at the top
mysql_select_db("stud",$con);
or
}
?>
(ii) you can put this code in a blank PHP
file which we will name as
Database’s name is stud connex.php and in
processregister.php,at the top,
write: require(‘connex.php’);
18
RCS: Step 2c
2. Extract the data sent by the form found in
register.html. The code below goes in
processregister.php
<?php
If the form used the GET method,
$uname=$_POST['txtuname'];
$name=$_POST['txtname']; you would be writing
$password=$_POST['pws']; $uname=$_GET[‘txtuname’];
Instead!
?>

19
RCS: Step 2d
3. Check whether the username entered already exists in the database; if
it exists, display an error message, else, insert the new username and
other data into the database, displaying a success message. The code
below goes in processregister.php
<?php
$sql="SELECT * FROM student WHERE uname='$uname';";
$result=mysql_query($sql,$con);
if(mysql_num_rows($result)>0){ //if we get more than zero row…means the username exists!
echo "Username already exist, pick another one!";
}
else{ //the username does not exist in database yet, so we can store it!
$sql="INSERT INTO student (uname,name,password) VALUES
('$uname','$name','$password');";
mysql_query($sql,$con);
echo "Successfully added new record";
}
?>
20
RCS: The Problem
Currently, based on the code we have written, every time a user tries to register, it is only
after the form is submitted that the username will be checked and if it already exist, the
user will then have to fill in all the form details again. Then he/she submits again...praying
that the newly chosen username does not exist in database yet...else keep doing this stuff
on and on till a username is accepted…

RCS: The Solution


What we propose is this:
As soon as the user fills in the username text box in register.html and moves to the next
text box, an event (onblur) is triggered. The even will cause a function [ ajax() ] to be called
which in turn will send the username to the server quietly in the background. All this will
happen without the user being interrupted...therefore, he/she can leisurely continue filling
the form.
21
RCS: Step 3
Modify the form in register.html to add the event trigger

<tr>
<td>User Name</td>
<td><input type="text" name="txtuname" onblur="ajax()" /></td>
</tr>

22
RCS: Step 4a
Write the JavaScript function ajax(). You can either write it in between <head></head>
in register.html or in an external file like myjava.js, in which case you have to link the
file to register.html using <script type=“text/javascript” src=“myjava.js”></script>.
Note: We are using the GET method to send the data-> This is not related to the
GET/POST used in the form. GET is faster but is not appropriate for confidential data

function ajax(){
try {
requestbox=new XMLHttpRequest();
} catch (e) { alert("Your browser does not support AJAX!");}
var uname=document.regform.txtuname.value; //retrieve value
var url="checkuname.php?txtuname="+uname; //construct url
requestbox.open("GET",url,true); requestbox.onreadystatechange=displayResult;
//set callback function
requestbox.send(null);
}
23
RCS: Step 4b
Write the JavaScript function ajax(). You can either write it in between <head></head>
in register.html or in an external file like myjava.js, in which case you have to link the
file to register.html using <script type=“text/javascript” src=“myjava.js”></script>.
Note: We are using the POST method to send the data-> This is not related to the
GET/POST used in the form. POST is appropriate for sending confidential & large
amount of data

function ajax(){
try {
requestbox=new XMLHttpRequest();
} catch (e) { alert("Your browser does not support AJAX!");}
var uname=document.regform.txtuname.value; //retrieve value
var url="checkuname.php”;
requestbox.open(“POST",url,true); requestbox.onreadystatechange=displayResult; //set
callback function
requestbox.setRequestHeader("Content-type","application/x-www-form-urlencoded");
requestbox.send(“txtuname="+uname);
24
}
RCS: Step 5
We now have to implement the JavaScript function displayResult() which will receive the
reply sent by the server and will then display it using DOM on our registration.html
page. To enable the display, we have to add a pair of <div> tags with an id.
In html codes, add:
<tr>
<td>User Name</td>
<td><input type="text" name="txtuname" onblur="ajax()" />
<div id=‘message'></div>
</td>
</tr>

In JavaScript codes, add:


function displayResult(){
if((requestbox.readyState==4)&&(requestbox.status==200)){
document.getElementById(‘message').innerHTML=requestbox.responseText;
}
} 25
RCS: Step 6
We now have to create the checkuname.php file which basically borrows some codes
from processregister.php.

checkuname.php:

<?php
require('connex.php');
$uname=$_POST['txtuname'];
$sql="SELECT * FROM student WHERE uname='$uname';";
$result=mysql_query($sql,$con);
if(mysql_num_rows($result)>0){
echo "Username already exist, pick another one!";
}
else{
echo "username is valid- not registered yet!";
}
?> 26
RCS: Creating
Database
Structure of the table student in database stud

27
RCS: You are done!
If you have done everything properly, it should work...

A word of advice:
DO NOT COPY-PASTE, TYPE THE CODES!!!

28
Lab Exercise

• The above screen grab has been taken from the page products.html
• It consists of a form with a group of radio buttons.
• When a radio button is selected, AJAX is used to retrieve all products having gender
‘Male’ or ‘Female’ from the table tblproduct.
• The products are then listed within a div as shown above.
• Each product listed points to a URL (for example: Boxers points to boxers.html)
• You may make assumptions with respect to the database implementation details.

29

You might also like