#native_company# #native_desc#
#native_cta#

Using XML: A PHP Developer’s Primer, Part 3

By PHP Builder Staff
on April 9, 2012

The Ajax Engine
The init function initialises the Ajax environment and assigns all the required event handlers. If Ajax is not available via the XMLHTTPRequest object, the function exits and no event handlers are assigned.

Javascript:
var xmlHTTP = false; // holds a reference to an XMLHTTPRequest object
var bookInfoXsl = false; // holds a reference to the XSL transformer object

var bookSummary; // holds a reference to the book summary div

init(); // initialise the Ajax application

function init()
{
    if (!(xmlHTTP = getXMLHTTP())) {
        return; // don’t continue if XMLHttpRequest isn’t available
    }

    bookSummary = document.getElementById(‘bookSummary’);

    /* these event handlers ensure that if the mouse if over the book sumamry but not the link
           it does not disappear */
    bookSummary.onmouseover = function(e){  bookSummary.style.display = ‘block’;};
    bookSummary.onmouseout = function(e){   bookSummary.style.display = ‘none’; };

    /* attempt to load the XSL stylesheet */
    bookInfoXsl = loadXslStylesheet(‘xml/single_book_html.xsl’);

    var bookLinks = document.getElementById(‘bookList’).getElementsByTagName(‘a’);

    /* add event handlers to links inside the book list – the summary will be displayed while the mouse
       hovers over the link */
    for(var x = 0; x < bookLinks.length; x++)
    {   
        var oCurrent = bookLinks[x];

        oCurrent.onmouseover = displayBookSummary;
        oCurrent.onmouseout = hideBookSummary;

    }
}

The displayBookSummary function is executed when the user moves the mouse pointer over any of the book title links. On execution it makes an HTTP request to the single_book.php script. The isbn number is extracted from the href attribute of the link and appended to the query sting along with the xslt variable that indicates whether or not the browser supports XSLT.

Javascript:
function displayBookSummary(event)
{
    if (! (xmlHTTP)) { // do not continue if XMLHTTPRequest is not available
        return;
    }

    if (! event) { // In Internet Explorer the event object is not passed by default
        event = window.event;
        var target = event.srcElement;
    } else {
        var target = event.target;
    }

    /* find the co-ordinates of the mouse – this is where we will display the book sumamry DIV */
    var x = event.clientX;
    var y = event.clientY;

    bookSummary.style.top = y + ‘px’;
    bookSummary.style.left = x + ‘px’;

    /* extract the book ISBN */
    var href = target.getAttribute(‘href’);
    var isbn = encodeURIComponent(href.substring(href.indexOf(‘isbn=’) + 5, href.length));

    /* tell the receiving script whether we can do the transformation ourselves */
    xslt = bookInfoXsl?1:0;
   
    /* abort any past requests and send the new request */   
    xmlHTTP.abort();
    xmlHTTP.open(‘get’, ‘single_book.php?xslt=’ + xslt + ‘&’ + ‘isbn=’ + isbn, true);
    xmlHTTP.onreadystatechange = displayBookSummaryCallback;
   
    xmlHTTP.send(null);
}

The displayBookSummary callback is executed when a response has been received from the XMLHTTPRequest object. The type of response received is dependant on whether or not the browser supports xslt. If XSLT is supported, the response is an XML fragment, this is then parsed, transformed and the result of the transformation appended to the bookSummary div.

Javascript:
function displayBookSummaryCallback()
{
    if (xmlHTTP.readyState != 4) { // not fully loaded
        return;
    }

    if (! xmlHTTP.responseText) { // this happens if abort is used in Firefox and Netscape
        return;
    }

    if (bookInfoXsl) { // XSLT is avaiable so the reponse should be an XML response
        /* load the response into a DOMDocument */
        var oXml = loadXmlFromString(xmlHTTP.responseText);

        if (! parseXmlDom(oXml)) {
            /* xml cannot be parsed */
            return;
        }

        /* transform the XML */
        var transformed = transformXml(oXml, bookInfoXsl);

        if ((typeof transformed) == “object”) { // w3c compliant browsers
            /* append the new DOM to the HTMl document */
            if (! bookSummary.firstChild) {
                bookSummary.appendChild(transformed.documentElement);   
            } else {
                bookSummary.replaceChild(transformed.documentElement, bookSummary.firstChild);
            }
        } else { // Internet Explorer
            bookSummary.innerHTML = transformed;
        }
    } else { // XSLT is not supported, therefore we have an HTML response which we just insert into the book summary DIV
        bookSummary.innerHTML = xmlHTTP.responseText;
    }

    bookSummary.style.display = ‘block’;       
}

The hideBookSummary function is executed when the mouse pointer moves off the book link and hides the book summary div:

Javascript:
function hideBookSummary()
{
    bookSummary.style.display = ‘none’;
}

Conclusion
In this article we have demonstrated how XSLT can be used in conjunction with PHP and Javascript to create an Ajax application. We have, however, only touched the tip of the Ajax iceberg. It is easy to become overwhelmed by the seemingly countless number of possible applications which come from marrying these technologies together. When developing Ajax applications in particular, take the following points into consideration:

    * Ensure your application is still fully functional in the worst case scenario and still accessible to all its users.
    * Use Ajax technologies only where required (i.e: to help save bandwidth, enhance the users experience) and not just for the sake of using it.
    * Test…test and test all Javascript code thoroughly in all mainstream web browsers and ensure that if a script fails, it fails gracefully without breaking the user interface.

1
|
2
|
3
|
4