Unit 8 PHP and Other Web Technologies: What Is AJAX?

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 10

UNIT 8 PHP AND OTHER WEB TECHNOLOGIES

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.

How AJAX Works


The core idea behind AJAX is to make the communication with the server asynchronous, so that data is transferred and processed in the background. As a result the user can continue working on the other parts of the page without interruption. In an AJAX-enabled application only the relevant page elements are updated, only when this is necessary. In contrast, the traditional synchronous (postback-based) communication would require a full page reload every time data has to be transferred to/from the server. This leads to the following negative effects: * The user interaction with the application is interrupted every time a server call is needed, since a postback has to be made. * The user has to wait and look at blank screen during each postback. * The full page is being rendered and transferred to the client after each postback, which is time consuming and traffic intensive. * Any information entered by the user will be submitted to the server, perhaps prematurely. The AJAX-enabled applications, on the other hand, rely on a new asynchronous method of communication between the client and the server. It is implemented as a JavaScript engine that is loaded on the client during the initial page load. From there on, this engine serves as a mediator that sends only relevant data to the server as XML and subsequently processes server response to update the relevant page elements.

The XMLHttpRequest Object


All modern browsers support the XMLHttpRequest object (IE5 and IE6 use an ActiveXObject). The XMLHttpRequest object is used to exchange data with a server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object


All modern browsers (IE7+, Firefox, Chrome, Safari, and Opera) have a built-in 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");
To handle all modern browsers, including IE5 and IE6, check if the browser supports the XMLHttpRequest object. If it does, create an XMLHttpRequest object, if not, create an ActiveXObject:

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

XMLHttpRequest Methods

abort() Cancels the current request. getAllResponseHeaders() Returns the complete set of HTTP headers as a string. getResponseHeader( headerName ) Returns the value of the specified HTTP header. open( method, URL ) open( method, URL, async ) open( method, URL, async, userName ) open( method, URL, async, userName, password ) Specifies the method, URL, and other optional attributes of a request. The method parameter can have a value of "GET", "POST", or "HEAD". Other HTTP methods, such as "PUT" and "DELETE" (primarily used in REST applications), may be possible The "async" parameter specifies whether the request should be handled asynchronously or not . "true" means that script processing carries on after the send() method, without waiting for a response, and "false" means that the script waits for a response before continuing script processing. send( content ) Sends the request. setRequestHeader( label, value ) Adds a label/value pair to the HTTP header to be sent.

XMLHttpRequest Properties

onreadystatechange An event handler for an event that fires at every state change.

readyState The readyState property defines the current state of the XMLHttpRequest object. Here are the possible values for the readyState propery: State Description 0 The request is not initialized 1 The request has been set up 2 The request has been sent 3 The request is in process 4 The request is completed readyState=0 after you have created the XMLHttpRequest object, but before you have called the open() method. readyState=1 after you have called the open() method, but before you have called send(). readyState=2 after you have called send(). readyState=3 after the browser has established a communication with the server, but before the server has completed the response. readyState=4 after the request has been completed, and the response data have been completely received from the server.

responseText Returns the response as a string. responseXML Returns the response as XML. This property returns an XML document object, which can be examined and parsed using W3C DOM node tree methods and properties. status Returns the status as a number (e.g. 404 for "Not Found" and 200 for "OK"). statusText Returns the status as a string (e.g. "Not Found" or "OK").

Send a Request To a Server


To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object: xmlhttp.open("GET","ajax_info.txt",true); xmlhttp.send();

Method

Description Specifies the type of request, the URL, and if the request should be handled asynchronously or not. method: the type of request: GET or POST url: the location of the file on the server async: true (asynchronous) or false (synchronous) Sends the request off to the server. string: Only used for POST requests

open(method,url,async)

send(string)

GET or POST?
GET is simpler and faster than POST, and can be used in most cases. However, always use POST requests when:

A cached file is not an option (update a file or database on the server) Sending a large amount of data to the server (POST has no size limitations) Sending user input (which can contain unknown characters), POST is more robust and secure than GET

GET Requests A simple GET request: Example xmlhttp.open("GET","demo_get.asp",true); xmlhttp.send(); In the example above, you may get a cached result. To avoid this, add a unique ID to the URL: Example xmlhttp.open("GET","demo_get.asp?t=" + Math.random(),true); xmlhttp.send();

If you want to send information with the GET method, add the information to the URL: Example xmlhttp.open("GET","demo_get2.asp?fname=Henry&lname=Ford",true); xmlhttp.send();

POST Requests
A simple POST request: Example xmlhttp.open("POST","demo_post.asp",true); xmlhttp.send(); To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method: Example xmlhttp.open("POST","ajax_test.asp",true); xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded"); xmlhttp.send("fname=Henry&lname=Ford");

Server Response
To get the response from a server, use the responseText or responseXML property of the XMLHttpRequest object. Property Description responseText get the response data as a string responseXML get the response data as XML data

The responseText Property


If the response from the server is not XML, use the responseText property. The responseText property returns the response as a string, and you can use it accordingly:

Example document.getElementById("myDiv").innerHTML=xmlhttp.responseText;

The responseXML Property


If the response from the server is XML, and you want to parse it as an XML object, use the responseXML property: Example Request the file cd_catalog.xml and parse the response: 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;

Example Explained - The MySQL Database The database table we use in the example above looks like this: id 1 2 3 4 FirstName Peter Lois Joseph Glenn LastName Griffin Griffin Swanson Quagmire Age 41 40 39 41 Hometown Quahog Newport Quahog Quahog Job Brewery Piano Teacher Police Officer Pilot

Example Explained - The HTML Page


When a user selects a user in the dropdown list above, a function called "showUser()" is executed. The function is triggered by the "onchange" event: <html> <head> <script type="text/javascript"> function showUser(str) {

if (str=="") { 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","getuser.php?q="+str,true); xmlhttp.send(); } </script> </head> <body> <form> <select name="users" onchange="showUser(this.value)"> <option value="">Select a person:</option> <option value="1">Peter Griffin</option> <option value="2">Lois Griffin</option> <option value="3">Glenn Quagmire</option> <option value="4">Joseph Swanson</option> </select> </form> <br /> <div id="txtHint"><b>Person info will be listed here.</b></div> </body> </html> The showUser() function does the following:

Check if a person is selected Create an XMLHttpRequest object

Create the function to be executed when the server response is ready Send the request off to a file on the server Notice that a parameter (q) is added to the URL (with the content of the dropdown list)

The PHP File


The page on the server called by the JavaScript above is a PHP file called "getuser.php". The source code in "getuser.php" runs a query against a MySQL database, and returns the result in an HTML table: <?php $q=$_GET["q"]; $con = mysql_connect('localhost', 'peter', 'abc123'); 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); ?>

PHP XML
For this please follow the tutorials in xml folder

You might also like