• AJAX 07.05.2009 1 Comment

    Ajax stands for Asynchronous JavaScript and XML and is a set of techniques for creating highly interactive web sites and web applications. The desired result is to update the website pages, using data fetched from the Internet, without refreshing the web page in the users’ browser.

    The communication between the server and the web browser is done using XMLHttpRequest objects manipulated through a JavaScript function. The goal is to create a JavaScript function which, based on users action, will change the data displayed on users’ browser following some well defined rules.

    Creating the XMLHttpRequest Object

    This object is built in the browser and, depending on what browser you are running the code, it is accessed in different way. Netscape Navigator (version 7.0 and later), Apple Safari (version 1.2 and later), and Firefox let you create XMLHttpRequest objects with code like this:

    XMLHttpRequestObject = new XMLHttpRequest();

    In case that you are dealing with Internet Explorer the object can be created using code like this:

    XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);

    The object is accessed in those browsers through the browser window object, and checking it’s presence means that you are dealing with certain web browsers.

    For Netscape, Safari and Firefox the code will be as follows:

    if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
    }

    For Internet Explorer we’ll have:

    if (window.ActiveXObject) {
    XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);
    }

    Although the XMLHttpRequest object supported in different browsers differs we can use the same basic properties and methods of this object.
    So, the code used to create XMLHttpRequest object for different web browsers will be:

    var XMLHttpRequestObject = false;
    if (window.XMLHttpRequest) {
    XMLHttpRequestObject = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
    XMLHttpRequestObject = new ActiveXObject(“Microsoft.XMLHTTP”);
    }

    Opening the XMLHttpRequest Object

    It’s time to open the XMLHttpRequest object. Here’s how you use the XMLHttpRequest object’s open method in general (items in square brackets are optional, and items in italics are placeholders that you fill in yourself):

    open(“method”, “URL”[, asyncFlag[, "userName"[, "password"]]])

    Where method is the HTTP method used to open the connection, such as GET, POST, PUT, HEAD, or PROPFIND, URL is the requested URL, asyncFlag is a boolean value which indicates if the call is asynchronous (default value true), userName is the user name of your account and the password is the password of your account.

    The method used to open the connection will be for this case the GET method. After the connection is open, we can start to open the XMLHttpRequest object and to configure it in preparation for connecting to the server and downloading data.

    This piece of JavaScript code will prepare the object:

    XMLHttpRequestObject.open(“GET”, dataSource);

    Note that using the open method like this configures the XMLHttpRequest object and it does not connect, or open any connection to the server.

    The onreadystatechange property contains the name of the event handler that should be called when the value of the readyState property changes (read/write). Using this property we can call an anonymous function that will open the connection to the server and to download the necessary data. Inside the anonymous function, we need to check on the data that’s been downloaded: is the download complete and are we ready to use that data? We can determine that with two properties of the XMLHttpRequest object: readyState and status.

    The value of 4 for the readyState property means that the download is complete and the value of 200 for the status property means that is completed OK. Checking these values with an if statement which returns the true value means that we can go further with our request.

    The JavaScript code will be as follows:

    XMLHttpRequestObject.onreadystatechange = function(){
    if (XMLHttpRequestObject.readyState == 4 && XMLHttpRequestObject.status == 200)
    {//here we’ll place the necessary code to fetch the data}
    }

    To recover the downloaded text we can use the XMLHttpRequest object’s responseText property. That property is where the XMLHttpRequest object stores downloaded plain text. If we use XML data the object property will be responseXML (we’ll use it a little bit later) which is common for all major browsers.

    The JavaScript code will be:

    documentGetElementById(divID).innerHTML = XMLHttpRequestObject.responseText;

    where the element with the divID id will be the placeholder for our requested data.

    Connecting to the server

    In this example, we’re using the GET method, so we call the XMLHttpRequest object’s send method, passing it a value of null, which is JavaScript’s placeholder for a value of nothing.

    The JavaScript code will be:

    XMLHttpRequestObject.send(null);

    At this point we have created the XMLHttpRequest object, we opened it and we have created the connection to the server. From now we can make useful XML to store data and to have the source for our Ajax requests.

    Using Ajax with XML

    In the Firefox/Mozilla brand of browsers, we have to specify that we’re going to be downloading XML data, not plain text. To do that, we have to set the MIME type of the download to text/xml. We can achieve this using this line of code:

    XMLHttpRequestObject.overrideMimeType(“text/xml”);

    Another difference will be that we will use the XMLHttpRequest object’s responseXML property, which holds a JavaScript XML document object:

    var xmlDocument = XMLHttpRequestObject.responseXML;

    Let’s say that we want to download data regarding streets name from a certain city area (Bucharest in my case). For this we have to create a variable streetsName which will hold the data parsed from the XML file ruled by the Tag Name read-only property:

    streetsName = xmlDocument.getElementsByTagName(“streetName”);

    After this we need to create the format for the placeholder of the data. In this case I will create a list of elements <span> displayed as block. Maybe it will be better to generate elements of an unordered list, but the problem is that, using the following sequence of JavaScript code, the HTML output will be a type of <ul></ul><li>...</li>, which means that we have an empty ul element and some orphans li elements, and this could lead to problems on CSS formatting.

    The necessary code will be:

    var xmlDocument = XMLHttpRequestObject.responseXML;
    streetsName = xmlDocument.getElementsByTagName("streetName");
    obj.innerHTML = "Here are the fetched streets name:";
    for (loopindex = 0; loopIndex < streetsName.length; loopIndex++)
    {
    obj.innerHTML += "<span>" + streetsName[loopIndex].firstChild.data + "</span>";
    }

    where obj = document.getElementById(divID); which is the container of our data.

    The structure of the XML file will be simple:

    <?xml version="1.0" ?>
    <streetsName>
    <streetName>Calea Victoriei</streetName>
    <streetName>Regina Elisabeta</streetName>
    <streetName>Lascar Catargiu</streetName>
    <streetName>Iuliu Maniu</streetName>
    <streetName>Cotroceni</streetName>
    <streetName>Ion Ionescu de la Brad</streetName>
    <streetName>Calea Dorobantilor</streetName>
    </streetsName>

    From now the only thing we need to create is a form element which, based on user click action, will execute the function that will fetch the desired data from server.

    The entire code (HTML and JavaScript) can be downloaded from the following link, a simple example on how data is fetched form server using Ajax and XML.

    • Share/Bookmark
  • Web Design 23.04.2009 No Comments

    Almost every website on the Internet has a navigational menu constructed horizontally or vertically. Simple or more complex with drop-down sub-items, it’s presence is necessary to lead the visitor(s) to the desired information inside the website. There are quite enough methods to build navigational menus, and I’ll give my opinion on few of them.

    Use of table for building the menu

    HTML element <table> has the advantage of being well implemented in all major browsers, so no displaying issues when it's content is deployed. The idea is simple, to create only one table row, with one data cell for each item menu. Using the CSS style attributes the menu will get the appearance it needs.

    The HTML code is a follows:

    <table>
    <tr>
    <td><a href="">Item 1</a></td>
    <td><a href="">Second Item</a></td>
    <td><a href="">Third One</a></td>
    <td><a href="">Item 4</a></td>
    <td><a href="">Fifth in the row</a></td>
    <td><a href="">LastItem</a></td>
    </tr>
    </table>

    We can add some style to the table appearance and be sure you set the border-collapse property to collapse so no spaces are between data cells and borders are collapsed into a single border when possible. A detailed presentation of this style property can be found at W3 Schools CSS border-collapse property page.

    Using unordered list items to create navigational menu

    Using the items of an unordered list to create the navigational menu is, maybe, the most used technique.
    Comparing with the previous method it requires almost the same number of lines for CSS styles, and the effect is similar. To display items horizontally you can use the display:inline style property, so the elements of the unordered list are displayed in the same line, like a row of elements. Setting the item elements to be displayed as inline elements, make them "unmovable" on y axis, which means that using padding or margin property to arrange the way they are displayed has no effect. But giving some values to height or/and line-height properties this issue can be easily handled.

    Another way to display the elements on the same row is to float the list-items of the unordered list to left. This method tends to be more desired then the previous and the result is much similar with the menu created using table elements.

    Following the next link you can see a few examples of horizontal navigational menus using the methods described above. I left the style properties unaltered so you can see on different web browser how the menus are displayed.

    Adding some graphic style to the menu

    Using background images for the elements of the menu creates a nice and more desired visual effect. Even if you use a repeated background image or you create a little more sophisticated rounded corner button for your menu you definitely add a bit of color to the (maybe) flat HTML page. In the next line I'll give some hints on how to create these rounded corner buttons.

    Creating rounded corner buttons for the navigational menu

    The simplest approach may be to create a button with a given width and height and use it as a background image for each item of the menu. This will work fine in situations when the text of the menu items has the same length or the differences are insignificant.

    Split image for the background

    Another method is to split the images in two parts and build the menu items using besides the anchor element an additional span element. The code for the menu will look like:

    <ul id="split">
    <li><a href=""><span>Item 1</span></a></li>
    <li><a href=""><span>Second Item</span></a></li>
    <li><a href=""><span>Third One</span></a></li>
    <li><a href=""><span>Item 4</span></a></li>
    <li><a href=""><span>Fifth in the row</span></a></li>
    <li><a href=""><span>Last Item</span></a></li>
    </ul>

    The idea is to set the display:block property for anchor and span elements, and using the padding values the items are displayed correctly with the desired effect, which means that the width of each item will follow the length of the text. Note that the image on the right side in this case should have a width which is greater than the length of the text with the values for the left and right padding added; otherwise the background image will be broken.

    Using two span elements for the right and left margins

    In this case the image is split in three parts, one for the right margin, second for the left margin and the third one for the middle. This last one image may have a width as small as possible, because it can be repeated on x axis. The HTML code of the menu will be as follows:

    <ul id="split3">
    <li><a href=""><span><span>Item 1</span></span></a></li>
    <li><a href=""><span><span>Second Item</span></span></a></li>
    <li><a href=""><span><span>Third One</span></span></a></li>
    <li><a href=""><span><span>Item 4</span></span></a></li>
    <li><a href=""><span><span>Fifth in the row</span></span></a></li>
    <li><a href=""><span><span>Last Item</span></span></a></li>
    </ul>

    The good part for this method is that the padding values can be set just for the last span element, and this is enough to reach the desired effect. Even we have more CSS and HTML code for this last method I think is more simple than the previous one, because you don't have to tweak padding values to have all elements aligned.

    Please follow this link to see (and download files) examples of building navigational menus using the method I've described.

    The resulted page was tested on Firefox v3.0.9., Internet Explorer v6.0, v7.0 and v8.1, Opera v9.63, Safari v3.2.1 and Google Chrome.

    • Share/Bookmark
  • When a visitor reaches a web page for the first time, and he or she has to watch how the images are fulfilling the placeholders floating the text around or not, could be turned into a “leave and forget this” experience. A neat aspect of your web page presentation can make your visitors to never come back. For many web pages a good tweak could be the option to preload the images using JavaScript and display them with the rest of the page content in one “shot” on visitor’s screen.

    Mootools JavaScript Framework

    Mootools JavaScript framework is designed for the intermediate to advanced JavaScript developer and allows you to write powerful, flexible, and cross-browser code with its elegant, well documented, and coherent API. I use this framework and so far I’m pleased with the way things are going. If you want to know more about please read the Mootools documentation.
    In the next lines I will present how to use one of this framework plug-in, Assets Method:images to preload images and the content after the operation is completed. It’s easy to understand and to reproduce.

    Assets Method:images

    What does this plug-in do? Preloads an array of images (as strings) and returns an array of img elements.. The syntax is very simple:

    var myImages = new Asset.images(source[, options]);

    where sources – is an array or a string, of the paths of the image files and options – (object, optional) could be a function which is executed on onProgress or onComplete events for this plug-in.

    Optimizing web page appearance

    The purpose of using this plug-in is to have our page content displayed after the images within are loaded. Our page will have some text and let’s say 10 images with the size varying from 60Kb to 100Kb to be displayed.
    First, we need to hide the content when web page is loaded. For doing this we have two options: one to set the display style property to none, and the second to set the visibility style property to hidden. The difference between this two options is that display:none means that the placeholder for the element is not present at all, and for visibility:hidden the placeholder exists on page but is not visible.

    With Mootools JavaScript Framework we can set the desired style property using:

    $('myContent').setStyle('display', 'none');

     or

    $('myContent').setStyle('visibility', 'hidden');

    The problem is that until the JavaScript library is loaded there is a slightly chance for our content to be shown until it has the style property set. So, it will be better to use a very trivial JavaScript function to set the style property which will be declared on <head> area, and call it inside the document body.

    Our function will be as follows:


    function hideContent{
    documentGetElementById('myContent').style.display = "none'
    }

     or

    function hideContent{
    documentGetElementById('myContent').style.visibility = "hidden';
    }

    It is important where the function should be fired up. So I place the JavaScript code just after the opening <div> tag with the id "myContent". Place the code before, and you will have a "null" object.
    At this point we have our content hidden. After this we can initiate the images preloading process. The options for the Asset Mootools Plug-in could be one of two functions which can be executed on onComplete or onProgress events. On onProgress we have a function which will create HTML elements so during the preloading process a "Loading content, please be patient ..." text string will be displayed, and on onComplete event a function will reveal the content of our page.

    Creating HTML elements

    One of the methods used to create HTML elements with Mootools is the Element constructor which creates a new element of the type passed in. I chose to create two elements, one of division type and the second of image type, which will be injected after the text generated to be displayed. The image, which will be an animated GIF, is added just as a bit of flavor for our page presentation. The code will be executed based on MooTools' custom domready event.
    The elements will be created inside a division container. We have two options to place this container, before the main content container or after. If we place it at the end of page content, the string text will appear without the image, for a certain period of time, and this is an undesired effect, so it will be better to place it just after the opening <body> tag.

    The JavaScript code will be as follows:

    var myImages = new Asset.images(['images/img1.png', 'images/img2.png', 'images/img3.png', 'images/img4.png','images/img5.png', 'images/img6.png', 'images/img7.png', 'images/img8.png', 'images/img9.png', 'images/img10.png'], {
      onProgress: function(){
        var myDisplayTextContainer = new Element('div', {id: 'loadingText'}); //create text container
        var myPreloadingImg = new Element('img', {id: 'loadingImg'}); //create image
        myPreloadingImg.setProperty('src', 'images/preloading.gif'); //set the image source
        $('loading').grab(myDisplayTextContainer); //grabs text string container
        myPreloadingImg.inject(myDisplayTextContainer, 'after'); //inject image after text string container
        $('loadingText').set('text', 'Loading content, please be patient ...'); //create text string
      },
      onComplete: function(){
        $('loading').setStyle('display' , 'none'); //or use $('loading').setStyle('visibility', 'hidden')
        (function(){
    $('myContent').setStyle('display', ''); //or use $('myContent').setStyle('visibility', 'visible')
        }).delay(250);
      }
    })

    I use a delay time before the content is displayed, because the animated GIF creates an ugly visual effect just before is disappearing.
    Anyway, being a stochastic process, a different behavior is expected for each web browser, even the desired result may be as expected.
    Please follow the link, to see how content is displayed using the Mootools Asset Method:images to preload images.

    Limitations and issues using this method

    There could be a chance when using this method with display style property used to hide/show content, that the images will not be displayed on Internet Explorer 6. Using visibility style property instead to target this browser engine version will fix this issue. On the other hand, if the visibility property is used on Internet Explorer 7, there could be a chance that the images and some text will not appear on page, or they are shown after some time.
    Another issue is that, is more than one instance of the image injected after the text string container. This could simply be "cosmeticized" setting the overflow style property for the image container to hidden and setting the height of the container to a value that fits the text string and the preloading image heights.

    Preloading images using JavaScript

    If your are looking for some JavaScript functions to preload images, independent of any framework, here you can find a good example for a JavaScript Image Preloader.

    I hope this resource is useful.

    • Share/Bookmark

Search

Polls

New blog template! What do you think?

View Results

Loading ... Loading ...

Calendar

September 2010
M T W T F S S
« Aug    
 12345
6789101112
13141516171819
20212223242526
27282930  
boyish-swiss