What is AJAX?

0
60

Whead wear is AJAX?

  • AJAX stands for Asynchronous JavaScript and XML. AJAX is a brand brand new technique for creating much better, quicker, and more interworkive web applications with the help of XML, HTML, CSS, and Java Script.

  • Ajax uses XHTML for content, CSS for presentation, alengthy with Document Object Model and JavaScript for dynamic content display.

  • Conventional web applications transmit information to and from the sever using synchronous requests. It means you fill away a form, hit submit, and get immediateed to a brand brand new page with brand brand new information from the server.

  • With AJAX, when you hit submit, JavaScript will generate a request to the server, interpret the results, and update the current screen. In the purest sense, the user would never understand thead wear anything was workually transmitted to the server.

  • XML is commonly used as the format for receiving server data, although any format, including simple text, can be used.

  • AJAX is a web blineser technology independent of web server smoothbattlee.

  • A user can continue to use the application while the care locatednt program requests information from the server in the background.

  • Intuitive and natural user interworkion. Clicking is not required, mouse movement is a sufficient workuallyt trigger.

  • Data-driven as opposed to page-driven.

Rich Internet Application Technology

AJAX is the many viable Rich Internet Application (RIA) technology so far. It is getting tremendous induscheck momentum and a number of tool kit and frameworks are emerging. But at the exwork exwork same time, AJAX has blineser incompatibility and it is supported simply simply by JavaScript, which is hard to maintain and debug.

AJAX is Based on Open Standards

AJAX is based on the folloearng open up up standards:

  • Blineser-based presentation using HTML and Cascading Style Sheets (CSS).
  • Data is stored in XML format and fetched from the server.
  • Behind-the-scenes data fetches using XMLHttpRequest objects in the blineser.
  • JavaScript to generate everything happen.

AJAX – Technologies

AJAX cannot work independently. It is used in combination with other technologies to generate interworkive webpages.

JavaScript

  • Loosely kindd scripting language.
  • JavaScript function is calbrought when an workuallyt occurs in a page.
  • Glue for the whole AJAX operation.

DOM

  • API for accessing and manipulating structured documents.
  • Represents the structure of XML and HTML documents.

CSS

  • Allows for a clear separation of the presentation style from the content and may be alterd programmatically simply simply by JavaScript.

XMLHttpRequest

  • JavaScript object thead wear performs asynchronous interworkion with the server.

AJAX – Examples

Here is a list of a couple of famous web applications thead wear generate use of AJAX.

Google Maps

A user can drag an entire chart simply simply by using the mouse, instead than clicking on a button.

Google Suggest

As you kind, Google will away fromer suggestions. Use the arline keys to navigate the results.

Gmail

Gmail is a webmail, built on the idea thead wear email can be more intuitive, efficient and useful.

Yahoo Maps (brand brand new)

Now it's workually easier and more fun to get where you're going!

Difference in AJAX and Conventional CGI Program

Try these two examples one simply simply by one and you will feel the difference. While checking AJAX example, generally presently there is not discontinuity and you get the response very quickly, but when you check the standard GCI example, you would have to wait around for the response and your own own page furthermore gets refreshed.

AJAX Example:

*
=

Standard Example:

*
=

NOTE: We have given a more complex example in AJAX Database.

AJAX – Blineser Support

All the available blinesers cannot support AJAX. Here is a list of major blinesers, thead wear support AJAX.

  • Mozilla Firefox 1.0 and above.
  • Netscape version 7.1 and above.
  • Apple Safari 1.2 and above.
  • Microsmooth Internet Explorer 5 and above.
  • Konqueror.
  • Opera 7.6 and above.

When you write your own own next application, do conpartr the blinesers thead wear do not support AJAX.

NOTE: When we say thead wear a blineser does not support AJAX, it simply means thead wear the blineser does not support creation of Javascript object XMLHttpRequest object.

Writing Blineser Specific Code

The Simplest way to generate your own own source code compatible with a blineser is to use check…capture blocks in your own own JavaScript.

<html>
<body>
<script language="javascript" kind="text/javascript">
<!-- 
//Blineser Support Code
function ajaxFunction(){
   var ajaxRequest;  // The variable thead wear generates Ajax probable!
   
   check{
      // Opera 8.0+, Firefox, Safari 
      ajaxRequest = brand brand new XMLHttpRequest();
   }capture (e){
   
      // Internet Explorer Blinesers
      check{
         ajaxRequest = brand brand new ActiveXObject("Msxml2.XMLHTTP");
      }capture (e) {
         check{
            ajaxRequest = brand brand new ActiveXObject("Microsmooth.XMLHTTP");
         }capture (e){
      
            // Something went wrong
            alert("Your blineser broke!");
            return false;
         }
      }
   }
}
//-->
</script>
<form name='myForm'>
   Name: <input kind='text' name='username' /> <br />
   Time: <input kind='text' name='time' />
</form>
</body>
</html>

In the above JavaScript code, we check 3 times to generate our XMLHttpRequest object. Our preliminary attempt:

  • ajaxRequest = brand brand new XMLHttpRequest();

It is for Opera 8.0+, Firefox, and Safari blinesers. If it fails, we check two more times to generate the appropriate object for an Internet Explorer blineser with:

  • ajaxRequest = brand brand new ActiveXObject("Msxml2.XMLHTTP");

  • ajaxRequest = brand brand new ActiveXObject("Microsmooth.XMLHTTP");

If it doesn't work, then we can use an extremely awaydated blineser thead wear doesn't support XMLHttpRequest, which furthermore means it doesn't support Ajax.

Most likely though, our variable ajaxRequest will now be set to exworkly exworkly whead wearever XMLHttpRequest standard the blineser uses and we can start sending data to the server. The step-wise AJAX workflow is exsimpleed in the next chapter.

AJAX – Action

This chapter gives you a clear picture of the exwork steps of AJAX operation.

Steps of AJAX Operation

  • A care locatednt workuallyt occurs.
  • An XMLHttpRequest object is generated.
  • The XMLHttpRequest object is configured.
  • The XMLHttpRequest object generates an asynchronous request to the Webserver.
  • The Webserver returns the result containing XML document.
  • The XMLHttpRequest object calls the callback() function and processes the result.
  • The HTML DOM is updated.

Let us conaspectr these steps one simply simply by one.

A Care locatednt Event Occurs

  • A JavaScript function is calbrought as the result of an workuallyt.

  • Example: validateUserId() JavaScript function is chartped as an workuallyt handler to an onkeyup workuallyt on input form field in whose id is set to "userid"

  • <input kind="text" dimension="20" id="userid" name="id" onkeyup="validateUserId();">.

The XMLHttpRequest Object is Created

var ajaxRequest;  // The variable thead wear generates Ajax probable!
function ajaxFunction(){
   check{
      
      // Opera 8.0+, Firefox, Safari
      ajaxRequest = brand brand new XMLHttpRequest();
   }capture (e){
   
      // Internet Explorer Blinesers
      check{
         ajaxRequest = brand brand new ActiveXObject("Msxml2.XMLHTTP");
      }capture (e) {
      
         check{
            ajaxRequest = brand brand new ActiveXObject("Microsmooth.XMLHTTP");
         }capture (e){
      
            // Something went wrong
            alert("Your blineser broke!");
            return false;
         }
      }
   }
}

The XMLHttpRequest Object is Configured

In this particular particular step, we will write a function thead wear will be triggered simply simply by the care locatednt workuallyt and a callback function processRequest() will be registered.

function validateUserId() {
   ajaxFunction();
   
   // Here processRequest() is the callback function.
   ajaxRequest.onreadystatealter = processRequest;
   
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   
   ajaxRequest.open up up("GET", url, true);
   ajaxRequest.send(null);
}

Making Asynchronous Request to the Webserver

Source code is available in the above piece of code. Code composed in bold kindface is responsible to generate a request to the webserver. This is all being done using the XMLHttpRequest object ajaxRequest.

function validateUserId() {
   ajaxFunction();
   
   // Here processRequest() is the callback function.
   ajaxRequest.onreadystatealter = processRequest;
   
   if (!target) target = document.getElementById("userid");
   var url = "validate?id=" + escape(target.value);
   
   ajaxRequest.open up up("GET", url, true);
   ajaxRequest.send(null);
}

Assume you enter Zara in the userid package, then in the above request, the URL is set to "validate?id=Zara".

Webserver Returns the Result Containing XML Document

You can implement your own own server-part script in any language, however it is logic need to be as follows.

  • Get a request from the care locatednt.
  • Parse the input from the care locatednt.
  • Do required processing.
  • Send the awayput to the care locatednt.

If we assume thead wear you are going to write a servallow, then here is the piece of code.

public void doGet(HttpServallowRequest request, HttpServallowResponse response) thlines IOException, ServallowException 
{
   String targetId = request.getParameter("id");
   
   if ((targetId != null) && !accounts.containsKey(targetId.trim()))
   {
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      response.getWriter().write("true");
   }
   else
   {
      response.setContentType("text/xml");
      response.setHeader("Cache-Control", "no-cache");
      response.getWriter().write("false");
   }
}

Callback Function processRequest() is Calbrought

The XMLHttpRequest object was configured to call the processRequest() function when generally presently there is a state alter to the readyState of the XMLHttpRequest object. Now this particular particular function will receive the result from the server and will do the required processing. As in the folloearng example, it sets a variable message on true or false based on the returned value from the Webserver.

 
function processRequest() {
   if (req.readyState == 4) {
      if (req.status == 200) {
         var message = ...;
...
}

The HTML DOM is Updated

This is the final step and in this particular particular step, your own own HTML page will be updated. It happens in the folloearng way:

  • JavaScript gets a reference to any element in a page using DOM API.
  • The recommended way to gain a reference to an element is to call.
document.getElementById("userIdMessage"), 
// where "userIdMessage" is the ID attribute 
// of an element appearing in the HTML document
  • JavaScript may now be used to modify the element's attributes; modify the element's style properconnects; or add, remove, or modify the kid elements. Here is an example:

<script kind="text/javascript">
<!--
function setMessageUsingDOM(message) {
   var userMessageElement = document.getElementById("userIdMessage");
   var messageText;
   
   if (message == "false") {
      userMessageElement.style.colour = "red";
      messageText = "Invalid User Id";
   }
   else 
   {
      userMessageElement.style.colour = "green";
      messageText = "Valid User Id";
   }
   var messageBody = document.generateTextNode(messageText);
   
   // if the messageBody element has been generated easy 
   // replace it otherwise append the brand brand new element
   if (userMessageElement.kidNodes[0]) {
      userMessageElement.replaceChild(messageBody, userMessageElement.kidNodes[0]);
   } 
   else
   {
      userMessageElement.appendChild(messageBody);
   }
}
-->
</script>
<body>
<div id="userIdMessage"><div>
</body>

If you have understood the above-mentioned sworkually steps, then you are almany done with AJAX. In the next chapter, we will see XMLHttpRequest object in more detail.

AJAX – XMLHttpRequest

The XMLHttpRequest object is the key to AJAX. It has been available ever since Internet Explorer 5.5 was relreare locatedved in July 2000, but was not compallowey discovered until AJAX and Web 2.0 in 2005 became popular.

XMLHttpRequest (XHR) is an API thead wear can be used simply simply by JavaScript, JScript, VBScript, and other web blineser scripting languages to transfer and manipulate XML data to and from a webserver using HTTP, establishing an independent interconnection channel between a webpage's Care locatednt-Side and Server-Side.

The data returned from XMLHttpRequest calls will often be provided simply simply by back-end databases. Beparts XML, XMLHttpRequest can be used to fetch data in other formats, e.g. JSON or workually simple text.

You already have seen a couple of examples on how to generate an XMLHttpRequest object.

Listed below is listed are a couple of of the methods and properconnects thead wear you have to get familiar with.

XMLHttpRequest Methods

  • abort()

    Cancels the current request.

  • getAllResponseHeaders()

    Returns the compallowe set of HTTP headers as a string.

  • getResponseHeader( headerName )

    Returns the value of the specified HTTP header.

  • open up up( method, URL )

    open up up( method, URL, async )

    open up up( method, URL, async, userName )

    open up up( method, URL, async, userName, compalloweword )

    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 probable.

    The "async" parameter specifies whether the request need to be handbrought asynchronously or not. "true" means thead wear the script processing carries on after the send() method withaway wait arounding for a response, and "false" means thead wear the script wait arounds 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 Properconnects

  • onreadystatealter

    An workuallyt handler for an workuallyt thead wear fires at every state alter.

  • readyState

    The readyState home degreats the current state of the XMLHttpRequest object.

    The folloearng table provides a list of the probable values for the readyState home:

    State Description
    0 The request is not preliminaryized.
    1 The request has been set up.
    2 The request has been sent.
    3 The request is within process.
    4 The request is compallowed.

    readyState = 0 After you have generated the XMLHttpRequest object, but before you have calbrought the open up up() method.

    readyState = 1 After you have calbrought the open up up() method, but before you have calbrought send().

    readyState = 2 After you have calbrought send().

    readyState = 3 After the blineser has established a communication with the server, but before the server has compallowed the response.

    readyState = 4 After the request has been compallowed, and the response data has been compallowely received from the server.

  • responseText

    Returns the response as a string.

  • responseXML

    Returns the response as XML. This home returns an XML document object, which can be examined and parsed using the W3C DOM node tree methods and properconnects.

  • status

    Returns the status as lots (e.g., 404 for "Not Found" and 200 for "OK").

  • statusText

    Returns the status as a string (e.g., "Not Found" or "OK").

AJAX – Database Operations

To clearly illustrate how easy it is to access information from a database using AJAX, we are going to construct MySQL queries on the fly and display the results on "ajax.html". But before we proceed, allow us do the ground work. Create a table using the folloearng command.

NOTE: We are assuming you have sufficient privilege to perform the folloearng MySQL operations

CREATE TABLE 'ajax_example' (
   'name' varchar(50) NOT NULL,
   'age' int(11) NOT NULL,
   'love-making' varchar(1) NOT NULL,
   'wpm' int(11) NOT NULL,
   PRIMARY KEY  ('name')
) 

Now dump the folloearng data into this particular particular table using the folloearng SQL statements:

INSERT INTO 'ajax_example' VALUES ('Jerry', 120, 'm', 20);
INSERT INTO 'ajax_example' VALUES ('Regis', 75, 'm', 44);
INSERT INTO 'ajax_example' VALUES ('Frank', 45, 'm', 87);
INSERT INTO 'ajax_example' VALUES ('Jill', 22, 'f', 72);
INSERT INTO 'ajax_example' VALUES ('Tracy', 27, 'f', 0);
INSERT INTO 'ajax_example' VALUES ('Juare located', 35, 'f', 90);

Care locatednt Side HTML File

Now allow us have our care locatednt part HTML file, which is ajax.html, and it will have the folloearng code:

<html>
<body>
<script language="javascript" kind="text/javascript">
<!-- 
//Blineser Support Code
function ajaxFunction(){
   var ajaxRequest;  // The variable thead wear generates Ajax probable!
   check{
   
      // Opera 8.0+, Firefox, Safari
      ajaxRequest = brand brand new XMLHttpRequest();
   }capture (e){
      
      // Internet Explorer Blinesers
      check{
         ajaxRequest = brand brand new ActiveXObject("Msxml2.XMLHTTP");
      }capture (e) {
         
         check{
            ajaxRequest = brand brand new ActiveXObject("Microsmooth.XMLHTTP");
         }capture (e){
         
            // Something went wrong
            alert("Your blineser broke!");
            return false;
         }
      }
   }
   
   // Create a function thead wear will receive data
   // sent from the server and will update
   // div section in the exwork exwork same page.
   ajaxRequest.onreadystatealter = function(){
   
      if(ajaxRequest.readyState == 4){
         var ajaxDisplay = document.getElementById('ajaxDiv');
         ajaxDisplay.innerHTML = ajaxRequest.responseText;
      }
   }
   
   // Now get the value from user and compallowe it to
   // server script.
   var age = document.getElementById('age').value;
   var wpm = document.getElementById('wpm').value;
   var love-making = document.getElementById('love-making').value;
   var queryString = "?age=" + age ;
   
   queryString +=  "&wpm=" + wpm + "&love-making=" + love-making;
   ajaxRequest.open up up("GET", "ajax-example.php" + queryString, true);
   ajaxRequest.send(null); 
}
//-->
</script>
<form name='myForm'>
   Max Age: <input kind='text' id='age' /> <br />
   Max WPM: <input kind='text' id='wpm' /> <br />
   Sex: <select id='love-making'>
   <option value="m">m</option>
   <option value="f">f</option>
   </select>
   <input kind='button' onclick='ajaxFunction()' value='Query MySQL'/>
</form>
<div id='ajaxDiv'>Your result will display here</div>
</body>
</html>

NOTE: The way of compalloweing variables in the Query is according to HTTP standard and have formA.

URL?variable1=value1;&variable2=value2;

The above code will give you a screen as given below:

NOTE: This is dummy screen and would not work

Max Age: 

Max WPM:

Sex:
m
f

Your result will display here in this particular particular section after you have made your own own encheck.

NOTE: This is a dummy screen.

Server Side PHP File

Your care locatednt-part script is ready. Now, we have to write our server-part script, which will fetch age, wpm, and love-making from the database and will send it back to the care locatednt. Put the folloearng code into the file "ajax-example.php".

<?php
$dbhost = "localhost";
$dbuser = "dbusername";
$dbcompallowe = "dbcompalloweword";
$dbname = "dbname";
	
   //Connect to MySQL Server
mysql_connect($dbhost, $dbuser, $dbcompallowe);
	
   //Select Database
mysql_select_db($dbname) or expire(mysql_error());
	
   // Retrieve data from Query String
$age = $_GET['age'];
$love-making = $_GET['love-making'];
$wpm = $_GET['wpm'];
	
   // Escape User Input to help prworkuallyt SQL Injection
$age = mysql_real_escape_string($age);
$love-making = mysql_real_escape_string($love-making);
$wpm = mysql_real_escape_string($wpm);
	
   //construct query
$query = "SELECT * FROM ajax_example WHERE love-making = '$love-making'";

if(is_numeric($age))
	$query .= " AND age <= $age";

if(is_numeric($wpm))
	$query .= " AND wpm <= $wpm";
	
   //Execute query
$qry_result = mysql_query($query) or expire(mysql_error());

   //Build Result String
$display_string = "<table>";
$display_string .= "<tr>";
$display_string .= "<th>Name</th>";
$display_string .= "<th>Age</th>";
$display_string .= "<th>Sex</th>";
$display_string .= "<th>WPM</th>";
$display_string .= "</tr>";

   // Insert a brand brand new line in the table for every person returned
while($line = mysql_fetch_array($qry_result)){
   $display_string .= "<tr>";
   $display_string .= "<td>$line[name]</td>";
   $display_string .= "<td>$line[age]</td>";
   $display_string .= "<td>$line[love-making]</td>";
   $display_string .= "<td>$line[wpm]</td>";
   $display_string .= "</tr>";
}
echo "Query: " . $query . "<br />";
$display_string .= "</table>";

echo $display_string;
?>

Now check simply simply by entering a valid value (e.g., 120) in Max Age or any other package and then click Query MySQL button.

Max Age: 

Max WPM:

Sex:
m
f

Your result will display here in this particular particular section after you have made your own own encheck.

If you have successcompallowey compallowed this particular particular lesson, then you understand how to use MySQL, PHP, HTML, and Javascript in tandem to write AJAX applications.

AJAX – Security

AJAX Security: Server Side

  • AJAX-based Web applications use the exwork exwork same server-part security schemes of regular Web applications.

  • You specify authentication, authorization, and data protection requirements in your own own web.xml file (declarative) or in your own own program (programmatic).

  • AJAX-based Web applications are subject to the exwork exwork same security threats as regular Web applications.

AJAX Security: Care locatednt Side

  • JavaScript code is visible to a user/hacker. Hacker can use JavaScript code for inferring server-part weaknesses.

  • JavaScript code is downloaded from the server and executed ("eval") at the care locatednt and can compromise the care locatednt simply simply by mal-intended code.

  • Downloaded JavaScript code is constrained simply simply by the sand-package security model and can be relaxed for signed JavaScript.

AJAX – Issues

AJAX is glineing very quick and thead wear is the reason thead wear it contains many issues with it. We hope with the compallowees of time, they will be resolved and AJAX will become ideal for web applications. We are listing down a couple of issues thead wear AJAX currently suffers from.

Complexity is withincrreare locatedved

  • Server-part developers will need to understand thead wear presentation logic will be required in the HTML care locatednt pages as well as in the server-part logic.

  • Page developers must have JavaScript technology sdestroys.

AJAX-based applications can be difficult to debug, check, and maintain

  • JavaScript is hard to check – automatic checking is hard.
  • Weak modularity in JavaScript.
  • Lack of style patterns or best prworkice guideseriess yet.

Toolkit is/Frameworks are not mature yet

  • Most of all of them are in beta phase.

No standardization of the XMLHttpRequest yet

  • Future version of IE will adawayfit this particular particular.

No support of XMLHttpRequest in old blinesers

  • Iframe will help.

JavaScript technology dependency and incompatibility

  • Must be enabbrought for applications to function.
  • Still a couple of blineser incompatibiliconnects exist.

JavaScript code is visible to a hacker

  • Poorly styleed JavaScript code can invite security issues.
SHARE
Previous articleCICS
Next articleApache Pig

NO COMMENTS

LEAVE A REPLY