My Blog List

Friday, July 11, 2008

Sending Data to a Database-Enabled XHR

Sending data to the database starts with an XHR GET or POST to a server-side language/engine. After the server receives the request, it parses the XML or simple key/value pair sent by the XHR and updates the database accordingly. This request model updates the database based on user interaction, without ever refreshing the browser. This is a great way to replicate the Save button in a desktop application. We will use this model in the sample by saving sent emails to the database to allow the user to retrieve it at a later time.

Sending data to a database-enabled XHR provides the most power out of the request models mentioned in this chapter. Essentially, it provides us with full database control through the XHR. There are many different situations in which you will want to post data to the server with the XHR. For example, you might want to password-protect your XHR by sending a password to the server, and then authenticate it before querying the database. Or, you might want to insert or update records in a database, or select records based on the request.

Server-side interaction with Ajax allows us to create on-demand database updates, just as a desktop application would save our progress. There is so much to cover on the server side of a request, which is why I dedicated an entire section of the book to this very topic in , "Server-Side Interaction." But first, it is important that there be a solid understanding of the object and its capabilities before diving into complex code

A Database-Enabled XHR

Learning how to create a database-enabled XHR is like making your first database interaction. It opens a whole new world of possibilities and is not as complicated as you would think; it is trivial compared to the complex functionality that you can achieve with database-integrated Ajax. To use this model, we would start with a request to a server-side language. The server-side language would query the database, based on what was requested, via custom methods that we would write to handle specific database interactions. After the data has been received by the server-side language, it can be returned to the XHR that originally requested it as XML, JSON, or text and handled by the client-side code. This request allows users to retrieve custom data based on the requests that they make.



Although this request model is quite a bit more powerful than a standard request, you might want even more control. The next model will provide you with the ability to post data to the database and receive data based on the request, or simply receive a Boolean for a successful database INSERT, all without refreshing the page.

A Standard XHR

If you were to break down an Ajax request to its bare functionality, this is what you would be left with. In this scenario, a static XML, JSON, or text file residing on the same domain is requested by the XHR object through the GET method. It is then returned by the server to be handled by the client-side code that requested it. Take a look at to see the flow of a standard Ajax model.


This type of request can be beneficial if a web-savvy client or a developer is updating the requested file on the server, which is typically not the case, especially with large-scale applications. If this model is not going to meet your needs, the next approach has what this model is missing most: a database.

An In-Depth Look at XMLHttpRequest

The XHR (XMLHttpRequest) object is the core of the Ajax engine. It is the object that enables a page to get data from (using the GET method) or post data to (using the POST method) the server as a background request, which means that it does not refresh the browser during this process. As we covered in , "Introduction to Ajax," the hype surrounding Ajax has been based on this object and the fact that the interaction model it creates is more intuitive than a standard HTTP (Hypertext Transport Protocol) request. This is because changes happen on demand when the user makes them, and allow web applications to feel more like desktop applications. The XHR eliminates the need to wait on the server to respond with a new page for each request and allows users to continue to interact with the page while the requests are made in the background. This is a key factor in maintaining an intuitive user experience: Users should never be aware of the process; rather, they should be focused on the task at hand, which is using your service. The on-demand nature of the XHR is extremely beneficial when dealing with web applications where users are trying to accomplish tasks because the standard HTTP request is better suited for presentation-type websites.

Aside from the background data processing, the GET and POST methods of the XHR object work the same as a standard HTTP request. Using either the POST or the GET method allows you to make a request for data from the server and receive a response in any standardized format. The most common formats in which to receive a response are XML, JSON (JavaScript Object Notation), and text. We will cover all formats , "The Response." POST is specifically useful when sending data that is larger than 512 bytes (an amount that the GET method cannot handle). After a response is received, the application can be populated with new data from the server by using the DOM with DHTML, which is a combination of XHTML, JavaScript, and CSS.

All Ajax requests start with a client-side interaction that is typically managed by JavaScript. JavaScript creates the XHR object and makes an HTTP request to the server. What happens from here can take on many different forms. Let's take a look at three of the most common request models and their processes.

Saturday, July 5, 2008

A List of XHR Properties and Corresponding Definitions

Properties

Definitions

onreadystatechange

An event handler that fires when the state of the request object changes.

readyState

Returns number values that indicate the current state of the object. These values are listed in Table 2.3.

responseText

String version of the response from the server.

responseXML

DOM-compatible document object of the response from the server.

status

Status code of the response from the server.

statusText

A status message returned as a string.

Wednesday, June 25, 2008

A List of XHR Methods and Corresponding Definitions

Methods

Definitions

Abort()

Cancels the current HTTP request.

getAllResponseHeaders()

Retrieves the values of all the HTTP headers.

geTResponseHeader("label")

Retrieves the value of a specified HTTP header from the response body.

Open("method", "URL"[, asyncFlag[, "userName"[, "password"]]])

Initializes an MSXML2.XMLHTTP or Microsoft.XMLHTTP request, and specifies the method, URL, and authentication information for the request.

Send(content)

Sends an HTTP request to the server and receives a response.

SetRequestHeader("label", "value")

Specifies the value of an HTTP header based on the label.

Friday, June 13, 2008

Creating the Object


With a better understanding of the XHR and different request models, we can now focus on creating the object. Creating the request object is trivial in comparison to the power that is unleashed when applying it to a project.

To create the request object, you must check to see if the browser uses the XHR or the ActiveX object. The primary difference between the objects is the browsers that use them. Windows Internet Explorer (IE) 5 and above use the ActiveX object, whereas Mozilla, Firefox, Netscape, Opera, and Safari use the native JavaScript XHR object. The second difference is the way in which we create each object: Windows IE requires the name of the object to be passed as a parameter to the ActiveX constructor, whereas the other browsers provide us with the native JavaScript object, which only we need to instantiate:

function makeRequest(url)
{
if(window.XMLHttpRequest)
{
request = new XMLHttpRequest();
}
else if(window.ActiveXObject)
{
request = new ActiveXObject("Msxml2.XMLHTTP");
}

sendRequest(url);
}

As you can see from the code sample, the object creation is really a very simple task. We create a method named makeRequest to handleyou guessed itmaking the request and to decipher what type of object the browser uses by creating a condition that checks for the native XHR object. If this object is not available, we check for the ActiveXObject. After the correct object type has been identified for the current browser, the correct object is instantiated and a request object is created. This object can now be used to access all the properties and methods listed in which are available to the XHR object.