AJAX using Prototype Library - II

Wednesday 7 March 2012 Posted by Sridharan Natarajan 0 comments
The global Ajax object of the prototype library deals with the AJAX functionality. The xmlHttpRequest object creation for various browsers are abstracted by this Ajax object. The entire logic from creating the xmlHttpRequest to sending a request can be achieved in a one line code.

new Ajax.Request('request_url.php', { method:'get' });

The first parameter is the URL of the request; the second is the options. The method refers to the HTTP method to be used; by default method is POST.

Handling Responses

We must have a callback to handle the response back from the ajax request. The callback can be defined in the the options hash.

In the below example two callbacks are defined for success and failure responses. Callback methods are called accordingly based on the response status.

new Ajax.Request('request_url.php',
  {
    method:'get',
    onSuccess: function(res){
      var response = res.responseText;
      alert("Response: " + res);
    },
    onFailure: function(){ alert('Unable to process...') }
  });

Apart from the two callbacl methods used above, prototype has few other callbacks.

  • onUninitialized
  • onLoading
  • onLoaded
  • onInteractive
  • onComplete
  • onException

 Passing Parameters

The additional parameters can be passed in the options hash.

new Ajax.Request('request_url.php', {
  method: 'get',
  parameters: {action: 'update', uid: 6}
  });

Parameters can be used with GET and POST methods.
Labels:

AJAX using Prototype Library - I

Friday 6 May 2011 Posted by Sridharan Natarajan 1 comments
Prototype is a most commonly used javascript library. Prototype provides a number of utility methods to access DOM and AJAX.

As we saw in the previous post, we have to create a XMLHTTPRequest for each browser, send the request and have to define a callback method to receive and process the response. AJAX made simple with Prototype.

Prototype library provides various functions for AJAX for our convenience.

Below are the list for the common options for request and callbacks used with Prototype.

Common options

Option Default Description
asynchronous true Determines whether XMLHttpRequest
is used asynchronously or not. Since synchronous usage is rather unsettling, and
usually bad taste, you should avoid changing this. Seriously.
contentType 'application/ x-www-form-urlencoded' The Content-Type header for your request. You might want to send XML in-stead of the regular URL-encoded format, in which case you would have to change this.
encoding 'UTF-8' The encoding for your request contents. It is best left as is, but should weird encoding issues arise, you may have to tweak it in accordance with other encoding related parts of your page code and server side.
method 'post' The HTTP method to use for the request. The other widespread possibility is 'get'. As a Ruby On Rails special, Prototype also reacts to other verbs (such as 'put' and 'delete' by actually using 'post' and putting an extra '_method' parameter with the originally requested method in there.
parameters ' ' The parameters for the request, which will be encoded into the URL for a 'get' method, or into the request body for the other methods. This can be provided either as a URL-encoded string
or as any Hash-compatible object
(basically anything), with properties representing parameters.
postBody None Specific contents for the request body on a 'post' method (actual method, after possible conversion as described in the
method opt ion above). If it is not provided, the contents of the parameters option will be used instead.
requestHeaders See text Request headers can be passed under
two forms:
  • As an object, with properties representing headers.
  • As an array, with even-index (0, 2...) elements being header names, and odd-index (1, 3...) elements being values.

Prototype automatically provides a set of default headers, that this option can override and augment:
  • X-Requested-With is set to 'XMLHttpRequest'.
  • X-Prototype-Version
    provides Prototype's current version (e.g. 1.5.0).
  • Accept defaults to 'text/ javascript, text/html,
    application/xml, text/ xml, */*'
  • Content-type is built based on the contentType and encoding options.

Common Callbacks

Callback Description
onComplete Triggered at the very end of a request's life-cycle, once the request completed,
status-specific callbacks were called, and possible automatic behaviors were processed.
onException Triggered whenever an XHR error arises. Has a custom signature: the first argument is the requester (i.e. an Ajax.Request instance), the second is the exception object.
onFailure Invoked when a request completes and its status code exists but is not in the 2xy
family. This is skipped if a code-specific callback is defined, and happens before onComplete.
onInteractive (Not guaranteed) Triggered whenever the requester receives a part of the response
(but not the final part), should it be sent in several packets.
onLoaded (Not guaranteed) Triggered once the underlying XHR object is setup, the connection open, and ready to send its actual request.
onLoading (Not guaranteed) Triggered when the underlying XHR object is being setup, and its connection opened.
onSuccess Invoked when a request completes and its status code is undefined or belongs in
the 2xy family. This is skipped if a code-specific callback is defined, and happens before onComplete.
onUninitialized (Not guaranteed) Invoked when the XHR object was just created.
onXYZ With XYZ being an HTTP status code for the response. Invoked when the response just completed, and the status code is exactly the one we used in t he callback name. Prevents execution of onSuccess / onFailure. Happens before onComplete.
 

Responder Callbacks

Callback Description
onCreate Triggered whenever a requester object from the Ajax namespace is created, after
its parameters where adjusted and its before its XHR connection is opened. This
takes two arguments: the requester object and the underlying XHR object.
onComplete Triggered at the very end of a request's life-cycle, once the request completed,
status-specific callbacks were called, and possible automatic behaviors were processed.
onException Triggered whenever an XHR error arises. Has a custom signature: the first argument is the requester (i.e. an Ajax.Request instance), the second is the exception object.
onInteractive (Not guaranteed) Triggered whenever the requester receives a part of the response
(but not the final part), should it be sent in several packets.
onLoaded (Not guaranteed) Triggered once the underlying XHR object is setup, the connection open, and ready to send its actual request.
onLoading (Not guaranteed) Triggered when the underlying XHR object is being setup, and its connection opened.
onUninitialized (Not guaranteed) Invoked when the XHR object was just created.
Labels:

Form Validation Using AJAX

Thursday 28 April 2011 Posted by Sridharan Natarajan 4 comments
Form Validation is the most important feature in any web site that accepts inputs from the world wide users.
In older days, if anything needs to be validated against the existing data in DB, we have to submit the form, validate it in the server and then reloads the page to display the error message. So, the call to the server is explicitly visible to the user.
Now, lets look at how AJAX deals this and bring it to the implicit server call, validates and displays the message in the browser without reloading the page.

Most of the web-sites are having sign-up/register forms to allow users signed-up to their site. There should be a unique username to each users to identify them. So, the usernames entered in the Register form should validated against the existing usernames, so that someone should not avail the username that was already chosan by another user. This validation can be done only in server side.

We will see the step by step implementation for checking the availability of the username chosan.

1. Create a Sign-up form. I have only username text box and Check Availability Button. But, in real-time, there can be lot of fields like, First Name, Last Name, username, password, email and etc. For the explanation of AJAX validation, I considered only username field.


<html>
 <head><title>Form Validations Using AJAX</title></head>
<body>
<form name="register" action="register.php">
<div id="res_msg"></div> 
<label>Enter User Name : </label><input type="text" name="username" value="" /> <br/>
<input type="button" name="check_username" value="Check Availability" onClick="checkAvailability();" />
</form>
</body>
</html> 

The div,<div class="res_msg"></div>, in the above code is just a place holder to display the response message received from the AJAX call.
The button calls the javascript function checkAvailability(). Once the button is clicked, this function will be invoked. We will create the function in the next step.

2. Now, create a XMLHTTPRequest and send a request to the server.

Add the below code inside the <head> tags in the above HTML code.

<script type="text/javascript">

//This creates XMLHttpRequest for various browsers
function getXMLHttpReqObject(){
  var xmlhttp = null; 
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 
  return xmlhttp;

}

function checkAvailability(){
  var username = document.register.username.value;
  var xmlhttp = getXMLHttpReqObject();

  if(xmlhttp != null){
     xmlhttp.onreadystatechange = processCheckAvailability;
     xmlhttp.open("GET","register.php?username=" + username,true);
     xmlhttp.send();

  }

}
</script>



The checkAvailability() functions, creates a XMLHTTPRequest for register.php and sends the request.

3. The next step is to write a callback function processCheckAvailability(). This callback function will be called whenever the readyState value is changed. As you know, the response will be available only when the readyState is 4.

Add the below code inside the <script> tags.
function processCheckAvailability(xmlhttp){
if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
  {
    document.getElementById("res_msg").innerHTML = xmlhttp.responseText;
  }
}

4. Now this is the time to write the server side script that actually validates the input.
Add the following code to register.php
//add code to create a DB connection and selectDB
if(!empty($_POST) and !empty($_POST[´check_username´])){
$sql = "SELECT COUNT(*) AS cnt FROM tbl_users WHERE username=´".$_POST[´username´]."´";
$result = mysql_query($sql);
$row = mysql_fetch_array($result);
if($row[´cnt´] == 0){
echo "Username is available.";
}else{
echo "Username is not available.";
}
}

Now, the AJAX way of doing a form validation is ready.
Labels:

Introduction to AJAX

Saturday 23 April 2011 Posted by Sridharan Natarajan 1 comments
AJAX is an acronym for Asynchronous JavaScript and XML and it is a technique that allows the web pages to be updated asynchronously without refreshing the entire page. It gives better user experience, interactive web pages and seamless server communication.

You can implement AJAX in the following way:

1. Create XMLHttpRequest object
    AJAX uses the XMLHttpRequest object to exchange data asynchronously with  the web server. This XMLHttpRequest object is having the following states:
readyState Status Codes:
0 = uninitialized (Request to the server is not initialized)
1 = loading (Connection to the server is established)
2 = loaded (Request to the server has been loaded)
3 = interactive (Request is in process)
4 = complete (Response is processes and the response is sent)
This state is called readyState.This is the important property of the XMLHttpRequest object.

The readyState 4 means, the request has been processed and the response is received.

2. Define a call back function that will be called whenever the state of the XMLHttpRequest object is changed. The event is called onreadyStateChanged.
Status is an another important property that holds the status of the response returned from the server.
Ex.
200: "OK"
404: Page not found

3. Send the request.

4. Most importantly the responseText/responseHTML holds the actual body of the response.  This can be displayed in any part of the web page.

Now we will see how to implement the above steps.
<html>
<head>
<script type="text/javascript">

//This creates XMLHttpRequest for various browsers
function getXMLHttpReqObject(){
  var xmlhttp = null; 
  if (window.XMLHttpRequest)
  {// code for IE7+, Firefox, Chrome, Opera, Safari
    xmlhttp=new XMLHttpRequest();
  }
  else
  {// code for IE6, IE5
    xmlhttp=new ActiveXObject("Microsoft.XMLHTTP");
  }
 
  return xmlhttp;

}

function getEmpName(){
  var empId = document.getElementById("getEmpName").value;
  var xmlhttp = getXMLHttpReqObject();

  if(xmlhttp != null){
     xmlhttp.onreadystatechange = displayName;
     xmlhttp.open("GET","getEmpName.php?empId=" + empId,true);
     xmlhttp.send();

  }

}

//this is the callback function that will be called whenever the readystate is changed.
function displayName(xmlhttp){
  
  if (xmlhttp.readyState == 4 && xmlhttp.status == 200)
  {
    document.getElementById("empName").innerHTML = xmlhttp.responseText;
  }
  
} 

</script>

</head>

<body>
   <form>
     Enter Emp Id <input type="text" name="empId" value="" /> &nbsp;
<input type="button" name="getEmpName" id="getEmpName" value="Get Emp. Name" onClick="getEmpName();"/> </br>
Employee Name: <span id="empName"></span>
   </form>
</body>

</html>

Labels: