| AJAX XMLHttpRequest: |
|
| Introduction |
|
| Ajax uses XMLHttpRequest objects for browser-server communication. The mechanism for sending data to and retrieving data from the server with Ajax is the XMLHttpRequest object. |
|
| XMLHttpRequest has an important role in the AJAX web development technique. It has been used by many websites to implement attractive and dynamic web applications. |
|
| XMLHttpRequest can be used inside a web browser scripting language(Like JavaScript), to send an HTTP or an HTTPS request directly to a web server and load the server response data directly back into the scripting language. |
|
| The XMLHttpRequest object is at the heart of Ajax and has become the de facto standard for enabling XML data to be passed asynchronously over HTTP. Asynchronous interaction implies that the browser can continue to process events in the page after the request is sent. Data is passed in the background, and can be automatically loaded into the page without requiring a page refresh. |
|
| Three parameters are specified when you create an XMLHttpRequest object: a URL, the HTTP method (GET or POST), and whether or not the interaction is asynchronous. |
|
| An XMLHttpRequest calls on a particular URL, possibly passing in some arguments on the URL or the message body. But what sort of thing resides at the URL? |
|
| It contains some informative values or a string, that is to be send at client side and be processed by the server. |
|
| var url = "test.php?uname=user&id=" + escape(field.value); |
|
var reqobj; // global variable to hold request object
function loadXMLDocument(url, params)
{
if(window.XMLHttpRequest) {
try {
reqobj = new XMLHttpRequest(); // creation of XMLHttpRequest object
} catch(e) {
reqobj = false;
}
} else if(window.ActiveXObject) {
try {
reqobj = new ActiveXObject("Msxml2.XMLHTTP");
} catch(e) {
try {
reqobj = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
reqobj = false;
}
}
}
if(reqobj) {
reqobj.onreadystatechange = processReqChange;
return true;
}
return false;
}
|
|
| Creating an XMLHTTPRequest object: |
|
| For Better use of ajax we must have to initialize the XMLHttpRequest object, use of that is very simple in most browsers, but it becomes little bit complex, when we try to use the IE 5 and 6. |
|
| Explanation |
|
| If you review the above code, you can see that, The funchtion LoadXMLDocument accepts two parameter, first one be the url (server location) of the server side script which is being called and the second one is the variable to pass to the script. |
|
| The script looks like as: |
|
<script type="text/javascript" src="js/xmlhttp.js"></script>
<script type="text/javascript">
var params = 'x=' + encodeURIComponent(input) + '&goal=' +
encodeURIComponent(goal);
loadXMLDoc('/scripts/testscript.php', params);
</script>
|
|
| This is the script reside in the path scripts/testscripts.php, it have two parameters, namely are “x”, “goal” |
|
| Note: We here describe the example by taking the GET method, and for post method please refer the above article where we describe get and post method. |
|
|
|
|
|
| AJAX Examples |
|
| Creating Your First AJAX Page: |
|
| We have now know much more about ajax, and for the shake of understanding let us take a simple example which can exactly clears the concept what is the process and how ajax works. |
|
| Let us take an example: |
|
| Let us explain the working of the example described below. It includes an html page, which has the text box for search, also containing JavaScript and xml. And a php page having a php script for communicate to the server. |
|
| Functionality work as when you enter the text in the specified text field in the HTML page, it gives the response of your text, typed by you. Without doing a page refresh. And suddenly you got your response without doing wait. |
|
| HTML page: |
| validate_name.php |
|
| Explanation |
|
| We have taken a very basic example, the html page shows a text field in which, when you type the character less than 3 it shows a massage that string “Name typed is too short”, and if you type the name more than three characters and it would be not the name which we hard coded here (our main purpose is just to explaining the example, that why we here not taken the database and queries at all) as: kamal, dhirendra, aman, saurabh, it shows a massage “name already exists”, and if you type the name other than these four names it shows ka massage “This name is available for you” |
|
<script type="text/javascript">
var http = false;
if(navigator.appName == "Microsoft Internet Explorer") {
http = new ActiveXObject("Microsoft.XMLHTTP");
} else {
http = new XMLHttpRequest();
}
function validate(user) {
http.abort();
http.open("GET", "validate.php?name=" + user, true);
http.onreadystatechange=function() {
if(http.readyState == 4) {
document.getElementById('valid_name').innerHTML = http.responseText;
}
}
http.send(null);
}
</script>
<h1>Check your name availability:</h1>
<form>
<input type="text" onkeyup="validate(this.value)" />
<div id="valid_name"></div>
</form>
|
|
| Explanation: |
|
| new XMLHttpRequest() --The above constructor is for any other browser. |
|
| new ActiveXObject(Microsoft.XMLHTTP) --The above constructor is used for Internet Explorer. |
|
| http.readyState == 4 ---The 4 state means that the response is being sent by the server and it is ready. |
|
| http.onreadystatechange--- An anonymous function is assigned to the event indicator. Actually it specifies the callback function to be triggered when the ready state changes. |
|
| http.open( "POST", "data.xml", true); |
|
| POST or GET |
|
| URL of the script to execute. The Last Argument is for checking for whether the request is asynchronous or synchronous, true is used for asynchronous and false for synchronous. |
|
| Description of the page validate_name.php Line by Line: |
|
| Line 1: <script type="text/javascript">Line 1 defines the <script> tag is used for embedded JavaScript code in an HTML document, the type defines the type you used and the language used for that. |
|
| Line2: var http = false; Create a new variable http and assign it a false value. You'll use false as a condition that means the XMLHttpRequest object hasn't been created yet. |
|
| Line 3 to 7 having a loop trying to create the XMLHttpRequest Object for the different browsers. We already define the xmlhttprequest object and also define the ActiveXObject. |
|
| Line 8: function validate(user) This is a JavaScript function named validate and the argument passed is user. |
|
| Line 9: http.abort(); Aborts the xmlhttp request. When the response is no longer required, we want to abort the request in order to make another more relevant one. |
|
| Line 10- 15: |
|
| In the code(function on line 10) is used for the sending a request to the server. To send a request to the server we use this method. It takes three parameters which we describe above, please refer to the above section where we describes it in details. |
|
| If we talk about sending data to the server, onreadystatechange is the prior requirement to first write a function that will be able to receive the information, the basic functionality of the onreadystatechange function is to catch the data that is return by the server. |
|
| readyState == 4: |
|
| The readyState property holds the status of the server's response. Each time thereadyState changes, the onreadystatechange function will be executed |
|
| State Description are given below: |
|
0 Request uninitialized
1 Request Loading
2 Request Loaded
3 Request in process
4 Request is complete |
|
| Line 16: send(null); To send the request off to the server we use this method. |
|
| Two methods of XMLHttpRequest are used: |
|
open: command GET or POST, URL of the document, true for asynchronous.
send: with POST only, the data to send to the server. |
|
| The request below read a document on the server. |
|
obxml.open('GET', url', true);
objxml.send(null); |
|
| Line 18: Closes the script tag. |
|
| Line 19: <h1>Check your name availability:</h1> Display this content at User end |
|
| Line 20: Opens a form tag. |
|
| Line 21: <input type="text" onkeyup="validate(this.value)" /> Create a text field and call a function to an event(onkeyup). |
|
| Line 22: <div id="valid_name"></div> Taking a div with taking an id . |
|
| Line 23:. </form> Close the form. |
|
| Page name: validate.php |
|
<?php
function validate($name) {
if($name == '') {
return '';
}
if(strlen($name) < 3) {
return "<span id=\"warn\">Name typed is too short</span>\n";
}
switch($name) {
case 'kamal':
case 'dhirendra':
case 'aman':
case 'saurabh':
return "<span id=\"warn\">Name already Exist</span>\n";
}
return "<span id=\"notice\">This name is available for you!</span>\n";
}
echo validate(trim($_REQUEST['name']));
?>
|
|
| Explanation |
|
| This is the php script page which is communicate to server. This page simply calls the validate function and checks that whether it is empty or not. |
|
| The second if statement checks whether the string have less than three character, if it so than a message will be displayed “ Name typed too short” |
|
| We here take few names as hard coded, you may be fire a query for the names exist in the database. |
|
| And if the name typed in the text box will matched with the name described here or the query you fire, a new message will come “Name already exist.” |
|
| Rather than if you type a names other than the matching name a message comes “This name is available for you.” |
|
|
|
|
|
| Javascript function |
|
| Javascript function |
|
| The JavaScript functions are to used to make a request for an information to the server. The server process the request and returns the specific information. |
|
| JavaScript the same page integrates the information in the same page. The theme is that instead of refreshing the whole page with the response, it only refreshes the part which is being queried. |
|
| Ajax script is made up of two different functions, the first one is fetch Data () and the other one is filter Data (). The XMLHttpRequest are created within the function, also the code is used to send the data located within this function. |
|
|
|
|
|
| The Back-End & Front End Page |
|
| The Back-End Page |
|
| However, your ‘back-end’ page needs to be written in a dynamic scripting language which is able to query a database. accept query string data - anything which requires access to a server or needs to fetch client-side data; examples of these kind of language is php. |
|
| The back-end page are the page having the logic and ideas for running the concept of the front end page. If you want to run your Ajax internally,you have to prepare a back-end page in a dynamic language. |
|
| This page can be created in any dynamic language, as well as it uses another language to communicate with the database for query. |
|
| The Front-End Page: |
|
| User interaction, GUI page, Display page and all the names are meant for the front page the HTML page, this page is built for display a page with the input fields, through which a user can filled the data and gets the required output. |
|
| To begin with, your ‘front-end’ page can be in any scripting language - it can even be just a basic HTML file. |
|
| In technical terms the page with .php(we consider for the php language) for displaying the input field to the user and return the result, is called the front end page, the page are basically having the html codes and the scripting language like JavaScript etc. |
|
|
|
|
|
| AJAX: Real-life examples & Usage cases |
|
| Ajax with PHP(Using Database) |
|
| Let us take an example of ajax with the use of database, how can we interact with database while using ajax in php, may be this question arises in your mind, so here we explain each and every thing through this example. |
|
| Example: |
|
| The example shown below is having two php page . First page is for display the field, having HTML tags and the java script, the text field which is in a div is for receiving the result of the user input, text field is for user input a user puts his customer id and while clicks on the check button the request send to the server and the process will occur using the second page. |
|
| Actually the other page is meant for the php script and mysql query.Which is used for communicating the server. And responsible for processing the query (id) in the database. |
|
| Actually the theme of the example is when a user filled his customer id in the html page, the page will checks whether the customer exists or not if it exist then it will give the user name, address, city and phone no and if the id enter by the user/customer is not exist in the database then a message will come “Customer with the ID= XXXX doesn't exist.” |
|
| Page name: findUser.php |
|
1.<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
2.<html>
3.<head>
4. <title>Customer Report</title>
5. <script type="text/javascript">
6. var url = "customerDetl.php?id="; // The server-side script
7. function handleHttpResponse() {
8. if (http.readyState == 4) {
9. if(http.status==200) {
10. var results=http.responseText;
11. document.getElementById('divCustInfo').innerHTML = results;
12. }
13. }
14 . }
15. function requestCustInfo() {
16. var sId = document.getElementById("txtId").value;
17. http.open("GET", url + escape(sId), true);
18. http.onreadystatechange = handleHttpResponse;
19. http.send(null);
20. }
21. function getHTTPObject() {
22. var xmlhttp;
23. if(window.XMLHttpRequest){
24. xmlhttp = new XMLHttpRequest();
25. }
26. else if (window.ActiveXObject){
27. xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
28. if (!xmlhttp){
29. xmlhttp=new ActiveXObject("Msxml2.XMLHTTP");
30. }
31. }
32. return xmlhttp;
33.}
34. var http = getHTTPObject(); // creating HTTP Object
35. </script>
36. </head>
37. <body>
38. <p>Please enter your customer ID to retrieve information:</p>
39. <p>Customer ID: <input type="text" id="txtId" value="" /></p>
40. <p><input type="button" value="check" onClick="requestCustInfo()" /></p>
41. <div id="divCustInfo"></div>
42. </body>
43. </html
|
|
| Explanation: |
|
Line 1: First line is as you know the defifnes foe html.
Line 2:<html>Html tag starts.
Line 3:<head> starts.
Line 4:<title > tag starts with a title.
Line 5: it start a script name javascript.
Line 6: var url = "customerDetl.php?id="; Crreating a variable to store the url(php script page url), with the id appended as a query string. |
|
| In theline 7 a function is created with the name handle HttpResponse. This function is used for checking the condition for readyState == 4 (This is the state when the completion of the process would occur.) and the status (This returns the HTTP status code from the server such as 200 for OK or 404 for not found.) |
|
| The result of the response .Text (response. Text) this is used for returning the response to the server, the response text contain the text of the http response.) is stores in a variable called results. And return to the div id which is present in the HTML page named as <div id="divCustInfo">. |
|
| Line 15-20: |
|
| function requestCustomerInfo() is created here, initialize the open function using the argument as div id url and the condition. |
|
| Onreadystatechange Event handler for an event that fires at every state change. |
|
| Before we send the HTTP request, we specify the onreadystatechange property to be the name of our new function handleHttpResponse(). This means that every time the HTTP ready state has changed, our function handleHttpResponse() is called. |
|
| Line 21-32: We have already describe these lines, taking as an example above so there are no need to describe this, it simply for creation of the XMLHttpRequest object. |
|
| Line 38-41: |
|
<p>Please enter your customer ID to retrieve information:</p>
<p>Customer ID: <input type="text" id="txtId" value="" /></p>
<p><input type="button" value="check" onClick="requestCustInfo()" /></p>
<div id="divCustInfo"></div>
|
|
| This is the html tags to display the field for input “Please enter….” Is simply a text message and the field where the user puts its input is <input type="text" id="txtId" value="" /> this is the field where user puts his input. |
|
| <div id="divCustInfo"></div> This is used for storing the server response. |
|
| Page name: customerDetl.php |
|
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title>Customer Report</title>
<?php
//customer ID
1. $ID = $_GET["id"];
2. //variable to hold customer info
3. $Info = "";
4. //database information
5. $sDBServer = "localhost"; ## Database Host Name
6. $sDBName = "user"; ## Database Name
7. $sDBUsername = "root"; ## Database User
8. $sDBPassword = ""; ## Database User Password
## Creating database connection
9. $Link = mysql_connect($sDBServer,$sDBUsername,$sDBPassword);
10. @mysql_select_db($sDBName, $Link) or $Info = "Unable to open database";
## Mysql Query for fetching the data from the database from the tabe customers
11. $sQuery = "Select * from Customers where id=".$ID;
12. if($Info == '') {
13. if($Result = mysql_query($sQuery) and mysql_num_rows($Result) > 0) {
14. $Values = mysql_fetch_array($Result,MYSQL_ASSOC);
15. $Info = "Name: ".$Values['name'].
"<br />"."Add: ".$Values['address']."<br />".
16. "city: ".$Values['city'].
"<br />"."Phone: ".$Values['phone_no']."<br />";
17. } else {
18. $Info = "Customer with the ID= $ID doesn't exist.";
19. }
20. }
20. mysql_close($Link);
?>
</head>
<body>
21. <div id="divInfoToReturn"> <?php echo $Info ?> </div>
</body>
</html>
|
|
| Explanation |
|
| This page is business login page of the example, pages having the php script and the mysql query which directly communicates with the server the line by line explanation of the code is: |
|
Line1: Storing the value of id with the help of $_GET in a variable $ID.
Line 2-3: Creating a variable to store user information. |
|
4. //database information
5. $sDBServer = "local host"; ## Database Host Name
6. $sDBName = "user"; ## Database Name
7. $sDBUsername = "root"; ## Database User
8. $sDBPassword = ""; ## Database User Password |
|
| This is used to for database connection: |
|
$sDBServer is used for server name (In this example we take it a local host server).
$sDBName Is used for Database.
$sDBUsername is for the database user name;
$DBPassword is for the database password. |
|
| Line 9-10: |
|
9. $Link = mysql_connect($sDBServer,$sDBUsername,$sDBPassword);
10. @mysql_select_db($sDBName, $Link) or $Info = "Unable to open database"; |
|
| It Is used for connection to the database. |
|
| Line 11-21: |
|
11. $sQuery = "Select * from Customers where id=".$ID;
12. if($Info == '') {
13. if($Result = mysql_query($sQuery) and mysql_num_rows($Result) > 0) {
14. $Values = mysql_fetch_array($Result,MYSQL_ASSOC);
15. $Info = "Name: ".$Values['name']."<br />"."Add: ".$Values['address']."<br />".
16. "city: ".$Values['city']."<br />"."Phone: ".$Values['phone_no']."<br />";
17. } else {
18. $Info = "Customer with the ID= $ID doesn't exist.";
19. }
20. }
21.mysql_close($Link); |
|
| 11. $query is used a for keeping the simple select query which is acted on the table customer and fetches its all data. |
|
| 12-13. Process the above query with mysql function and stores it in the var. $Result and then fetch the result set with the mysql function mysql_fetch_array and the result would comes with this is final result which is being stores in the $Value variable. |
|
| 14-15: Display the result data comeming from the $Value. |
|
| 16-20 if this would not be occurred then the message is displayed “Customer with the ID =XXXX doesn’t exist”. |
|
| 21: close the connections of the database. |
|
|
|
|
|
|
| AJAX: Real-life examples & Usage cases |
|
| Search example |
|
| In the current example we have a drop down box instead of the text field as in second example, drop down box having some names of user and while you select a name the information regarding to the user will display in the same page, the information of the user coming from the database and the event is fires on selecting the name of the dropdown box. |
|
| WE here taking the information coming from the data on selection, but you can change the script as your convenience. |
|
| Page name: selectUser (HTML page) |
|
<html>
<head>
<script type="text/javascript" src="user.js"></script>
</head>
<body>
<form>
Select a User: <select name="users" onChange="showUser(this.value)">
<option value="">Select a name</option>
<option value="10">kamal</option>
<option value="9">Ajay</option>
</select>
</form>
<br />
<div id="txtHint"><b>Person info will be listed here.</b></div>
</body>
</html>
|
|
| Page name: getUser.php(Php scipt page) |
|
$q=$_GET["q"];
$con = mysql_connect('localhost', 'root', '');
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("test", $con);
$sql="SELECT * FROM user WHERE id = '".$q."'";
$result = mysql_query($sql);
echo "<table border='1'>
<tr>
<th>Name</th>
<th>Contents</th>
</tr>";
while($row = mysql_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['name'] . "</td>";
echo "<td>" . $row['editor'] . "</td>";
echo "</tr>";
}
echo "</table>";
mysql_close($con);
?>
|
|
| page name: user.js (javascript page) |
|
var xmlhttp;
function showUser(str)
{
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Browser does not support HTTP Request");
return;
}
var url=" getUser.php"; <!-- changes may be done here,
Note Here Page get_user.php is the page
which contains the php code(sql fo data retriving) -->
url=url+"?q="+str;
url=url+"&sid="+Math.random();
xmlhttp.onreadystatechange=stateChanged;
xmlhttp.open("GET",url,true);
xmlhttp.send(null);
}
function stateChanged()
{
if (xmlhttp.readyState==4)
{
document.getElementById("txtHint")
.innerHTML=xmlhttp.responseText;
<!-- cahanges may be done here,
Note Here txtHint stands for the id of the div,
taken in html page-->
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
// code for IE7+, Firefox, Chrome, Opera, Safari
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
// code for IE6, IE5
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
|
|
| Explanation: |
|
| The first page is a html page which display the drop – down box, having the name the employee in the drop – down box. The second page contains the php script and the third page consists the java script this java script page is included in the first page and the second page is called in the .js file. |
|
| This example uses the database you can use the example as your convenience it can be change to an hard coded data in place of the data coming from the database. |
|
|
|
|
|
| AJAX: Real-life examples & Usage cases |
|
| Ajax- form vatidation |
|
| This is a new type of example of email validation, where we want to validate a form through ajax, The display page contains three fields first one is the name field, second one is the email address field and the last is for the city, this example is for validate the email address, when a user fills his name and then his email id and as he go to fill the city the email validation checks whether the email filled by the user is valid or invalid, a message appers identifying the valid/ invalid email. |
|
| Page name: validation.php |
|
<html>
<head>
<script type="text/javascript">
function validate(email)
{
var httpxml;
try
{
// Firefox, Opera 8.0+, Safari
httpxml=new XMLHttpRequest();
}
catch (e)
{
// Internet Explorer
try
{
httpxml=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
httpxml=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
function stateck()
{
if(httpxml.readyState==4)
{
document.getElementById("displayMsg")
.innerHTML=httpxml.responseText;
}
}
var url="getdata.php";
url=url+"?email="+email;
url=url+"&sid="+Math.random();
httpxml.onreadystatechange=stateck;
httpxml.open("GET",url,true);
httpxml.send(null);
}
</script>
</head>
<form name=f1 action=''>
<table border="1" cellpadding="2" c
ellspacing="2" vspace="80" align="center" width="50%">
<tr>
<td align="right"> Name:</td>
<td align="left"><input type=text name=n1></td>
</tr>
<tr>
<td align="right">email address:</td>
<td align="left" height="40"><input type=text name=email
onBlur="validate(this.value);"><div id="displayMsg"></div></td>
</tr>
<tr>
<td align="right">City:</td>
<td align="left"><input type="text" name="city"></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" v
alue="Submit" ><input type="hidden" value="test" name="todo"></td>
</tr>
</table>
</form>
</html>
|
|
| Page Name: getdata.php |
|
<?php
$email=$_GET['email'];
echo $email;
if (!eregi("^[_a-z0-9-]+(.[_a-z0-9-]+)
*@[a-z0-9-]+(.[a-z0-9-]+)*(.[a-z]{2,3})$", $email))
{
echo "<font color=red> Invalid email</font>";
}else{
echo "<font color=green> Valid Email</font>";
}
?>
|
|
| Explanation: |
|
| This is simple a form validation script through ajax, in which the html page having the html script and the javascript and the php script is written in getdata.php page the concept of the script is so simple, the user enter its detais and its email id and it is validating through php page which have the validation script. |
|
| The code written in the validate.php have the same meaning as in the above code as explained in the above example. |
|
|
|
|
|
|
|
|
|
|
|
|
|
0 comments: