Monday, September 16, 2013

Friday, September 3, 2010

100 Popular jQuery Examples, Plugins and Tutorials

    1. jQuery Lavalamp MenuIt is the jQuery plugin that is based of Guillermo Rauch plugins for mootools and Ganesh Mawwaha’s jQuery 1.1.x plugins. Through the Sliding Doors CSS/Javascript method, you are able to add a background hover effect on HTML link lists with Lavalamp by utilizing the Eazing library.
    2. Superfish Menus – Suckerfish on ‘roids, This jQuery plugin allows the development of improved Suckerfish style of dropdown menus from the existing pure CSS type of dropdown menu. The features that are added as a result of these include: a timed-delay on mouseout, automatic utilization of hoverIntent plugin when present; obligatory IE6 –hover capability; animated sub-menu; accessibility through keyboard tab key; generation of arrows to indicate the submenus; use of drop shadows for browsers that are capable; and many others.
    3. jQuery Context MenuThis jQuery plugin provides easy implementation, CSS styling, keyboard shortcuts and control methods.
    4. Kwicks for jQueryThis highly versatile and customizable widget had started as just a port for Mootools framework.
    5. jQuery iPod-style Drilldown MenujQuery has an iPod-style drilldown menu that helps users traverse hierarchical data with relative ease and control. This feature is very useful in organizing large data structures that don’t translate well into the traditional fly-out or dropdown menus.
    6. jQuery File TreeThis jQuery plugin is a configurable AJAX file-browser plugin where you use to create a fully interactive and customized file tree as little as one of the Javascript code.
    8. CSS Sprites2 using jQueryOne can use jQuery to implement CSS Sprites2. One distinct advantage of jQuery over the other javascript libraries is that it allows users to select elements on a pages using CSS-like syntax that we are already familiar with.
    9. jQuery AccordionIt is the jQuery plugin that allows the creation of the accordion menu. It can be used for nested lists, nested divs and definition lists. This plugin has options for structure specification, active element, when necessary, and animation customization.
    IMAGE MANIPULATION
    10. jQZoomIt is the jQuery plugin that easily allows the creation a small magnifier window near an image or group of images on the web page. You decide to build jQZoom to embed big images in your B2B. This creates the jQZoom in your eCommerce websites or any other websites.
    11. jCropThis jQuery plugin allows an easy and quick way of adding image-cropping functionality to web application. This functionality combines the use of typical plug in with a powerful cross-platform DHTML cropping engine that is compatible to common desktop graphics applications.
    12. Captify 1.1.0It is a jQuery plugin that creates short and beautiful image captions that appear every time a user’s mouse passes over an image.
    IMAGE GALLERIES AND VIEWERS
    13. Simple Controls GalleryThis jQuery tools displays and rotates images by fading it into view over the previous images using navigation controls that pop up when the mouse moves over the gallery.
    14. Agile CarouselIt is a jQuery plugin that provides for the easy creation of a custom carousel. This plugin makes use of PHP to call images from the folder that is specified by the user. Users can configure different options including slide timer length, controls, transition type, easing type and more.
    TRANSITION EFFECTS
    15. InnerFadeIt is a small jQuery plugin used in the jQuery Javasrcipt Library. This plugin allows using fade effects on any element found within a container in and out. The elements may include divs, list items or images. In order to do this, you have to create your own slideshow and the produce a newsticker or an animation.
    16. Easing PluginIt is the jQuery plugin that comes from GSGD that provides advanced easing options. This plugin can support a default easing mode. This allows you to set your preferred animation once for all animations. It uses the Robert Penners easing equations for all the transitions.
    17. HighlightFadeIt is a jQuery plugin that allows the use of fading effects from one color to any other pre-selected colors at any transition speed and interval of color update using a color progression tactic that is customizable.
    18. JQuery Cycle PluginIt is a jQuery plugin that is classified as basic slideshow plugin. It is based on the Slideshow plugin by Matt Oakes, jqShuffle plugin by Benjamin Sterling and the InnerFade plugin by Torsten Baldes. This plugin can do auto-stop, before and after callbacks, pause-on-hover, and many other transition effects.
    jQUERY CAROUSEL
    19. Riding Carousels using jQueryIt is the jQuery plugin used for controlling items in a list in vertical or horizontal order. The list of items can be loaded with or without AJAX, or can be a static HTML content. It can be scrolled in either direction with or without animation effects.
    COLOR PICKER
    20. FarbtasticIt is a jQuery plugin that allows you to add more color picker widgets in a page using Javascript. These widgets are linked to an element and will update the value of that element when one particular color is picked.
    21. jQuery Color PickerIt is a jQuery plugin that allows you to select color in a way that is almost the same as you pick colors in Adobe Photoshop. This jQuery plugin is a Flat mode element in a page and is easy to customize the look by simply changing the images. It also has powerful controls used for selecting the colors and fits easily into the viewport.
    LIGHTBOX
    22. jQuery ThickBoxIt is a jQuery plugin that is created using the jQuery library. The function of this jQuery plugin is to resize images that are bigger than the browser window and provides versatility in inline content, images, AJAX content and iFramed content. It will remain at the center of the window even if you change the size of the browser window or you scroll the pages.
    23. SimpleModal DemosIt is a jQuery plugin defined as lightweight plugin that creates a basic interface to provide a modal dialog. This jQuery plugin shall give developers a cross-browser overlay and a container that will contain data provided to SimpleModal
    24. jQuery LightBox PluginIt is a jQuery plugin that provide an option to present an image on a page in a simple and elegant manner. Under this jQuery plugin, the lightboxes can be assembled in one group and provides many options for configurations. It also provides both the manual and automatic options to create and to start lightboxes.
    25. Revealing Photo SliderThis tool of jQuery allows to create a thumbnail photo gallery where clicking a button would reveal the entire photo and other information about the photo.
    26. FancyBoxThis jQuery tool automatically scales large images to fit in windows by adding a nice drop-shadow under the zoomed item. This tool can be used to group items that are related and add navigation between them. It is totally customizable through CSS and settings.
    28. jQuery.popeyeIt is a jQuery plugin that converts an unordered list of images into a simple image gallery. When an image is clicked, it enlarges just like with LightBox.
    FORM ELEMENTS AND VALIDATION
    29. jQuery Form ValidationIt is a jQuery plugin that is fast, unobtrusive, scalable and easy to use validation plug in that offers a variety of methods for all types of validation needs. It comes from the very basic to the more complex schemes of validation.
    30. Ajax Form ValidationThis refers to the client aspect of validation using Javascript. The username will perform the validation by checking with the server whether a chosen username is available and valid.
    31. jQuery AlphaNumericIt is a jQuery plugin that uses javascript to allow you to control what characters a user can use and enter on text areas and text boxes.
    32. jQuery.combobox – It is a jQuery plugin that provides a simple way of producing an HTML type of combobox from the existing HTML Select tags. This plug in was created to provide the solution on the limitation in styling of standard Select tag.
    33. jQuery CheckboxIt is a jQuery plugin that creates a replacement for the standard checkbox. This plugin allows you to modify the look of the elements of the checkbox in the page.
    34. File Style PluginIt is a jQuery plugin that solves your problem with browsers that does let you style file inputs. This jQuery plugin also allows you to style filename field to normal textfield by using css.
    36. Submit a Form Without Page RefreshBy using jQuery, you not only can add form validation to wordpress comments without any page reload but also submit your form without a page refresh.
    37. jQuery AJAX Contact FormUsers of jQuery can make an AJAX contact form with a “honeypot” to foil email bots, load success and error messages without leaving the page and provides descriptive error messages detailing the reasons for the failed validation of the submitted value.
    38. jQuery Form ValidationThis form of jQuery can show form-input validators both the browser-side and server-side
    STAR RATING
    39. Simple Star Rating SystemIt is a jQuery plugin used for star rating system. This jQuery system was created with the basic framework of the star rating system of Wil Stuckey. This jQuery plugin provides the solution on the problem of the original script requiring too much coding. It also did away with the requirement for developing a star system.
    40. Half Star Rating PluginIt is a jQuery plugin that was developed in response to the clamor for an enhancement of the simple rating system of Ritesh Agrawal and allow for the use of half-star rating system.
    TABLE PLUGINS
    41. Table Sorter PluginIt is a jQuery plugin that is used to turn a standard HTML table with TBODY and THEAD tags into a table which is sortable without resorting to page refreshes. This jQuery plugin can effectively sort and parse multiple data including data in a cell that are linked.
    42. Autoscroll Plugin for jQueryIt is a jQuery plugin that provides for hotspot scrolling of webpages. This jQuery plugin will still work even with earlier versions of jQuery.
    43. Scrollable HTML Table PluginIt is a jQuery plugin that is used to convert HTML tables into scrollable tables. This jQuery plugin solution does not require any additional coding.
    44. Table Row CheckBox ToggleThis jQuery tool adds a toggle function to any table row that you specify based on a CSS class name. This tool will toggle on by default any check boxes within that table row.
    45. TablesorterThis is a jQuery plugin that allows you to turn a standard HTML table with <td> and <th> tags to a sortable table without refreshing the page. This plugin can successfully parse and sort many kinds of data in a cell.
    46. TableEditorThis tool allows flexible in-place editing of HTML tables. Users can easily drop handler functions to update.
    ROUNDED CORNERS
    47. jQuery Curvy CornersIt is a jQuery plugin that allows for the creation of nice looking rounded corners without the use of images. It is a jQuery plugin considered to be unobtrusive and can work well with all major browsers which include iPhone. Another nice feature about this jQuery plugin is that the corners to be rounded and its radius can be set easily.
    OTHER JQUERY PLUGINS
    48. HeatColor PluginIt is a jQuery plugin that provides color to elements and determined by a value derived from that element. This derived value comes from a range of value which are either pre-designated or passed in. The element is then assigned a “heat” color which is derived from the position of the value within the range of values.
    49. jQuery Date PickerIt is a jQuery plugin that is considered unobtrusive and clean. It adds date-entry functionality to web forms and pages. It was created from the basics up in order to attain flexibility and extensibility. It has varied options of use that allow you to all a calendar widgets to web pages and forms.
    DYNAMIC CONTENT
    50. Create a Log-in Form with jQueryOne can create a sliding panel that slides in to reveal new content and animate the height of the panel through jQuery.
    51. Spoiler Revealer with jQueryThis is a technique in jQuery that can hide and reveal content with animation effect once it is clicked.
    52. AJAX UploadIt is a jQuery plugin that provides for easy uploading of multiple files without having to refresh the page. This plugin also allows the use of any element to trigger the file selection window.
    53. FCBKcompletejQuery also provides users with Facebook-like dynamic inputs along pre-added and auto-complete values.
    MANIPULATING CONTENT
    55. jQuery Books WidgetOne can use jQuery with some custom Javascript to create interesting widgets like a browsable Amazon.com books widget.
    56. Text Size SliderUsers of jQuery can control the text size of an article on a page using a slider. This feature of jQuery allows the user to control exactly the size they prefer and is a very impressive feature to have on a site.
    57. PaginationUsers of jQuery can group large numbers of items into pages and present navigational elements that allow users to move easily from one page to another.
    58. Coda-SliderThis jQuery tool also groups items together through navigational elements that allow users to traverse the pages.
    59. Slick Auto-Playing Featured-Content SliderThis jQuery plugin allows users to cycle through panels and auto-playing different kinds of custom content. It features an arrow indicator to guide users on which panel he is currently viewing.
    BROWSER TWEAKS
    60. Setting Equal Heights with QueryThrough jQuery, users can utilize a script that can equalize the box heights within the same container to create a tidy grid.
    62. BGI FrameThis jQuery tool helps users in dealing with IE z-index issues.
    63. Fix OverflowThis jQuery bug fix solves the issue on the scroll bar covering overflowing elements when the element is only one line.
    64. Lazy LoadThis tool can delay the loading of images below the fold on long pages, loading the images only when the user scrolls down on that part of the page.
    65. MaxlengthThis jQuery plugin automatically limits the number of characters a user can input in a field and giving feedback on how many spaces are remaining.
    ANIMATION EFFECTS
    66. ScrollableIt is a lightweight and flexible jQuery plug-in used to create a scrollable content. It can contain any HTML, including images, forms, text, video or a combination of any of them.
    67. Fading Menu-Replacing ContentThis jQuery tool lets users to utilize animation and change the way to style a page on-the-fly to react to events that happen on your page.
    TOP jQUERY TIPS
    70. Rotate Through Tabbed ContentThrough this functionality of jQuery, the movement is more likely to catch the user’s eyes, thus increasing the chances they will notice the tabbed box and allow the user to see all the content of the box instead of just the first tab.
    71. Stopping the RotationThis technique allows users to stop the rotating of tabs and stop it from switching when you are interacting with them. The technique involves some editing a couple of lines from the document ready function.
    72. Build a Tabbed Content with CSS and jQueryThis technique outlines the steps required to easily customize to fit the size and color scheme, use fixed or variable height, automatically rotate through the tabs and stop the rotation when the user needs to.
    73. Advanced CSS Accordion EffectThis technique is improved by the use of Javascript and all browsers will handle this technique even without JS enabled.
    74. Consistent Base Font SizeThis is the best jQuery technique to gain control over your font sizes until IE finally support the resizing of text in pixels.
    75. Maintain Consistent MarginsThis jQuery technique enables users to remove the margin and padding from every element instead of CSS resets.
    76. Set a Float to Clear a FloatThis jQuery is one of the most important things to understand with CSS. However, it is also important to learn how to clear floats.
    77. Image ReplacementThis image replacement technique involves the positioning an image over the top of the HTML. One feature of this technique is that even when images are disabled, the text is still visible.
    78. Faux ColumnsThis technique allows 2 adjacent columns with unequal amounts of content to have 1px tall background image being repeated vertically in the containing element of the 2 columns.
    79. Animate a Hover with jQueryThis technique allows users to animate an image while hovering over it and allow users to see information while doing that
    85. 43,439 Reasons to Use Append() CorrectlyThis technique provides for the proper way of using this jQuery method. Although an extremely easy and useful method to work with, it can significantly affect the performance of the page.
    87. Minimize Manipulation of DOMWe can further make the code faster if we cut down on the frequency that we insert into the DOM. Insertion operations of DOM will make things slow down.
    88. Give context to your selectorsWhen you use the selector, the entire DOM will be traversed as a result of the action. This can be a very expensive process.
    jQUERY TUTORIALS
    89. How jQuery WorksThis is a featured tutorial on jQuery by John Resig, the creator of jQuery. This is an ideal basic tutorial for those who are starting to learn jQuery for the first time.
    90. jQuery in 15 DaysThis is a 15 day tutorial that turns you from a greenhorn to an expert in 15 days.
    91. BassistanceThis tutorial covers the basics of jQuery up to the more advanced topic like building plugins.
    92. Remy Sharp’s BlogHe has written numerous tutorials and plugins and he is also the person responsible for the very helpful jQueryForDesigners website which also provides useful tutorials in answer to request of readers.
    93. CSS TricksThis reference site is full of examples, tips, tricks, tutorials and news about cascading style sheets (CSS).
    94. jQuery Cheat SheetsIt provides to aspects of cheat sheets. These are: those made for iPod and other mobile devices; and those with the A4 cheat sheet.
    98. How to Get Anything You WantThis is an introductory tutorial on traversal methods and jQuery selectors and their use in DOM navigation
    99. It’s all about CSSAs the title suggests, this tutorial is all about CSS selectors. Once you learn from this tutorial, you can now easily query the DOM.
    100. jQuery Crash CourseThis tutorial is designed for web designers with advanced knowledge of codes.

atooltip jQuery ToolTip plugin

<!-- Include the needed js files-->
<script type="text/javascript" src="js/jquery.min.js"></script>
<script type="text/javascript" src="js/atooltip.jquery.js"></script>

Initiate the plugin

// initiate the plugin after DOM has loaded
$(function(){

    // basic usage
    $('a.normalTip').aToolTip();
    // fixed tooltip
    $('a.fixedTip').aToolTip({
        fixed: true
    });
    // on click tooltip with custom content
    $('a.clickTip').aToolTip({
        clickIt: true,
        tipContent: 'Hello I am aToolTip with content from param'
    });   
    // List of all paramaters and their default values:
    $('a').aToolTip({
        clickIt: false,                     // set to true for click activated tooltip
        closeTipBtn: 'aToolTipCloseBtn',    // you can set custom class name for close button on tooltip
        fixed: false,                        // Set true to activate fixed position
        inSpeed: 400,                        // Speed tooltip fades in
        outSpeed: 100,                        // Speed tooltip fades out
        tipContent: '',                        // Pass in content or it will use objects 'title' attribute
        toolTipClass: 'aToolTip',            // Set custom class for tooltip
        xOffset: 5,                            // x Position
        yOffset: 5                            // y position
    });
});

 

Basic HTML markup used in the demos

<!-- Here is the markup for the 3 examples-->
<a href="#" class="normalTip" title="Hello, I am aToolTip">Normal Tooltip</a>
<a href="#" class="fixedTip" title="Hello, I am aToolTip">Fixed Tooltip</a>
<a href="#" class="clickTip">On Click Tooltip</a>

 

What does the tooltip markup look like?

<!-- the tooltip markup looks like this

<div class="aToolTip">
    <p class="aToolTipContent">Your tooltip content</p>
</div>

-->

 

download

23 Best jQuery Facebook Style Plugins

The Facebook User Interface is one of the most popular, attractive and simple to use. At the same time, it is a challenge for designers to create these kind of user interface. These jQuery plugins help designes to create facebbok style UI with ease.

1. Facebox

Facebox is a jQuery-based, Facebook-style lightbox which can display images, divs, or entire remote pages. It is simple to use and easy on the eyes. Download the tarball, view the examples, then start enjoying the curves.

2. Creating a Facebook-like Registration Form with jQuery

Facebook is a showcase of great UI design. And as it has become a major part of our lives, it has also raised the bar for web development, pushing developers to meet higher expectations. This however has a good side ? it challenges web developers and designers to better themselves and constantly improve their work. In this tutorial, we are going to learn from the best, and create a facebook-like sign up form. So go ahead and download the demo files to start learning!

3. Simple facebook-like textbox dropdown jquery plugin

I created this plugin as a colleague of mine asked to do similar functionality as the status dropdown on facebook?It is very very simple, and could be extended with a lot of functionality, but I will leave that as a challenge for later or others.

4. Tipsy – Facebook-style tooltip plugin for jQuery

Tipsy is a jQuery for creating a Facebook-like tooltips effect based on an anchor tags title attribute.

5. Facybox

Facybox is a jQuery-based, Facebook/Fancybox-style lightbox which can display images, divs, or entire remote pages. It is simple to use and easy on the eyes.

6. FCBKcomplete

FCBKcomplete allows to generate fancy facebook-like dynamic inputs with auto complete & pre added values.

7. Facebook Style jQuery Chat

Everyone loves the gmail and facebook inline chat modules. This jQuery chat module enables you to seamlessly integrate Gmail/Facebook style chat into your existing website.

8. Display Collapsed Comments like Facebook with Jquery and Ajax

In this post I want to explain Facebook like Collapsed Comments, while clicking View all Comments link it displays all the existing comments. I made a demo with jquery, ajax and php.

9. Elastic – Make your textareas grow Facebook style jQuery plugin

This Jquery plugin makes your textareas grow and shrink to fit its content. It was inspired by the auto growing textareas on Facebook. The major difference between Elastic and its competitors is its weight.

10. Facebook Style Wall Post Application with jQuery and Ajax

Are you looking for Facebook style wall post application. It contains update, comment and delete with jquery animation effect. In this post I had combined some of my old tutorials demos in single page.

11. Facebook like multi Toggle Comment Box with jQuery and PHP

Implement Facebook like toggle comment box for every updated wall. I had designed a simple example it contains of very simple jQuery and PHP code.

12. Facebook like suggestions with jQuery content appears and disappears

This post IS about how to implement Facebook-like users Suggestions. When you click delete(X) button “Do not show this suggestion” the content disappears slowly and to get the new suggestion content appears. I had developed this using jQuery, PHP just some lines of code.

13. TextboxList jQuery Plugin

TextboxList turns normal textboxes into a widget which can be navigated with the keyboard, effectively turning your input into a ?list? of items that can be easily deleted. It comes with an Autocomplete plugin.

14. Facebook Autocompletion JQuery Plugin

I was evaluating all the available JQuery plugins to get a Facebook-like contact autocompletion functionality, and deemed the one by Ian Tearle to be the most complete available. However, most complete does not mean fully done, or bug free, and I learned this the hard way doing an initial implementation on a project I?m doing at work.Spending all day with the lovely Firebug debugger and testing in both Firefox 3 and IE7, I can say I have it working the way I need it to. My version fixes the f

15. FaceBoox style autosuggest with jQuery

This autosuggest search engine is inspired from facebook for design, uses jQuery as ajax framework and BSN Autosuggest libs. This autosuggest search engine is inspired from facebook for design, uses jQuery as ajax framework and BSN Autosuggest libs.

16. FaceBook Style Image Editing jQuery Plugin

I have just finished making my first jquery plugin, the FaceBook Style Image Editing jQuery Plugin. It is not so hard after all. This will add a link when hover on image. For instance, if you hover on your profile image on facebook. This Plugin meanwhile works on Div Only

17. Facelist jQuery Plugin

Media By Ian Tearle presents the jQuery Facelist project. Built for the sole purpose of providing a Facebook style autosearch, Ian is letting you build upon this excellent product.

18. How to create a Facebook Friend Selector using jQuery and PHP or Grails

Create a Facebook Friend Selector using jQuery and PHP or Grails.

19. Facebook style photo tagging with jQuery, Ajax and Joomla

This tutorial explains how to create facebook style Photo tagging with jQuery.

20. Facebook style information box with jQuery

On Facebook there is a big information page in each profile, there is also a smaller one to the left and this time the requirement was to create exactly the same functionality. We need to show certain information that the user wants to show there, and also having a small control box with check boxes that when checked or unchecked will send an Ajax call to the server to update which fields are shown

21. Facebook style Unobtrusive Ajax Pagination for will paginate with jQuery

I really like the pagination that Facebook provides on their status tab. It is not true pagination in that the result set is changed, but it does add additional results to the bottom of the set. Anyway, I went ahead and created a plugin for jQuery based on the wonder Rails plugin will_paginate. Introducing, jquery-bottomless-pagination.

22. Facebook Style Alert Confirm Box with jQuery and CSS

I received a request from my reader that asked to me how to implement facebook style alert box. So I had designed Facebook Style Alert Confirm Box with jquery plug-in jquery.alert.js. It is simple just changing some lines of CSS code.

23. Boxy – Facebook-like Dialog Overlay With Frills

Boxy is a flexible, Facebook-style dialog box for jQuery with support for dragging and size tweening. It differs from other overlays I have seen by providing an object interface to control dialogs after they have been created. And for simple usage scenarios, boxy also provides a jQuery plugin for automatically hooking up links and forms, as well as an ask() helper for presenting multiple choices to the user.

Sunday, August 29, 2010

Handling Session timeout & other server http errors in AJAX

 

AJAX has really changed the way we build web applications.When I surf internet today, I find almost all the websites Ajaxified in some way. Writing an AJAX application is as simple as writing simple JavaScript methods and some server side code.

I have been writing AJAX codes since a long time now and believe me tge most difficult part is to handle errors and exceptions. Session timeout is one of the most trivial error that one needs to consider while creating an AJAX enabled application.

Normally, we use AJAX to deliever HTML content that we put in a DIV or SPAN tag and display it on screen. But suppose the request that we sent using AJAX was generated an error due to session timeout then the session timeout screen will be shown in DIV tag. Any error generated by server let say http 404 error or http 505 can lead to display such error in our display DIV.

Handle Session timeout errors

One solution that you can use to handle the session timeout errors is using JSON or XML format as output for your AJAX requests. You have to check for session in your script, say for example if you are using JSP then probably you can do something like this:

 

if(null == session || session.getAttribute("SOME_ATTR_THAT_I_PLACED_IN_SESSION")) {
isSessionNull = true;
}
...
{
<%
if(isSessionNull) {
out.println("status: error");
}
else {
out.println("status: success");
}
%>
}

In short, create a status field in your JSON script or a status tag in your XML which will describe the status of the request.

I am looking for some more ways of checking session timeouts in AJAX. Kindly let me know if you have a good solution.

Handle Server HTTP errors in AJAX


HTTP errors like 404, 503 are sometimes tedious to handle using AJAX. There is a simple trick to solve this problem. First let us see simple AJAX handler function that we use to get response XML/text through AJAX.

 

xhr.open("GET", "http://someurl", true);
xhr.onreadystatechange = handleHttpResponse;
xhr.send(null);
...
...
function handleHttpResponse() {
if (xhr.readyState == 4) {
//handle response your way
spanBodyContent.innerHTML = xhr.responseText;
}
}

Normal AJAX handlers has a if to check readyState and if it is 4 (response arrived state) then we get the response from xhr.responseText or xhr.responseXML.

AJAX’s XMLHttpRequest object has attributes to check the status of your http request. You can use two attributes: status and statusText for knowing this.

xhr.status
..
xhr.statusText


Thus by checking status attribute from your AJAX xhr object can solve your problem.

xhr.open("GET", "http://someurl", true);
xhr.onreadystatechange = handleHttpResponse;
xhr.send(null);
...
...
function handleHttpResponse() {
if (xhr.readyState == 4) {
try {
if(xhr.status == 200) {
//handle response your way
spanBodyContent.innerHTML = xhr.responseText;
}
}catch(e) {//error}
}
}
Thus, if status is not 200, you may not want to update your DOM with the ajax result and display some error message on your web page.

Amazon Online Shopping with Web Service Framework for PHP

Introduction

phpIf you have done any on-line shopping, then you probably don't need an introduction to Amazon.com. But have you ever thought of writing your own application to make purchases on Amazon? In fact, you can do just that with the Amazon Web Services API. This tutorial guides you through writing a simple PHP application to access Amazon E-commerce Web services to do on-line shopping, using the Web Services Framework for PHP.

Table of Contents

 

Designing the PHP Class Library for Amazon

When writing a Web service application, it is a good practice to keep all of the Web service invocation logic in a separate layer and build the dependent logic on top of that. So, in this case we will create a class named 'AmazonClient' and contain all the Web services requests to the Amazon Web service in it.

First of all, create the skeleton of the class which would be filled by the operations as we go on through the tutorial.

<?php
class AmazonClient extends WSClient
{
const AMAZON_ENDPOINT = "http://webservices.amazon.com/onca/xml";

private $amazon_key;
private $amazon_service;


public function __construct($amazon_key)
{
parent::__construct(array(

"to"=>self::AMAZON_ENDPOINT ));
$this->amazon_key = $amazon_key;
$this->amazon_service = "AWSECommerceService";
}


/* the service operations to be implemented */

}
?>

So whoever uses this PHP class will only need to write the following bit of code. For example, to do an ItemSearch:

$amzon_client = new AmazonClient("your amazon key");
$amazon_client->ItemSearch();

Next, we will look at how to fill the class body with service operation invocations..


 


Using The SOAP API


As always, we will start our on-line shopping task by searching. For that, you can use Amazon's ItemSearch service operation.


ItemSearch operation requires a keyword and a Search Index as input parameters. In fact, the keyword will be your search query. Search Index is the item category you want to search, and hence needs be one of the values defined by Amazon. Some of the possible values are Books, Music, DVD, Software, Software Video Games and etc..


Here is our version of ItemSearch which just wraps the Amazon request for ItemSearch:

/**
* Search Web
* @param $query query string
* @param $catagory catagory to search
* @param $catagory page to search
* @return associate array consist of the response parameters
*/

public function ItemSearch($query, $catagory, $page = 1)

{
$req_payload = <<<XML
<ItemSearch xmlns="http://webservices.amazon.com/AWSECommerceService/2007-10-29">
<AWSAccessKeyId>19VBVF8C8HQQ0HTH7PR2</AWSAccessKeyId>
<Request>
<ResponseGroup>Medium</ResponseGroup>
<ItemPage>{$page}</ItemPage>
<Keywords>{$query}</Keywords>
<SearchIndex>{$catagory}</SearchIndex>
</Request>
</ItemSearch>
XML;
/* call the request method with the request payload */
$ret_message = $this->request($req_payload);
$simplexml = new SimpleXMLElement($ret_message->str);


$res = $simplexml->Items;

return $res;
}

You can test your code very easily with the following bit of code:

<?php
require_once("AmazonClient.php");
$amazon_client = new AmazonClient("your amazon key");


$items = $amazon_client->ItemSearch("Web Services", "Books");
foreach($items->Item as $item)

{
echo $item->ASIN.". ";
echo $item->ItemAttributes->Title. " - ";
echo $item->ItemAttributes->Author. "\n";

}
?>

You will find the detailed result se, that contains the information of the Books you searched for, like Book Title, Authors etc. Amazon returns many other fields that you may be interested in like the DetailPageURL ($item->DetailPageURL) of the item.


You may have noticed in the above code I have been echoing the "ASIN" of the item ($item->ASIN). ASIN is the unique identifier of the item used by Amazon. This is required to be remembered, since you will need it when you are adding items to the shopping cart.


After you've found the item you've been looking for, you may do a simple lookup on that particular item. For that, Amazon provides the ItemLookup operation. Here, by setting the request parameter 'ResponseGroup' to 'Large'. you will be able to access more information about the book, like people's reviews, impressions and so on.

/**
* ItemLookup
* @param $ASIN Amaxon Item Id
* @return associate array consist of the response parameters
*/

public function ItemLookup($ASIN)
{


$req_payload = <<<XML
<ItemLookup xmlns="http://webservices.amazon.com/AWSECommerceService/2007-10-29">
<AWSAccessKeyId>{$this->amazon_key}</AWSAccessKeyId>
<Request>
<ResponseGroup>Large</ResponseGroup>
<ItemId>{$ASIN}</ItemId>
<ReviewPage>1</ReviewPage>
</Request>
</ItemLookup>
XML;

$ret_message = $this->request($req_payload);
$simplexml = new SimpleXMLElement($ret_message->str);


$res = $simplexml->Items;

return $res;
}

You will be able to access this operation using the following lines of code:

/* we can use the same $amazon_client we created for the ItemSearch */
$lookups = $amazon_client->ItemLookup("0131488740");

echo $lookups->Item->ASIN.". ";

echo $lookups->Item->ItemAttributes->Title. " - ";
echo $lookups->Item->ItemAttributes->Author. "\n";

 


This way you will be able to retrieve a lot of interesting details of the item you want to buy, from your applicaiton. But if you feel that you may have missed something, you can simply put a link to the Item web page in Amazon.com by setting a hyperlink to the $lookups->Item-> DetailPageURL value inside the above code. After these operations, you will probably have enough information about the Item and may decide that you really want to buy this Item. In fact, you can put that Item to the virtual shopping cart through the Amazon 'CartCreate' operation. With this operation you can give one or more items you wish to add to the cart.

/**
* CartCreate
* @param $items array of items you wish to add to the new cart
* sould be a hash of "Product ASIN"=> "Quantity"
* @return associate array consist of the response parameters
*/

public function CartCreate(Array $items)

{

$items_xml = "";
foreach ($items as $asin => $quantity)

{
$items_xml .= <<<XML
<Item>
<ASIN>{$asin}</ASIN>
<Quantity>{$quantity}</Quantity>
</Item>

XML;
}
/* Create the request payload */
$req_payload = <<<XML
<CartCreate xmlns="http://webservices.amazon.com/AWSECommerceService/2007-10-29">

<AWSAccessKeyId>{$this->amazon_key}</AWSAccessKeyId>
<Request>
<Items>
$items_xml
</Items>
</Request>
</CartCreate>
XML;
/* call the request method with the request payload */
  $ret_message = $this->request($req_payload);
$simplexml = new SimpleXMLElement($ret_message->str);


$res = $simplexml-> Cart;

return $res;
}

Note that you are giving the items you want to buy in a hashmap with the mapping "Product ASIN"=> "Quantity". So the following code shows how you can create a cart and check the total price.

$cart = $amazon_client->CartCreate(array("0131488740" => 5));

echo $cart-> CartId." - ";
echo $cart->CartItems->SubTotal->FormattedPrice."\n";

echo $cart->PurchaseURL."\n";

From this you can retrieve the following information:




















Cart Id$cart-> CartIdThe Id of the cart you just created
HMAC$cart-> HMACSecurity Token which would be required in order to change the cart later
Purchase URL$cart->PurchaseURLYou can navigate to PurchaseURL to continue the rest of the transaction through the Amazon website..
CartItemId$cart->CartItems->CartItem[x]->CartItemIdThis exists for each cart item and is different from ASIN


Here you will need to keep the Cart Id, HMAC and CartItemId for each Item in order to modify or clear items in the cart. I will show you how you can implement it in your application with Amazon's CartModify and CartClear operations.

/**
* CartModify
* @param $cart_id id of the cart to modify..
* @param $HMAC security token for authentication..
* @param $items array of items you wish to change
* sould be a hash of "Cart Item Id"=> "Quantity"
* @return associate array consist of the response parameters
*/

public function CartModify($cart_id, $HMAC, Array $items)

{

$items_xml = "";
foreach ($items as $cart_item_id => $quantity)

{
$items_xml .= <<<XML
<Item>
<CartItemId>{$cart_item_id}</CartItemId>
<Quantity>{$quantity}</Quantity>
</Item>

XML;
}

/* create the request payload */
$req_payload = <<<XML
<CartModify xmlns="http://webservices.amazon.com/AWSECommerceService/2007-10-29">
<AWSAccessKeyId>{$this->amazon_key}</AWSAccessKeyId>
<Request>
<CartId>$cart_id</CartId>
<HMAC>$HMAC</HMAC>
<Items>
$items_xml
</Items>
</Request>
</CartModify>
XML;
/* call the request method with the request payload */
$ret_message = $this->request($req_payload);
$simplexml = new SimpleXMLElement($ret_message->str);


$res = $simplexml-> Cart;

return $res;
}
/**
* CartClear
* @param $cart_id id of the cart to modify..
* @param $HMAC security token for authentication..
* @return associate array consists of the response parameters
*/

public function CartClear($cart_id, $HMAC)
{


$req_payload = <<<XML
<CartClear xmlns="http://webservices.amazon.com/AWSECommerceService/2007-10-29">
<AWSAccessKeyId>{$this->amazon_key}</AWSAccessKeyId>
<Request>
<CartId>$cart_id</CartId>
<HMAC>$HMAC</HMAC>
</Request>
</CartClear>

XML;
/* call the request method with the request payload */   
$ret_message = $this->request($req_payload);
$simplexml = new SimpleXMLElement($ret_message->str);


$res = $simplexml;

return $res;
}

You will be able to modify or clear the cart you created earlier, using above operations in few lines of codes like the following:

$modified_cart_info = $amazon_client->CartModify("102-0208736-3675339", "lXOKkAyAVl6+/+D+KA3GvJRF4P0=", array("U181IPR3ATNL7R" => 3));


$cleared_cart_info = $amazon_client->CartClear("102-0208736-3675339", "lXOKkAyAVl6+/+D+KA3GvJRF4P0=");

Here I have put some fake values for HMACs, Card Ids and CartItemIds. Please use your own values here. (That is, you will be using the values retrieved from the CartCreate operation)


So that is all you need to write your own online shopping application. The next part of the tutorial is going to explain how to do the same thing in another way.


 


Using The REST API


The amazing thing about Amazon.com is that it provides Web services for both SOAP and REST consumers. And if you are using Web Service Framework for PHP you will be able to convert the SOAP consumer to a REST consumer with a very little change of code. But unfortunately with Amazon you may need to change all the request messages too, since their API for REST and SOAP are different. Now I will walk you through the same set of steps demonstrated above, but this time it will be using "REST" and not "SOAP".


The first and most important thing is to change the options of the WSClient constructor[4] which would be called inside the AmazonClient.

const AMAZON_ENDPOINT = "http://webservices.amazon.com/onca/xml";
parent::__construct(array(
"to"=>self::AMAZON_ENDPOINT,
"HTTPMethod"=>GET,
"useSOAP"=>FALSE));

Here, note the options given to the WSClient.












"to"This is the REST service endpoint of the Amazon ECommerce web service. This is different to the soap endpoint
"useSOAP" =>FALSEThis is where we tell the WSClient we are not interested in going with SOAP.
"HTTPMethod"=> "GET"We will use 'Get' method to do the queries

So that is the basic configuration you need to change to convert your SOAP consumer to a REST consumer. In addition to that you will need to change your request xml. For example, for the Item Search Operation your new (for REST) request will be like this.

<ItemSearch>
<Service>AWSECommerceService</Service>
<AWSAccessKeyId>{$this->amazon_key}</AWSAccessKeyId>

<Operation>ItemSearch</Operation>
<Keywords>{$query}</Keywords>
<SearchIndex>{$catagory}</SearchIndex>

<ItemPage>{$page}</ItemPage>
</ItemSearch>

As you can see in the 'REST' request all the XML elements can go only one level deeper. So the elements like Keywords, SearchIndex and ItemPage are taken away from "Request" element (which is where they were in the SOAP request) and put as immediate child of the ItemSearch. So the WSF/PHP engine will convert this in to the following HTTP request..

GET /onca/xml?Service=AWSECommerceService&AWSAccessKeyId='Your_amazon_key'&Operation=ItemSearch&Keywords='Your-Query'&SearchIndex=Books&ItemPage=1 HTTP/1.1

You will probably be thinking how can you give an array of elements to the 'REST' request. This kind of request messages are present in the Amazon E-Commerce service as well. (e.g. CartCreate, CartModify)


So next we will see how to invoke the 'CartCreate' operation with REST.

$i = 0;
$items_xml = "";
foreach ($items as $asin => $quantity)

{
$i ++;
$items_xml .= <<<XML
<Item.$i.ASIN>$asin</Item.$i.ASIN>
<Item.$i.Quantity>$quantity</Item.$i.Quantity>

XML;
}
/* call the request method with the request payload */       
$req_payload = <<<XML

<CartCreate>
<Service>AWSECommerceService</Service>
<AWSAccessKeyId>{$this->amazon_key}</AWSAccessKeyId>
<Operation>CartCreate</Operation>
$items_xml
</CartCreate>

XML;

So for a call like the following,

$cart = $amazon_client->CartCreate(array("0131488740" => 5, "0234323234" => 3));
the generated request message will be like,
         <CartCreate>
<Service>AWSECommerceService</Service>
<AWSAccessKeyId>your_amazon_key</AWSAccessKeyId>
<Operation>CartCreate</Operation>

<Item.1.ASIN>0131488740</Item.1.ASIN>
<Item.1.Quantity>5</Item.1.Quantity>

<Item.2.ASIN>0234323234</Item.2.ASIN>
<Item.2.Quantity>3</Item.2.Quantity>

</CartCreate>

which would be ultimately converted to a HTTP GET request with the following format.

GET /onca/xml?Service=AWSECommerceService&AWSAccessKeyId=your_amazon_key&Operation=CartCreate&Item.1.ASIN=0131488740&Item.1.Quantity=5&Item.2.ASIN=0234323234&Item.2.Quantity=3 HTTP/1.1

You may be wondering now how you should handle the 'REST' Reponse, and if that would be different from the way you handle the 'SOAP' Response? Fortunately, it is not. Both the payload of the SOAP response and that of the REST response have the same format. That means, you can use the same piece of code to handle the response in both 'SOAP' and 'REST' forms when you are using WSClient.


If you followed the tutorial fully, you will now have a PHP class which helps you to access Amazon Web services either in REST or SOAP form. If you want to improve the flexibility of your class by giving the class user an option to set which request format (from 'REST' and 'SOAP') they prefer, what you need to do is to simply add another parameter to your class constructor that specifies whether to use 'REST' or 'SOAP. Based on this constructor parameter, you can select the logic to be used when sending the request. So users of the class do not need to worry about the underlying message format after they initially construct the class.


 


Conclusion


This tutorial guided you to write a simple web service consumer for amazon.com services using WSO2 Web Service Framework for PHP (WSF/PHP). By writing a consumer for a popular public Web service, the simplicity of the use of WSF/PHP consumer API and it s ability to call both 'REST' and 'SOAP' services with a minimum amount of work is highlighted.


Resources



Author


Dimuthu Gamage is a Software Engineer at WSO2. He is a commiter of the Apache Web Service project and a developer of the WSF/PHP and WSF/Ruby projects.


dimuthu at wso2 dot com.


I wrote an article on "Amazon Online Shopping with Web Service Framework for PHP" for Oxygen Tank.
There I'm demonstrating how to write a simple client library to access Amazon Web Services and how to use that library to write your own application to do online shopping with Amazon.com
There I attached the Client library code and two sample applications, one very simple php command line application and the other much improved web application. Hope this will be useful to people who are interested in working with WSF/PHP.