Free, tested & ready to use examples!
AnyExample.com
 
Web anyexample.com
 

AJAX example: get page title

abstract 
AJAX (Asynchronous JavaScript and XML) is a JavaScript technique which involves special object XMLHttpRequest and sending/receive asynchronous (without full page reload) requests to server. This is an example of simple AJAX application which allows user to enter web-page url and display title of that page right after user stops typing.
compatible 
  • Any browser with XMLHttpRequest object support

There are three notable constituents in the example.

First, is a creation of XmlHTTPRequest object. Different browsers uses different code for object creation. For Internet Explorer it is necessary to use ActiveX (with different ActiveX control names for different versions). Other browsers, like Opera, Safari and Firefox has this object just build in JavaScript engine.

Second is using XmlHTTPRequest for sending and processing request. Function getInfo() gets url from text field checks whether it has opening slash, checks whether this request has already processed and if everything is fine starts GET request to download web-page.

Function receiveInfo() does error processing (page was not found, error 404 or some other errors), searches received text for <title>(title)</title> and displays result. We do not use XML functions here, because returned web-page may be invalid XML document(old HTML).

There is also function OnUrlKey() which sends request when user stops typing (it fact, it sets timer for every key pressed, but each time user press new key it 'disables' code in series of previous timers).

source code: HTML / JavaScript
 

<html>
    <head><title>Ajax Title fetcher</title>
    <script type="text/javascript">
    // creating XmlHttpRequest object
    // double check for IE/ActiveX and then try to use

    // native object (Safari, Firefox)
    var ajax_transport = false;
    try {
        ajax_transport = new ActiveXObject("Msxml2.XMLHTTP");
    } catch (e) {

        try {
            ajax_transport = new ActiveXObject("Microsoft.XMLHTTP");
        } catch (E) {

            if (typeof XMLHttpRequest != 'undefined') {
                ajax_transport = new XMLHttpRequest();
            }
        }

    }
    // done creating
    // ajax_transport is XmlHttpRequest object or boolean false
 
 
    // this function is called when user fetches data
    var prev_page = '';
    function getInfo()

    {
        // If XmlHttpRequest is not supported - there is no AJAX
        if (!ajax_transport) {
            alert('Your browser does not support AJAX/XmlHTTPRequest');
            return;
        }

 
        // We have to tell to some browsers (Opera, Firefox, etc.)
        // that we may receive  non-XML document
        if (ajax_transport.overrideMimeType)
            ajax_transport.overrideMimeType('text/html');

 
 
 
        // getting url value and adding first / if there is none
        var url = document.getElementById('url').value;
        if (url.charAt(0) != '/')

            url = '/' + url;
        // showing 'loading' label
        document.getElementById('load').style.display = 'block';

 
        // sending request
        ajax_transport.open("GET", url, true);
        ajax_transport.onreadystatechange=receiveInfo;
        ajax_transport.send(null)
        prev_page = url;
    }

 
    // this function is called, when data requested at function getInfo() (above)
    // is ready for processing
    function receiveInfo()
    {
        if (ajax_transport.readyState != 4)

            return;
 
        // hide 'loading' label
        document.getElementById('load').style.display = 'none';

 
        // result element
        var pageinfo = document.getElementById('pageinfo');
 
        // Firefox may throw exception while getting XmlHttpRequest status
        try { real_status = ajax_transport.status; }

        catch (e) { return; }
 
        // status != 200 means that page was not downloaded
        // error 404 happened or something like this
        if (real_status != 200)

        {
            var emsg  = '<p><b>Error ' + real_status + '</b> while ';
            emsg += 'trying to get document</p>';
            pageinfo.innerHTML = emsg;
            return;
        }

 
        // regexp which parses text for value between <title> .. </title> tags
        var re_title = new RegExp("<title>[\n\r\s]*(.*)[\n\r\s]*</title>", "gmi");
        // page text

        var content = ajax_transport.responseText;
        var title = re_title.exec(content);
 
        var emsg = ''; // output text

 
        if (title == null)  // regexp didn't match
        {
            emsg = '<p>Page does exist, but there is ';
            emsg += '<h1>no title-tag found</h1></p>';
        }

        else
            emsg = '<p>Title of the page is <h1>'+ title[1] + '</h1></p>';

 
        pageinfo.innerHTML = emsg;
    }
 
    var knum=0;
 
    function OnUrlKey(ev)

    {
        if (!ev) var ev = window.event;
        knum++;
        if ((ev.keyCode==10)||(ev.keyCode==13))

            getInfo();
        else
            window.setTimeout('if (' + knum + '==knum) getInfo();', 700);
    }
    </script>

    <style type="text/css">
    body { font-family: Arial, sans-serif; }
 
    div#load {
    position: absolute; right: 0; top: 0;
    padding: 3px; width: 40pt; font-size: 9pt; background-color: #A00; color: white;
    display: none;
    }

 
    small { font-size: 7pt; }
    </style>
    </head>
 
    <body>
        <div id="load">loading...</div>

        <p>
            Enter page URL:<br />
            <script type="text/javascript">
                document.write('<input type="text" size="'+(location.host.length+6)+'"');
                document.write(' value="http://' + location.host + '" readonly="readonly" />');
            </script><input type="text" id="url" size="40" onkeypress="OnUrlKey(event);" />

            <a href="ajax://get-info" onClick="getInfo(); return false;"
            style="color: blue;">[get page title]</a>
            <small>you can't use URL outside your domain</small>

        </p>
        <div id="pageinfo">
        </div>
    </body>
</html>

Try example online.

warning 
  • Note, that XMLHttpRequest for security reasons can send requests only for URLs within same(with AJAX web-application) domain.
tested 
  • Internet Explorer 6.0
  • Firefox 1.5
  • Firefox 2.0RC2
  • Opera 9
 


 
© AnyExample 2010-2013
License | Privacy | Contact