Showing posts with label ajax tutorial. Show all posts
Showing posts with label ajax tutorial. Show all posts
Friday, January 15, 2010

10 Super jQuery and Ajax Scripts for Web Developers

In web development scripts like jQuery and Ajax becomes very handy for web developers. If you are a learner or a expert these scripts is really helpful of all.

In this post I have shared free jQuery and Ajax scripts to help our upcoming web developers. In this list includes - A Drop-Down Menu Plugin for jQuery, Rotating jQuery Tabs, Sliding Login Panel with jQuery, AJAX Loading Panel, Mysql Ajax Table Editor, jQuery youtube playlist plugin etc.

Nice & Clean Sliding Login Panel built with jQuery

Please note the Login and Register forms in this demo will not work "out of the box" without a user login system pre-installed on your site (e.g. PHP/MySQL user login system)! However, most of the CMS such as Joomla, Drupal, Wordpress, etc have a login system integrated in their platform. So if you are using one, read their documentation to see how you could implement this script into your CMS.

Nice & Clean Sliding Login Panel built with jQuery

Download | Demo

UPLOADIFY

Uploadify is a jQuery plugin that allows the easy integration of a multiple (or single) file uploads on your website. It requires Flash and any backend development language. An array of options allow for full customization for advanced users, but basic implementation is so easy that even coding novices can do it.

Uploadify is available under the GPL and MIT licenses. This allows Uploadify to be used in a number of applications and commercial products.

UPLOADIFY

Download | Demo

Mysql Ajax Table Editor

Mysql Ajax Table Editor is a php script that will allow you to create web pages to edit mysql tables in a matter of minutes. Similar to phpMyEdit but way better. Some of MATE's features are advanced search, order by columns, edit multiple rows, language support and join other tables.

Mysql Ajax Table Editor

Download | Demo

jQuery youtube playlist plugin

This nice plugin allows you to turn a list of YouTube links into a playlist. This would allow the you to manage your videos on YouTube and simply insert links to the videos on your site. With javascript enabled a nice playlist is created, whilst without javasript the user gets a regular list of links to youtube pages.

jQuery youtube playlist plugin

Download | Demo

nmcDropDown: A Drop-Down Menu Plugin for jQuery

A quick jQuery plugin for creating drop-down menus. Very nice and easy to use.

nmcDropDown: A Drop-Down Menu Plugin for jQuery

Download | Demo

Datepicker and Calendar Eightysix

Calendar Eightysix is an unobtrusive developer friendly calendar and datepicker, offering a better user experience for date related functionalities. The successor of the popular Vista-like Ajax Calendar! Key features:

:: Quick navigation by jumping back and forth between months, years and decades without drop-down boxes
:: Highly and easily customizable
:: Packed with three themes
:: Lightweight (9.5 kB compressed)
:: Purely javascript; AJAX-less and no PHP needed

Datepicker and Calendar Eightysix

Download | Demo

Rotating jQuery Tabs

Tabs are generally used to break content into multiple sections that can be swapped to save space, much like an accordion.

By default a tab widget will swap between tabbed sections onClick, but the events can be changed to onHover through an option. Tab content can be loaded via Ajax by setting an href on a tab.

Rotating jQuery Tabs

Download | Demo

jQuery Highlighter - Easy to use jQuery Plugin

Highlighter easy for customization. Keyboard enabled.

* Keyboard Navigation (arrowkeys + ESC)
* Highly Customizable
* Autoplay
* Todo Accessible
* Todo Cross Browser Compatibility

jQuery Highlighter - Easy to use jQuery Plugin

Download | Demo

Fancy Sliding Tab Menu

The Fancy Sliding Tab Menu is back and better than ever in Version 2 and this time an idle state listener is included to bring all the tabs back to their normal state after a desired amount of time without mouse movement on the window.

The menu is developed in script.aculo.us and as mentioned above has some extra features as requested in comments after the last version of the Fancy Sliding Tab Menu.

Fancy Sliding Tab Menu

Download | Demo

AJAX Loading Panel

Enhance your site's look and feel during AJAX requests with the fully customizable state-of-the art Web 2.0 AJAX Loading Panel without writing a single line of code!

All you have to do is to follow a few easy steps, modify a couple of properties and add the show and hide methods to your XMLHttpRequest function.

AJAX Loading Panel

Download | Demo

Do you any opinion, please leave a comment.

Wednesday, July 15, 2009

10 Essential Ajax Scripts for Web Developers

Ajax Script is one of the most widely used languages across the globe for web development. It is simple, yet very powerful, and the number of ways that it can be used are almost limitless.

In this post I'm going to share ten essential Ajax scripts to help web developers with direct download link. The following list includes Progress Bar, Ajax grid, Ajax Menus, Ajax Event Calander, Ajax Tag Clouds, Ajax Image Transition etc.

1. Simple Javascript Progress Bar with CSS

WebAppers have created a simple Javascript based Percentage Bar / Progress Bar which is inspired by Bare Naked App. Bare Naked App taught us how to display Percentage Bar with 2 images only by using CSS.

Download Now | Click Here for Demo

2. Sigma grid-Ajax grid for php java & .net

Written in pure javascript, Sigma Grid is an Ajax data grid for displaying and inline editing data in a scrollable and sortable table. IE 6.0+ \ FireFox 2.0+ \ Safari 3.0+ \ Opera9.0+ supported. Pure javascript codes, Seamless Integration with any server side solution, such as j2ee, .net, PHP, perl. Inline editing, keyboard data navigation, nested multiline headers, sortable and frozen columns. Slice rendering and built-in paginal output allow you to manipulate huge datasets on the fly.

Download Now | Click Here for Demo

3. Instant.js

If you're looking to add some interesting backgrounds, rotations and other effects to images, Instant.js might be just what you're looking for. The JavaScript degrades gracefully, so browsers who don't have JavaScript enabled won't notice a difference.

Download Now | Click Here for Demo

4. Phatfusion image menu

Phatfusion image menu is horizontal menu, reveals more of the image as you rollover it.

Main features:

  • 2 optional onClick events - open & close

  • href passed to onClick events

  • stays open when clicked

  • closes when clicked

  • select item to pre-open


  • Download Now | Click Here for Demo

    5. dhtmlxScheduler :: Ajax Event Calendar

    dhtmlxScheduler is a web-based event calendar which provides simple in-browser scheduling solution. With smooth Ajax-enabled interface dhtmlxScheduler allows users to add, modify or delete events without refreshing the web page. dhtmlxScheduler is very lightweight (about 19KB gzipped), cross-browser and highly customizable.

    Download Now | Click Here for Demo

    6. DrasticCloud

    DrasticCloud is a configurable tag cloud. The example on the left presents the mountains in the grid ordered and scaled by height. Mountain names in green have been climbed. Change the settings in the cloud menu to change the cloud.

    Download Now | Click Here for Demo

    7. AJAX Rating Stars

    Based on the prototype.js javascript framework, these rating stars are really easy to implement on your website. They feature form field binding, javascript callback function support, and XMLHttpRequest value sending (AJAX).

    Download Now | Click Here for Demo

    8. Ajax Image Transition Manager

    The image transition manager is a javascript library based on scriptaculous and prototype. It supports several image transitions, such as fading, appearing, sliding, growing and shrinking. Because it uses the unobtrusive javascript technique, no inline javascript is needed and hyperlinks still function when javascript is disabled.

    Download Now | Click Here for Demo

    9. Sigma Visual Ajax builder

    Sigma visual builder is web based tool for AJAX RIA application GUI rapid design and involved scripts programming.WYSIWYG GUI builder. Do everything by drag & drop. More than 40 common components, including Tabs, Dialog, TreeGrid, TimeLine and many other web GUI components. Rich client-side API, works with any backend or static HTML pages. Wide cross-browser compatibility.

    Download Now | Click Here for Demo

    10. Smooth Counter

    It's been a while, but a new piece of Javascript is here to add some dynamics to your web-page. SmoothCounter is a script that enables you to count between 2 numbers (with a given precision) in a given period of time.

    Download Now | Click Here for Demo

    Do you have any opinion, leave a comment.

    Sunday, October 26, 2008

    Quick Calendar Using AJAX and PHP

    Online calendars are often used in many web applications. Though popular, the logic behind creating a calendar can be scary especially for those who are new to programming. There are many web calendars in the market but some of them are quite complicated. If we are not able to understand the code, it becomes harder for us to customise the calendar to fit into our existing application. As such, we need to create a calendar that can plug itself into any system seamlessly without problems. Whether we are using Wordpress, Mambo/Joomla or Drupal, we should only need to insert one line into our code for the calendar to work. ie something like this:

    require_once('quick_calendar.php');
    ?>


    If you are already bored at this point or not interested to know how to create a web calendar, feel free to see a live demo of the simple calendar here. The installation procedures is in the source code.

    Other than configuring the database access for the calendar, I do not want to change other things. With AJAX, I could even make the page static as I navigate between different months in the calendar. In this tutorial, I would like to share with you a simple calendar I created that fufills the objectives discussed above. The tutorial assumes that you have basic knowledge of PHP and SQL but don't worry, the actual code is minimal and you should be able to customise it easily by reading at the comments. I used PHP 4 so that it is compatible with most servers. You should also be able to re-create the calendar easily in other programming languages using the same logic.

    The First Step Problem Identification:

    Perhaps the hardest part in creating a calendar is to come up with a good solution to display the days of the month in the correct column, ie Monday, Tuesday..etc.



    Let us take April 2006 for example. There are 30 days and 6 rows in the calendar. If we are given a day in the month, say 15, we have to know that it falls on a saturday and is in the third row (third week). We cannot take for granted that the first day is always the first cell in the table (top left cell). Sometimes, we get 4 or 5 weeks in a month. Only if we know how many days are there in a certain month and which day the first of the month falls in only can we construct the calender as shown above.

    Getting Crucial information From The PHP Date function

    PHP provides a date() function that gives us alot of useful information about the days and months of the year. To built the calendar for any month, We need 2 important pieces of information from the Date function, ie the "number of days in the month" and a "numeric representation of the first day of the month".

    I can get today's date easily from the following code:

    // get year, eg 2006
    $year = date('Y');
    // get month, eg 04
    $month = date('n');
    // get day, eg 3
    $day = date('j');


    To get the number of days in this month, I will use the both the date and mktime function like so:

    // get number of days in month, eg 28
    $daysInMonth = date("t",mktime(0,0,0,$month,1,$year));


    The numeric representation of the day of the week ranges from 0 to 6. 0 is sunday and 6 is saturday. Again, to get the numeric first day of this month, the function mktime comes in handy.

    // get first day of the month, eg 4
    $firstDay = date("w", mktime(0,0,0,$month,1,$year));


    The Monthly Calendar As A 2-D Array

    If we look at the calendar again for April 2006, we will see that it is actually a table(grid) filled with values starting from 1 to x (no of days in the month). The first day of the month is a variable though... It can occur in any day of the week. In the table, imagine each cell as having coordinates (x,y), starting from the top left cell as (0,0) and the bottom right cell as (5,6). In the month of April, the first day of the month is stored in coordinate (0,6). So, the plan now is to store the days of the month in a 2-D Array.

    Firstly, we want to know the number of cells needed.

    // calculate total spaces needed in array
    $tempDays = $firstDay + $daysInMonth;


    Then we want to know the number of rows needed.

    // calculate total rows needed
    $weeksInMonth = ceil($tempDays/7);


    Populating The 2-D Array

    Knowing the number of rows and columns in the 2-D array, we can now fill the arrays with values using 2 for-loops. The first cell will start with a value of 1 and the subsequent cells will have their values increased by 1 till it reaches the end of the array.

    for($j=0;$j<$weeksInMonth;$j++) {
    for($i=0;$i<7;$i++) {
    $counter++;
    $week[$j][$i] = $counter;
    }
    }
    ?>


    For the month of April, the temporary array should be something like this:



    The Magic Offset

    As you can see, the array above is not correct. The first day of April, ie value 1 should be in (0,6) instead of (0,0). Remeber the variable $firstDay? It is the numeric representation of the first day of month which happens to be 6 in April 2006. If we subtract $firstDay from all the values in the array, we will get the array as follows:



    You should now be able to guess what we are going to do next. Looking at the array above, you see that we already got the values we want but we also have some unwanted values. Any number less than 1 or more than $daysInMonth (number of days in a month) should be ignored.

    function fillArray() {
    // create a 2-d array
    for($j=0;$j<$this->weeksInMonth;$j++) {
    for($i=0;$i<7;$i++) {
    $counter++;
    $this->week[$j][$i] = $counter;
    // offset the days
    $this->week[$j][$i] -= $this->firstDay;
    if (($this->week[$j][$i] < 1) || ($this->week[$j][$i] > $this->daysInMonth)) {
    $this->week[$j][$i] = "";
    }
    }
    }
    }
    ?>


    This is the core function in the entire calendar generation algorithm.

    Displaying The Calendar

    Getting the values right in the 2-D array, we are now ready to display them. Now, we will create a table and start looping again using the foreach function.


    <table width="400" border="1" cellpadding="2" cellspacing="2">
    <tr>
    <th colspan='7'><?= date('M', mktime(0,0,0,$month,1,$year)).' '.$year; ?></th>
    </tr>
    <tr>
    <th>Sun</th>
    <th>Mon</th>
    <th>Tue</th>
    <th>Wed</th>
    <th>Thur</th>
    <th>Fri</th>
    <th>Sat</th>
    </tr>

    <?php
    foreach ($week as $key => $val) {
    echo "<tr>";
    for ($i=0;$i<7;$i++) {
    echo "<td align='center'>$date</td>";
    }
    echo "</tr>";
    }
    ?>
    </table>


    The final display will be like this:



    We now have a plain calendar.

    Adding Special Dates To The Calendar

    This calendar only tells you "the days of a week" at the moment and is not very useful. Most online calendar will have reminders as well. Say for example, if my birthday falls on the 4th of April, I want the number 4 in the calendar be displayed differently, possible with a hyperlink in which upon clicking on it, will perform some task like redirecting me to a certain page or displaying more information about myself in a popup windows..etc. To do that, we need to a table in the database with at least 6 columns: id, day, month, year, link, desc.

    CREATE TABLE calendar (
    id INT NOT NULL AUTO_INCREMENT ,
    day VARCHAR( 2 ) NOT NULL ,
    month VARCHAR( 2 ) NOT NULL ,
    year VARCHAR( 4 ) NOT NULL ,
    link VARCHAR( 255 ) NOT NULL ,
    desc TEXT NOT NULL ,
    PRIMARY KEY ( id )
    );


    We then need to insert some data into the table for testing:

    VALUES (
    '', '24', '*', '2006', 'http://www.sitecritic.net', 'Check your web cccount on the 24th of every month. 2006 only!'
    ), (
    '', '5', '11', '2006', 'some_javascript_funtion', 'Olympics, remember to buy ticket from alice.'
    ),(
    '', '2', '1', '2007', 'some_javascript_funtion', 'early 2007. Any new plans for the year?'
    ), (
    '', '9', '*', '*', 'http://www.evolt.org', 'Remember to check updates from evolt.org every month.'
    );


    The * under the month or year column means every month or year.

    Next, we do a query and extract the important dates for a certain month and store it in an array.

    $sql = "SELECT * FROM calendar WHERE (month='$month' AND year='$year') || (month='*' AND year='$year') || (month='$month' AND year='*') || (month='*' AND year='*')";
    $rs = $db->query($sql);
    while ($rw = $rs->fetchRow()) {
    extract($rw);
    $links[] = array('day'=>$day', 'month'=>$month, 'year'=>$year, 'link'=>$link, 'desc'=>$desc);
    }
    ?>


    If we create a class to generate the calendar, we need to pass the $links array into the class like so:

    $cal = &new Calendar($cArray, $today, $links, $css);
    $cal->render();
    ?>


    The $cArray is a class containing the array for the plain calendar as shown in step 6. The $today variable is today's date. The $links variable contains the important dates in this month. With the $css variable, we can decorate the calendar table and make it look nicer.

    Adding AJAX Capability

    To make the calendar more user friendly, we want to be able to navigate easily between the months or years without refreshing the page. Thanks to AJAX, we can now do that easily. If the user clicks on "next month" for example, we need to call the AJAX function to refresh the calendar without refreshing the page. We do that using XMLHttpRequest. This is the main code that does the trick.

    http.open('get', 'quick_calendar.php?m='+m+&y='+y+'&ran='+ran_no);

    After I get a response from the AJAX function, i need to update the calender. The calendar is wrapped around with the div tag called 'quickCalender'. I just need to rewrite the contents of the tag on the fly.

    document.getElementById("quickCalender").innerHTML = http.responseText;

    Conclusion and Future Improvements

    In this tutorial, we went through the concept of how to create a web calendar using AJAX and PHP. I left the details in the code to prevent the tutorial becoming too long and indigestable. If you look at the code hard enough, you will notice that I packed alot of codes in one file. As a good programming practice, I should have broken them down into smaller parts/files. Because the objective of this project is to create a quick "plug and forget" calendar system, I did that on purpose.

    Also, the object oriented approach I used in the code may not be flexible enough if I want to have different layouts for the calendar. The problem can be easily fixed by using inheritance, ie creating a superclass for the QuickCalendar class. We can then have BrownCalendar, SpecialCalendar ...etc.

    Hope you enjoy reading this tutorial as much as I wrote it. The full demo can be seen here and source code is here.

    source:www.evolt.org

    Friday, October 3, 2008

    Building a Drag-and-Drop Shopping Cart with AJAX

    Keeping up with the latest Web technologies is tough nowadays. Every week it seems new sites are launched that push the envelope further and further in terms of what can be accomplished using just a Web browser.

    The rise of AJAX over the past several months has taken over the development world and breathed new life into the Web. Although these techniques have been possible for many years now, the maturity of Web standards like XHTML and CSS now make it a viable alternative that will be viewable by all but the oldest browsers.

    It's also been possible to accomplish many of the same things using Flex or Flash, but the development cycle with those applications is typically more involved and the overhead often not justified.

    We're going to harness the power of the Scipt.aculo.us JavaScript library to provide our interaction. As their Web site states, this library "provides you with easy-to-use, compatible and, ultimately, totally cool JavaScript libraries to make your web sites and web applications fly, Web 2.0 style." We're also going to utilize the library to handle the actual AJAX data piping to our application. Both of these libraries are free for all to use, and they're easier to integrate than you would think.

    For this article, we'll create an interactive shopping experience allowing us to add items to our shopping basket by dragging and dropping them onto an icon of a shopping cart. We'll add AJAX functionality, allowing us to update our shopping cart without redrawing the entire screen. To save the trouble of setting up a product database, we'll use Amazon Web Services to search for DVDs and use those to shop from.

    Start with a blank index.cfm in your root directory. You'll need to visit http://script.aculo.us/downloads to download the latest distribution (they're nearing a final release for version 1.5 as of this writing). Copy the "lib" and "src" directories into your empty directory. You'll need all of the .js files so just copy over the entire directory in each case. Next, type the following lines into the head /head section of your page:




    We'll need a search box to submit our query to Amazon:


    Search:



    The page will look for a form.search variable and run an Amazon search when it is defined. Each item returned will be placed in its own styled div that will be able to be picked up and dragged.

    The Scriptaculous library makes it easy to create "draggables" (the only required argument is the ID of the object that you want draggable). Listing 1 contains the code to search Amazon and return the results as draggable divs.

    At this point, all of the items returned from the search will be in their own box and should be draggable around the screen. When we created each draggable, we set "revert=true", which will snap each object back to its original location if not placed directly on a drop zone.

    Next, we'll add a graphic of a shopping cart to our page, which will become a drop target on which to drag items. The Scriptaculous library also makes it easy to create these "droppables". The syntax is simply:

    Droppables.add('id_of_element',[options]);

    The code below creates a droppable zone of id "cart1" and also runs a function onDrop() that pops up an alert box letting the user know an item has being added. We then hide the element from view, which allows the other divs to slide over and adjust accordingly.




    The items should now be disappearing when dropped onto the shopping cart, but there's nothing going on behind the scenes yet. Now it's time to add some AJAX to process our shopping cart.

    Although there are several AJAX libraries to choose from, we're going to use the ColdFusion Simple Remote Scripting library made available free of charge by Matthew Walker of ESWsoftware in New Zealand. uses an IFRAME for communication and encapsulates all of the dirty work for you. This library was chosen for its ability to handle HTML tables well and for its ability to interact directly with the browser's Document Object Model (DOM) to output our shopping cart rows.

    We'll start with an empty cart by including the following code:


    Your shopping cart





    (Don't worry about the fact that our table body () is empty right now - we'll be populating it in just a second through AJAX.)

    Next, you'll need to download the package from www.eswsoftware.com/products/download/. Copy the srs.cfm file into your Webroot (or you can add it to your CustomTags directory if you plan to do more AJAXing). You'll also need to create a subdirectory to hold the gateway pages that handle our AJAX data passing. Name the directory "SRS" and copy the Application.cfm and OnRequestEnd.cfm files into there from the "serverpages" directory in the zip file. You can use either regular CFM files or CFCs for these gateway pages (the download provides examples of each). The main thing to remember is that these pages should always return their results to "request.response".

    Simply adding a call to your page will handle the creation of the hidden IFRAME for you. Another great feature of the CF_SRS library is the ability to view an inline debugging window right inside the page you are working on. This allows you to see all of the data being passed back and forth through the gateway. You can enable this debugging by calling the tag as . This line can be placed anywhere but we'll add it at the very end of the file.

    Next, we'll need to create some JavaScript functions to handle the AJAX interactions. Add an onLoad function to your body tag as such: body onload="body_onLoad()". This will execute body_onLoad() when the page loads and we'll use this function to set up our gateway. The function should read as follows:

    function body_onLoad() {
    // create an SRS gateway to the cart.cfm page
    objGateway = new gateway("srs/cart.cfm?");
    // update cart in case of return visit
    // code for this function is below
    updateCart();
    }


    Once you have created your gateway, you can invoke the methods below to send requests to the server:

    objGateway.setListener( str ): Use this method to specify the name of the function in your Web page that will handle the server's response. str is a string representing the function's name. The listener defaults to "alert", which will pop up a JavaScript alert() box containing the server's response. Note that while ColdFusion is a case-insensitive language, JavaScript is case-sensitive. If you return a structure to your listener function, all the structure keys will be rendered in JavaScript as lowercase.
    objGateway.setArguments( obj ): Set the arguments and values to pass to the server. obj is an object literal, which is basically just a set of one or more attribute/value pairs wrapped in curly braces. Here's an example: { name:'Joe', age:30, country:'US' }. You can see that string values need to be wrapped in quotation marks, and colons (:) are used in place of equals signs (=).
    objGateway.resetArguments(): Remove all the arguments previously set.
    objGateway.request(): Send the request to the server.

    Note that you can chain these methods together. For example, it is perfectly acceptable to write:

    objGateway.resetArguments().setArguments( { state:'NY' } ).request()

    Using what we know now, let's take another look at our updateCart() function that we're calling onLoad.

    function updateCart() { objGateway.setListener('cartPacket_onReceive').setArguments(
    {action:'getCart'} ).request(); }


    The function chains together several commands. It sets the listener to "cartPacket_onReceive". That means that we'll execute this JavaScript function whenever data is returned from our gateway. This function handles the generation of our table body that contains our cart rows (see Listing 2).

    In our updateCart() function, we're also passing in an argument: action=getCart. This is going to be passed through to our cart.cfm gateway page. The full text of the gateway page is displayed in Listing 3.

    We're passing in the action variable with a value of "getCart". This gets passed to our cart.cfm gateway page and causes the user's session cart to be returned as a query object. Whenever we need to update our cart to add or delete rows, we'll set our listener to 'cartPacket_onReceive' and then redraw the table body.

    When we created our shopping cart on screen, we added the following button to clear our cart:



    We'll add two JavaScript functions to go along with that button. The first will confirm the delete and the second will issue a call to remove the items and redraw the cart:

    function emptyCartButton_onClick() {
    if ( confirm('Are you sure you want to empty your cart?') ) clearCart();
    }

    function clearCart() {
    objGateway.setListener('cartPacket_onReceive').setArguments( {action:'clearCart'}
    ).request();
    }


    Finally one more JavaScript function to be called when adding items to our cart:

    function addToCart(upc) {
    objGateway.setListener('cartPacket_onReceive').setArguments( { action:'addToCart',upc:upc }
    ).request();
    }


    Now that we have our addToCart() function coded, add the line "addToCart(element.id);" right before the Element.hide call in the shopping cart droppable. This will execute our addToCart() function and redraw the shopping cart when an item is dropped onto it.

    And that's all there is to it! With just 150 lines of code, we were able to create an interactive, drag-and-drop shopping experience that many did not think was possible using just the browser.

    By: Joe Danziger

    Very Dynamic Web Interfaces

    One of the classic drawbacks to building a web application interface is that once a page has been downloaded to the client, the connection to the server is severed. Any attempt at a dynamic interface involves a full roundtrip of the whole page back to the server for a rebuild--a process which tends to make your web app feel inelegant and unresponsive. In this article, I'll be exploring how this problem can be tackled with the use of JavaScript and the XMLHttpRequest object.

    I'm sure you're familiar with the traditional interface model for a web application. The user requests a page from the server, which is built and delivered to the browser. This page includes an HTML form element for capturing data from the user. Once the user posts their input back to the server, the next page can be built and served based on the input, and so the process continues. This is largely dictated by the nature of HTTP and differs from the traditional desktop application model of an interface which is inherently connected to the application layer.

    Take the simple example of filling out a serial number box to register a desktop app on a platform like Microsoft Windows. According to convention, once you've finished typing that tiresome string of alphanumeric into the little boxes, a big green 'tick' icon appears to indicate you've entered a valid code. This happens instantly as a result of the interface being sewn to the application; as soon as you finish typing the number, the application is able to check its validity and respond.

    Contrast this to the standard behavior of the same task represented through a web interface. Sure, all the boxes for keying in the serial number will look identical, but on completing input, the user would need to submit the page back to the server for the input to be validated. A new page would then load with a message to indicate success or failure, and on failure, the user would need to go back and try again ad infinitum.

    So whilst it's not terribly common that a user would be asked to enter a serial number into a web application, there are countless other examples of user actions that can benefit from very fast reactions from the interface, and when the business logic is all the way back at the server, this can be difficult to achieve in a traditional web app.

    Enter JavaScript
    Through the use of JavaScript, a reasonable amount of logic can be added to an HTML page in order to give timely feedback to user interactions. This has some major drawbacks, however. The first problem is that, as the JavaScript has been delivered to the browser along with the page, that logic has been opened up to interrogation. This might be fine for checking the format of an email address but would be no good for something like our serial number example, as the exposure of the method of verifying that input would compromise the integrity of the serial number mechanism.

    The second problem with including any serious logic within the page is that the interface layer is simply not the place for serious logic. This belongs in the application layer, which is way back at the server. The problem is compounded by the fact that JavaScript cannot usually be relied upon to be available at the client. Whilst the majority of users are able and willing to run JavaScript in their browser, a considerable number prefer not to, or browse with a device where JavaScript is either unavailable or makes no sense. Therefore, any logic operations performed with JavaScript at the client must be verified at the server in case the operation never occurred.

    The XMLHttpRequest Object
    A solution to these problem presents itself in the form of the XMLHttpRequest object. This object, first implemented by Microsoft as an ActiveX object but now also available as a native object within both Mozilla and Apple's Safari browser, enables JavaScript to make HTTP requests to a remote server without the need to reload the page. In essence, HTTP requests can be made and responses received, completely in the background and without the user experiencing any visual interruptions.

    This is a tremendous boon, as it takes the developer a long way towards achieving the goals of both a responsive user interface and keeping all the important logic in the application layer. By using JavaScript to ferry input back to the server in real time, the logic can be performed on the server and the response returned for near-instant feedback.

    The Basics
    Due to its history, and not yet being embodied in any public standard (although something similar is in the works for the proposed W3C DOM Level 3 Load and Save spec), there are two distinct methods for instantiating an XMLHttpRequest object. For Internet Explorer, an ActiveX object is used:

    var req = new ActiveXObject("Microsoft.XMLHTTP");
    For Mozilla and Safari, it's just a native object:

    var req = new XMLHttpRequest();


    Clearly, as a result of this inconsistency, it's necessary to fork your code based on support for the appropriate object. Whilst there are a number of methods for doing this (including inelegant browser hacks and conditional comment mechanisms), I believe it's best to simply test for support of either object. A good example of this can be found in Apple's developer documentation on the subject. Let's take their example:


    var req;

    function loadXMLDoc(url)
    {
    // branch for native XMLHttpRequest object
    if (window.XMLHttpRequest) {
    req = new XMLHttpRequest();
    req.onreadystatechange = processReqChange;
    req.open("GET", url, true);
    req.send(null);
    // branch for IE/Windows ActiveX version
    } else if (window.ActiveXObject) {
    req = new ActiveXObject("Microsoft.XMLHTTP");
    if (req) {
    req.onreadystatechange = processReqChange;
    req.open("GET", url, true);
    req.send();
    }
    }
    }


    A particularly important property to note is the onreadystatechange property. Note how it is assigned to a function processReqChange. This property is an event handler which is triggered whenever the state of the request changes. The states run from zero (uninitialized) through to four (complete). This is important because our script isn't going to wait for the response before continuing. The HTTP shenanigans are initiated, but then they carry on out of process whilst the rest of the script runs. Due to this, it's not as simple as having loadXMLDoc return the result of the request at the end of the function, because we don't know if we'll have a response by then or not. By having the function processReqChange check for the state changing, we can tell when the process has finished and carry on only if it has been successful.

    With this in mind, a skeleton processReqChange function needs to check for two things. The first is the state changing to a value of 4, indicating the process complete. The second is to check the HTTP status code. You'll be familiar with common status codes like 404 (file not found) and 500 (internal server error), but the status code we're looking for is good old 200 (ok), which means everything went well. If we get both a state of 4 and an HTTP status code of 200, we can go right ahead and start processing the response. Optionally, of course, we can attempt to handle any errors at this point, if, for example, the HTTP status code was something other than 200.

    function processReqChange()
    {
    // only if req shows "complete"
    if (req.readyState == 4) {
    // only if "OK"
    if (req.status == 200) {
    // ...processing statements go here...
    } else {
    alert("There was a problem retrieving
    the XML data:\n" + req.statusText);
    }
    }
    }

    In Practice
    I'm going to work up a practical example so we can get this going. Most web applications have some method of signing up users, and it's common to ask the user to pick a username to use for the site. Often, these need to be unique, and so a check is made against the database to see if any other user already has the username a new recruit is trying to sign up with. If you've ever signed up for a web mail account, you'll know how infuriating it is cycling around the process trying to find a username that isn't already taken. It would be really helpful if that check could be made without the user leaving the page.

    The solution will involve four key elements: an XHTML form, a JavaScript function for handling the specifics of this case, our pair of generic functions (as above) for dealing with HTTP, and finally, a script on the server to search the database.

    The Form
    Here's the easy bit--a simple form field to collect the user's chosen username. An onblur event handler is used to fire the script. In order to display a friendly message to the user if the name is taken, I've embedded it in the form and hidden it with CSS. This should prove a little less violent than a standard JavaScript alert box.

    onblur="checkName(this.value,'')" />


    The CSS defines a class for hidden and also one for showing the error. Call that one error.

    span.hidden{
    display: none;
    }

    span.error{
    display: inline;
    color: black;
    background-color: pink;
    }


    Handling the Input
    The checkName function is used to handle the input from our form. Its job is to collect the input, decide which script on the server to present it to, invoke the HTTP functions to do the dirty work on its behalf, and then deal with the response. As such, this function has to operate in two modes. One mode receives input from the form, the other the response from the HTTP request. I'll explain the reason for this in the next section.

    function checkName(input, response)
    {
    if (response != ''){
    // Response mode
    message = document.getElementById('nameCheckFailed');
    if (response == '1'){
    message.className = 'error';
    }else{
    message.className = 'hidden';
    }
    }else{
    // Input mode
    url =
    'http://localhost/xml/checkUserName.php?q=' + input;
    loadXMLDoc(url);
    }

    }

    Our response is going to be easy to deal with--it'll be a string of either 1 or 0, with 1 indicating that the name is in use. Therefore, the function changes the class name of the error message so it gets displayed or hidden, depending. As you can see, the dirty work at the server is being done by a script called checkUserName.php.

    HTTP Heavy Lifting
    As we saw earlier, the HTTP work is being done by two functions, loadXMLDoc and processReqChange. The former can remain totally as-is for the purposes of this example, with the only modifications needed to the latter being a quick bit of DOM work.

    You'll recall that by the time a successful response has been passed to processReqChange, we're no long in a position to pass any sort of return value back up the chain. Because of this, it's going to be necessary to make an explicit function call to another bit of code in order to do anything useful with the response. This is why our checkName function has to run in two modes. Therefore, the main job of processReqChange is to parse the XML coming back from the server and pass the raw values back to checkName.

    However, it is important that we keep these functions generic (we may have multiple items on the page that need to make use of XMLHttpRequest), and so hard-coding a reference to checkName at this point would be foolhardy. Instead, a better design is to have the server indicate the handling function as part of its response.

    standalone="yes"?>

    checkName
    1

    Parsing such a simple response should be no problem at all.

    function processReqChange()
    {
    // only if req shows "complete"
    if (req.readyState == 4) {
    // only if "OK"
    if (req.status == 200) {
    // ...processing statements go here...
    response = req.responseXML.documentElement;

    method =
    response.getElementsByTagName('method')[0].firstChild.data;

    result =
    response.getElementsByTagName('result')[0].firstChild.data;

    eval(method + '(\'\', result)');
    } else {
    alert("There was a problem retrieving the XML
    data:\n" + req.statusText);
    }
    }
    }


    By using the responseXML property of the XMLHttpRequest object, we have a ready-made XML object we can traverse with the DOM. By grabbing content of the method element, we know which local function to execute along with the result. Once you've finished testing, it's probably a good idea to dump the else clause from the above code, enabling the function to fail silently.

    The Server Script
    The final piece in our jigsaw is the script on the server to accept the request, process it, and return an XML document in response. For the purposes of our example, this script looks up usernames in a database table to determine whether a name is already in use. For brevity, my example PHP script below just checks against two hard-coded names, 'Drew' and 'Fred'.


    header('Content-Type: text/xml');

    function nameInUse($q)
    {
    if (isset($q)){
    switch(strtolower($q))
    {
    case 'drew' :
    return '1';
    break;
    case 'fred' :
    return '1';
    break;
    default:
    return '0';
    }
    }else{
    return '0';
    }

    }
    ?>
    standalone="yes"?>'; ?>

    checkName
    echo nameInUse($_GET['q']) ?>


    Of course, the logic used to verify the availability of the username in this script can be reused after the form is submitted to recheck that the name is available. This is an important step, since if JavaScript was not available at the client, this check would not have yet taken place. Additionally, on a busy site, a username which checked out OK at the time the user was filling the form in may have been taken by the time the form is submitted.

    Perhaps as a next step, if you're interested in playing with this some more, you could add the ability for the server to return a list of suggested alternative usernames if the suggested name is taken.

    In Conclusion
    This small example really only scratches the surface of the things achievable with XMLHttpRequest. Some other examples would include Google Suggest, which uses XMLHttpRequest to provide suggested search terms, and the Ta-da Lists application, which commits user data to the server in the background to provide a really fast list managing interface. The real challenge here is not figuring out how to make the code work but thinking of interesting ways in which it can be utilized.

    source:xml.com

    Ajax Tutorial for beginners

    In this tutorial we'll discuss the basic principles of remote scripting using Ajax, a combination of javascript and XML to allow web pages to be updated with new information from the server, without the user having to wait for a page refresh. Ajax therefore allows us to build web applications with user interfaces rather more like those of desktop applications, providing a better experience for the user. Ajax tools are becoming increasingly popular, and a list of ajax development projects is also given.

    Here you'll find:

    a brief tour of the important principles of Ajax
    code examples of all important points
    links to further Ajax and related resources

    This tutorial covers subjects which require some degree of familiarity with Javascript and PHP. Beginners may therefore find it a little hard going, but hopefully should still be able to grasp the principles and uses of Ajax, if not the details. There are some demos and further links at the bottom of the article and elsewhere on these pages - feel free to explore..

    What is it?
    The standard and well-known method for user interaction with web-based applications involves the user entering information (e.g. filling out a form), submitting that information to the server, and awaiting a page refresh or redirect to return the response from the server.

    This is at times frustrating for the user, besides being rather different to the 'desktop' style of user interface with which (s)he may be more familiar.

    Ajax (Asynchronous Javascript And XML) is a technique (or, more correctly, a combination of techniques) for submitting server requests 'in the background' and returning information from the server to the user without the necessity of waiting for a page load.

    Ajax is actually a combination of several technologies working together to provide this capability.

    How does it work?
    Instead of a user request being made of the server via, for example, a normal HTTP POST or GET request, such as would be made by submitting a form or clicking a hyperlink, an Ajax script makes a request of a server by using the Javascript XMLHTTPRequest object.

    Although this object may be unfamiliar to many, in fact it behaves like a fairly ordinary javascript object. As you may well know, when using a javascript image object we may dynamically change the URL of the image source without using a page refresh. XMLHTTPRequest retrieves information from the server in a similarly invisible manner.

    How is it coded?
    There are a few, relatively simple, steps to coding an Ajax application. The description below is an attempt to describe the salient points without bogging down the new user in too many of the technicalities.

    Firstly, we need to know how to create an XMLHTTPRequest object. The process differs slightly depending on whether you are using Internet Explorer (5+) with ActiveX enabled, or a standards-compliant browser such as Mozilla Firefox.

    With IE, the request looks like:

    http = new ActiveXObject("Microsoft.XMLHTTP");

    whereas in a standards-compliant browser we can instantiate the object directly:

    http = new XMLHttpRequest();


    There's an example of a short piece of code to create the object here, which clearly demonstrates the different approaches for the two different browser types, along with a browser detection routine.

    Secondly, we need to write an event handler which will be called via some event on our user's page, and will handle sending our request for data to our server.

    The event handler will use various methods of our XMLHTTPRequest object to:

    » make the request of the server
    » check when the server says that it has completed the request, and
    » deal with the information returned by the server

    We can make our request of the server by using a GET method to an appropriate server-side script. Here's an example event handler called updateData which assumes that we have created our XMLHTTPRequest object and called it http:

    function updateData(param) {
    var myurl = [here I insert the URL to my server script];


    http.open("GET", myurl + "?id=" + escape(param), true);
    http.onreadystatechange = useHttpResponse;
    http.send(null);
    }


    Note that the function listens to the onreadystatechange property of the XMLHTTPRequest object and, each time this parameter changes, calls a further function useHttpResponse.

    You will note also that, for the sake of clarity, I have said little about the server-side script which is called - essentially this can be any server routine which will generate the required output when called with the relevant URL and appended parameters, as in any other HTTP GET request. For the sake of the example we are passing a variable named id with a value param passed as an argument to the updateData function.

    Thirdly, then, we need to write a function useHttpResponse which will establish when the server has completed our request, and do something useful with the data it has returned:

    function useHttpResponse() {
    if (http.readyState == 4) {
    var textout = http.responseText;
    document.write.textout;
    }
    }

    Note here that our function checks for a readyState value of 4 - there are various numbered states describing the progress of such a request, but we are only interested in the value of 4, which indicates that the request is complete and we can use the returned data.

    In this case, we have received our information as simple text via the responseText property of our XMLHTTPRequest object. Information can, however, be returned as XML or as properties of a predefined javascript object, though this is perhaps beyond the scope of this tutorial.

    by ajaxprojects.com

     

    Copyright © 2009 - tutorialfeed.org