Handling Ajax Response


when you are sending request to the server, you can get a response in the below specified function.
onreadystatechange = functionname

functionname – is a javascript function to handle the ajax response.

function definition should be like this.

function processResponse(req, divid)
{
if (req.readyState == 4) {
if (req.status == 200) {
document.getElementById(divid).innerHTML=req.responseText;
}
}
}

Let’s see what this function should do. First, the function needs to check for the state of the request. The request readyState has 4 values is as follows.

  • 0  – uninitialized
  • 1  – loading
  • 2  – loaded
  • 3  – interactive
  • 4  – complete

If the state has the value 4, that means the full server response is received and it’s OK to continue processing it.
if (req.readyState == 4) { // response is received.}

Second thing,  is to check the status code of the HTTP server response. For that, we will look at value 200 for OK response.Otherwise there has to be some problem with the request.

if (req.status == 200) { //request status is OK}

After the above two cases are OK, then you have to process the response data based on your requirement. You have two options to access that data

responseText – this will return the server response as text
responseXML – this will return the response as an XML document(you can parse the XML and get the data using javascript DOM functions)

Ajax Basics – https://manikandanmv.wordpress.com/2008/09/23/ajax-asynchronous-javascript-and-xml/
Ajax GET request – https://manikandanmv.wordpress.com/2008/09/29/ajax-example/
Ajax POST request – https://manikandanmv.wordpress.com/2008/09/25/ajax-post-request/

Advertisements

Tags: , , , , , , , ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s


%d bloggers like this: