29
XML HTTP Request • The XMLHttpRequest object is used to exchange data with a server behind the scenes. => it is possible to update parts of a web page, without reloading the whole page. • All modern browsers like IE7+, Firefox, Chrome, Safari, and Opera have a built-in XMLHttpRequest object.

Xml http request

Embed Size (px)

DESCRIPTION

 

Citation preview

Page 1: Xml http request

XML HTTP Request

• The XMLHttpRequest object is used to exchange data with a server behind the scenes. =>

it is possible to update parts of a web page, without reloading the whole page.

• All modern browsers like IE7+, Firefox, Chrome, Safari, and Opera

have a built-in XMLHttpRequest object.

Page 2: Xml http request

Create an XMLHttpRequest Object

• Syntax for creating an XMLHttpRequest object:

variable=new XMLHttpRequest();

• Old versions of Internet Explorer (IE5 and IE6) uses an ActiveX Object:

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

Page 3: Xml http request

• Example• 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"); }

Page 4: Xml http request

Ajax - onreadystatechange Property

• Special property of XMLHttpRequest• stores the function that will process the

response from the server. • Example: Javascript Code:// Create a function that will receive data sent from the server

ajaxRequest.onreadystatechange = function(){ // We still need to write some code here }

Page 5: Xml http request

Ajax - readyState Property

• another property of XMLHttpRequest• The status of the server response is stored in

this.• The response can be

processing, downloading Completed.

Page 6: Xml http request

• the readyState changes, whenever onreadystatechange function executes.

• Example : Javascript Code:• // Create a function that will receive data sent from the

server ajaxRequest.onreadystatechange = function(){ if(ajaxRequest.readyState == 4){ // Get the data from the server's response } }

Page 7: Xml http request

Ajax - responseText Property

• To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object.

responseText => get the response data as a stringresponseXML => get the response data as XML data

• If the response from the server is not XML, use the responseText property.

Page 8: Xml http request

Example<!DOCTYPE html>

<html>

<head>

<script type="text/javascript">

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>

Page 9: Xml http request

<body>

<div id="myDiv"><h2>Let AJAX change this text</h2></div>

<button type="button" onclick="loadXMLDoc()">Change Content</button>

</body></html>

Page 10: Xml http request

responseXML Property

• If the response from the server is XML, and we have to parse it as an XML object, use the responseXML Property:

Page 11: Xml http request

<!DOCTYPE html><html><head><script type="text/javascript">function loadXMLDoc(){var xmlhttp;var txt,x,i;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) { xmlDoc=xmlhttp.responseXML; txt=""; x=xmlDoc.getElementsByTagName("ARTIST"); for (i=0;i<x.length;i++) { txt=txt + x[i].childNodes[0].nodeValue + "<br />"; } document.getElementById("myDiv").innerHTML=txt; } }xmlhttp.open("GET","cd_catalog.xml",true);xmlhttp.send();}</script></head>

Page 12: Xml http request

<body><h2>My CD Collection:</h2><div id="myDiv"></div><button type="button" onclick="loadXMLDoc()">Get my CD collection</button> </body></html>

Output :My CD Collection:

My CD Collection:Bob DylanBonnie TylerDolly PartonGary MooreEros RamazzottiBee GeesDr.HookRod StewartAndrea BocelliPercy SledgeSavage Rose

Get my CD collection

Page 13: Xml http request

AJAX - Send a Request To a Server• The XMLHttpRequest object is used to exchange data

with a server.• Send a request with open() and send() methods. Example:

xmlhttp.open("GET","ajax_info.txt",true);xmlhttp.send();

Method Description

open(method,url,async) Specifies the type of request, the URL, and if the request should be handled asynchronously or not.method: the type of request: GET or POSTurl: the location of the file on the serverasync: true (asynchronous) or false (synchronous)

send(string) Sends the request off to the server.

string: Only used for POST requests

Page 14: Xml http request

• After Sending the request,monitor the state of the request using onreadystatechange property.

Example: xmlhttp.onreadystatechange=function()

{if(xmlhttp.readyState==4 && xmlhttp.status == 200){var resp = xmlhttp.responseText;}}

Page 15: Xml http request

Or like this,xmlhttp.onreadystatechange = handleResponse;function handleResponse(){

if(xmlhttp.readyState == 4 && xmlhttp.status == 200){//returned text from the PHP scriptvar response = xmlhttp.responseText;}}

Page 16: Xml http request

• The readyState property holds the status of the server’s response

• the possible values for the readyState property:State Description0 The request is not initialized1 The request has been set up2 The request has been sent3 The request is in process4 The request is complete

• And status is the status of the HTTP Request, like 500 Internal Server Error, 400 Bad Request, 401 Unauthorized, 403 Forbidden, 404 Not Found etc. 200 means no error.

Page 17: Xml http request

AJAX - Server Response

• To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object.

• When a request to a server is sent.• The onreadystatechange event is triggered

every time the readyState changes.• The readyState property holds the status of

the XMLHttpRequest.

Page 18: Xml http request

AJAX AdvancedAJAX ASP/PHP Example

• Example: How a web page can communicate with a web server while a user type characters in an input field:

Page 19: Xml http request

function showHint(str){var xmlhttp;if (str.length==0) { document.getElementById("txtHint").innerHTML=""; return; }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("txtHint").innerHTML=xmlhttp.responseText; } }xmlhttp.open("GET","gethint.php?q="+str,true);xmlhttp.send();}

Page 20: Xml http request

<?php// Fill up array with names$a[]="Anna";$a[]="Brittany";$a[]="Cinderella";$a[]="Diana";$a[]="Eva";$a[]="Fiona";$a[]="Gunda";$a[]="Hege";$a[]="Inga";$a[]="Johanna";$a[]="Kitty";$a[]="Linda";$a[]="Nina";$a[]="Ophelia";$a[]="Petunia";$a[]="Amanda";$a[]="Raquel";$a[]="Cindy";$a[]="Doris";$a[]="Eve";$a[]="Evita";$a[]="Sunniva";$a[]="Tove";$a[]="Unni";$a[]="Violet";$a[]="Liza";$a[]="Elizabeth";$a[]="Ellen";$a[]="Wenche";$a[]="Vicky";

//get the q parameter from URL$q=$_GET["q"];

//lookup all hints from array if length of q>0if (strlen($q) > 0)  {  $hint="";  for($i=0; $i<count($a); $i++)    {    if (strtolower($q)==strtolower(substr($a[$i],0,strlen($q))))      {      if ($hint=="")        {        $hint=$a[$i];        }      else        {        $hint=$hint." , ".$a[$i];        }      }    }  }

// Set output to "no suggestion" if no hint were found// or to the correct valuesif ($hint == "")  {  $response="no suggestion";  }else  {  $response=$hint;  }

//output the responseecho $response;?>

Page 21: Xml http request

AJAX Database Example

• The AJAX example Which demonstrate how a web page can fetch information from a MySQL database using AJAX technology.

• This example consists of four elements:a MySQL databasea simple HTML forma JavaScripta PHP page

Page 22: Xml http request

The Database

Id FirstName Lastname Age Hometown Job

1 Rani Ajai 32 Kovai Professor

2 Ramya Bala 34 Karur Manager

3 Latha Mani 30 Trichy Teacher

4 Kani Mani 30 Kovai Bussiness

Page 23: Xml http request

The HTML FormThe example contains a simple HTML form and a link to a JavaScript:

<html> <head> <script src="selectuser.js"></script> </head><body> <form> Select a User: <select name="users" onchange="showUser(this.value)">

<option value="1“>Rani Ajai</option> <option value="2“>Ramya Bala</option> <option value="3“>Latha Mani</option> <option value="4“>Kani Mani</option> </select> </form>

<p> <div id="txtHint"><b>User info will be listed here.</b></div> </p> </body> </html>

Page 24: Xml http request

The JavaScriptThis is the JavaScript code stored in the file "selectuser.js":

var xmlHttp;function showUser(str) { xmlHttp=GetXmlHttpObject();if (xmlHttp==null) { alert ("Browser does not support HTTP request"); return; }

var url="getuser.php"; 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 || xmlHttp.readyState=="complete") { document.getElementById("txtHint").innerHTML=xmlHttp.responseText; } }function GetXmlHttpObject() { var xmlHttp=null; Try { // Firefox, Opera 8.0+, Safari xmlHttp=new XMLHttpRequest(); }catch (e) { //Internet Explorer try {xmlHttp=new ActiveXObject("Msxml2.XMLHTTP"); }catch (e) { xmlHttp=new ActiveXObject("Microsoft.XMLHTTP"); }} return xmlHttp; }

Page 25: Xml http request

• Process of The showUser() Function If an item in the drop down box is selected the function executes the

following:

Calls on the GetXmlHttpObject function to create an XMLHTTP object

Defines the url (filename) to send to the server

Adds a parameter (q) to the url with the content of the dropdown box

Adds a random number to prevent the server from using a cached file

Call stateChanged when a change is triggered

Opens the XMLHTTP object with the given url.

Sends an HTTP request to the server

Page 26: Xml http request

• The PHP Page• The server page called by the JavaScript, is a

simple PHP file called "getuser.php".• The page is written in PHP and uses a MySQL

databse.• The code runs a SQL query against a database

and returns the result as an HTML table:

Page 27: Xml http request

<?php $q=$_GET["q"];$con = mysql_connect('localhost', ‘my_db', ‘xxx'); if (!$con){ die('Could not connect: ' . mysql_error()); } mysql_select_db("ajax_demo", $con);$sql="SELECT * FROM user WHERE id = '".$q."'";$result = mysql_query($sql);echo "<table border='1'> <tr> <th>Firstname</th> <th>Lastname</th> <th>Age</th> <th>Hometown</th> <th>Job</th> </tr>"; while($row = mysql_fetch_array($result)) { echo "<tr>"; echo "<td>" . $row['FirstName'] . "</td>"; echo "<td>" . $row['LastName'] . "</td>"; echo "<td>" . $row['Age'] . "</td>"; echo "<td>" . $row['Hometown'] . "</td>"; echo "<td>" . $row['Job'] . "</td>"; echo "</tr>"; }echo "</table>"; mysql_close($con); ?>

Page 28: Xml http request

• When the query is sent from the JavaScript to the PHP page the following happens:

PHP opens a connection to a MySQL server

The "user" with the specified name is found

A table is created and the data is inserted and sent to the "txtHint" placeholder

Output:

Id Firstname Lastname Age Hometown

Job

1 Rani Ajai 32 Kovai Professor

Page 29: Xml http request