6.2. JavaScript and Ajax

Hiding and displaying the forms alongside the action icons is something that can be accomplished with basic JavaScript and will certainly be discussed later in this chapter. However, more complex scripting is needed for the file listing to reflect the state of the remote directory without requiring a full page reload. For this you must have a basic understanding of Ajax.

Not too many years ago a developer used to be able to get by with just knowing HTML. Then forms and CGI came about, followed by JavaScript and CSS. The simple days are long gone; now web sites are offering the same functionality that used to be the exclusive domain of desktop applications. You need to know a whole slew of different technologies and languages just to be even a moderately capable web developer.

A new buzzword, Ajax (which stands for Asynchronous JavaScript And XML), has surfaced in the past few years referring to the use of JavaScript to dynamically update a page's contents. Many web applications use JavaScript in this manner to improve functionality and add special eye-candy effects. It's not really a new concept, however; in fact developers who have been around a while may know it by another name — DHTML (Dynamic HTML).

The basic underpinning of the Ajax paradigm is the ability to make an HTTP request behind the scenes while a visitor is viewing a page. The web server responds with a message that JavaScript then parses and uses to update the page by replacing content, changing styles, and so on. Oftentimes the response message is sent as XML, but it can also be an HTML fragment, plain text, or even JavaScript code. You may find it easier to send responses as one of the latter three and use XML only when it's really necessary.

Please keep in mind that this is a PHP book, not a JavaScript book. JavaScript is a programming language in its own right and I can't delve into all of its intricacies. I'll cover just what you're sure to need. I will offer this advice, though: be critical. A lot of resources are available to help you learn JavaScript. However, for some reason many of them are filled with meaningless hype or present bad code. Perhaps this is because of the language's checkered past. My rule of thumb is to run away screaming in the opposite direction if you see browser detection performed by checking the user agent string or if the author says JavaScript is a lighter version of Java (which is utterly wrong). I recommend ppk on JavaScript written by Peter-Paul Koch and published by New Riders for solid, practical and sound information.

6.2.1. The XMLHttpRequest Object

The JavaScript implementation in most modern browsers uses the XMLHttpRequest object to transact the HTTP request, but some older versions of Internet Explorer do this through some version of the Microsoft.XmlHttp ActiveX object. They're all used pretty much the same way but getting the initial reference to the correct object is the tricky part. As such, this is a prime candidate for reusable code.

Save the following JavaScript function as public_file/js/ajax.js to encapsulate the logic of identifying which object is available and to return an instance reference:

function createXMLHTTPObject()
{
    if (typeof XMLHttpRequest != 'undefined')
    {
        return new XMLHttpRequest();
    }
    else if (window.ActiveXObject)
    {
        var axo = [
            'Microsoft.XmlHttp',

'MSXML2.XmlHttp',
            'MSXML2.XmlHttp.3.0',
            'MSXML2.XmlHttp.4.0',
            'MSXML2.XmlHttp.5.0'
        ];

        for (var i = axo.length − 1; i > −1; i--)
        {
            try
            {
                httpObj = new ActiveXObject(axo[i]);
                return httpObj;
            }
            catch(e) {}
        }
    }

   throw new Error('XMLHTTP not supported'),
}

The function checks first whether the more widely used XMLHttpRequest is available. If so, it returns an instance of it to the calling code. Otherwise the code checks for one of the various versions of the Microsoft.XmlHttp ActiveX objects. An exception will be thrown if no suitable objects are available to the client.

Communicating with the server from the client is easy once the correct reference is obtained. Table 6-1 shows the object's methods and Table 6-2 shows its properties.

Table 6-1. XMLHttpRequest Methods
MethodDescription
abort()Cancel the request.
getAllResponseHeaders()Retrieve all the HTTP response headers.
getResponseHeader(name)Retrieve the value of a particular header.
open(method, url, async[, username [, password]])Establish a connection between the client and server.

method specifies which HTTP method will be used (that is, GET, POST, and so on).

url is the URL of the requested resource.

async is a Boolean value indicating whether the request will be made asynchronously or not.

username and password are optional arguments when authentication is required to access the resource.
send(data)Send the request.
setRequestHeader(name, value)Set a header's value.

Table 6-2. xmlhttprequest properties
PropertyDescription
onreadystatechangeEvent handler assigned to fire each time readyState changes.
readyStateThe current request of the state:
0Uninitialized — the object has been created but open() hasn't been called
1Loaded — open() has been called but send() has not
2Loaded — send() has been called and the request's headers have been received
3Interactive — the response is being received
4Completed

responseTextThe response as text.
responseXMLThe response as XML.
statusThe HTTP response code (that is, 200, 404, and so on).
statusTextThe text accompanying the request's HTTP response code (that is, OK, File not found, and so on).

To perform an Ajax request, the onreadystatechange property is assigned a function as an event handler, which contains the code to parse the response coming back from the server. The handler must check to make sure the value of readyState is 4, which means the request has completed. Other readyState values indicate different stages in the request process as identified previously in Table 6-2.

The connection itself is initiated by calling the object's open() method which accepts the request method, the URL and whether or not the connection should be asynchronous (true) or synchronous/blocking (false). You will almost always use true for this argument or otherwise the user will be blocked from anything on the page until the request has completed. Keep in mind as well that the URL must be in same domain from which the original page was requested. This is by design and was done as a security precaution. The send() method then sends the request to the server.

Here is some code to illustrate this process:

<script type="text/javascript" src="js/ajax.js"></script>
<script type="text/javascript">
window.onload = function()
{
    window.httpObj = createXMLHTTPObject();
}

function doRequest()

{
    window.httpObj.onreadystatechange = function()
    {
        if (window.httpObj.readyState == 4 && window.httpObj.responseText)
        {
            // code to parse the response and update the page's content
            // goes here
        }
    }

   var url = 'process.php?param1=value+1&param2=value+2&nocache=' +
        (new Date()).getTime();
    window.httpObj.open('GET', url , true);
    window.httpObj.send(null);
}
</script>

I passed null as an argument to send() in the example, because I used the GET method. The data was provided as parameters in the URL string. To use POST instead, set the appropriate HTTP headers with setRequestHandler() and provide the encoded data to send(). Here is an example using POST:

function doRequest()
{
    ...
    var data = 'param1=value+1&param2=value+2';
    var url = 'process.php?cache=' + (new Date()).getTime();

    window.httpObj.open('POST', url, true);
    window.httpObj.setRequestHeader('Content-type',
        'application/x-www-form-urlencoded'),
    window.httpObj.setRequestHeader('Content-length', data.length);
    window.httpObj.setRequestHeader('Connection', 'close'),

    window.httpObj.send(data);
}

I recommend appending a timestamp to the URL regardless if you're sending the information via GET or POST. This ensures the URL is unique and prevents the request from being cached by the browser or any intermediate proxies.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.225.56.194