Implementing an Ajax Shopping Cart

an article added by: Sonja Lande at 06012007


In: Categories » » AJAX » Implementing an Ajax Shopping Cart

The focus of this article is to explain how to create aWeb application that implements a shopping cart. A shopping cart is a personal thing, yet it is available to everyone. This article goes through the problems of handling both personal and public data. This article discusses the following topics:

• Understanding the differences between a personal URL and a general URL

• Controlling access to a personal URL

• Knowing which HTTP verbs to use with a personal URL

• Using Asynchronous JavaScript and XML (Ajax) to retrieve a personal URL

Problem You want to implement a robust shopping cart in your Web application so that access of the data, which may be public or private, is consistent and straightforward.

Note This article discusses two examples: a shopping cart and a bank-account information display. Both examples illustrate the common problem of identity and personalization.

Theory When you go to a grocery store, you grab a shopping cart. The shopping cart is one of thousands of identical-looking shopping carts. No identifier on the shopping cart makes it distinguishable from another shopping cart. A shopping cart is not like a key, because a key is unique from another key due to its shape. The uniqueness of the shopping cart is defined not by the actual cart, but by the items that you place in the cart and plan to purchase.

In Europe, this uniqueness is critical because Europeans tend to shop in sections. They find a spot to park their shopping cart and then find what they need, carry those items back to the cart, and place them into the cart. They take a hunter-and-gatherer approach, where the prey is the food in the grocery store. There are literally hundreds of carts without owners, yet people don’t take the wrong cart, nor do they start taking things out of other people’s carts,1 nor do they walk away with somebody else’s cart on purpose. I say “on purpose” because people do occasionally walk 10 feet with somebody else’s cart before realizing, “Oops, these aren’t my items.” Looking at this from an abstract perspective, the shopping cart has become personalized, even though it becomes generic again when the person is done shopping. Web shopping carts are not implemented like shopping carts in real life.

On aWeb site, you can have only one shopping cart. In real life, you could walk around with multiple shopping carts (which, in fact, I’ve done). On aWeb site, you cannot hand off your shopping cart to another user. In real life, you can give your shopping cart to anybody. From a programmer’s perspective, a shopping cart on aWeb site is associated with a user and requires managing the details of an individual. In real life, from the perspective of a cashier, no personal information is exchanged. The reality of Web-based shopping carts is that they associate general data, such as which item is being purchased, with a specific user. Part of the problem with the current implementation of shopping carts is that Web applications cannot distinguish URLs from one other. Shopping carts are implemented using technologies that make shopping carts difficult to manage. Let’s look at another situation that is similar to a shopping cart. A bank account is similar to a shopping cart in that everybody can have an account, and the bank account can be manipulated the same way as a shopping cart. The big difference between a shopping cart and a bank account is that a bank account requires authorization.

Let’s say that a bank creates aWeb application that allows users to access their bank accounts from the Internet. Using current technologies, the application allows users to access their account using the same URL and then asks them to authenticate themselves. Based on the authentication, the users see whatever bank account information is associated with them.

A user can use only one data set, because there is no way for an administrator to exist: For example, a user with multiple accounts would not be able to access all the accounts, unless you write code that aggregates the controlled accounts. Using a unique URL with aWeb service, users can aggregate the accounts themselves.

Security is put into the hands of the Web application developer: The Web application developer must add barriers to ensure that only authorized people are allowed access to certain pieces of information. All too often, however, the barriers can result in security problems. HTTP security is well known, well defined, and stable, and those who manage it administrators are well aware of any security holes. Programmers, although capable and intelligent, are not security specialists.

Solution The solution to both the shopping cart and bank account problems is to use unique URLs. For example, the shopping cart URL might be /shoppingcart/12324, and the bank account might be /bankaccount/maryjane. Many people might balk at this solution, because it means each and every user will have unique URL, and managing unique URLs adds complexity. For example, imagine sending out an email that says, “Hey, buy this, and you’ll get credited with 1,000 points in your bank account.” You’re probably asking, “What URL will be sent in the email?”

Implementing Unique URLs Unique URLs can be determined ahead of time, or they can be generated dynamically. Generally speaking, you will be managing three URL types, defined as follows:

Root URL: The purpose of the root URL is to provide a context for the action and unique URLs. The root cannot be the action URL. Imagine a situation where you want to get a listing of all available shopping carts. If the root URL is the action URL, a unique URL would be returned whenever the root URL is queried.

Action URL: An action URL, such as /cart/retrieve, is the URL referenced by the client. Depending on the verbs supported, a reference to a unique URL is returned. In the case of the shopping cart, the only verb supported by the server is GET, which generates a unique URL when called. In the case of the bank account, the action URL supports the POST verb, which generates the unique URL when called. The verbs DELETE and PUT are not supported, because they have no meaning.

Unique URL: In the case of the shopping cart, an identifier URL such as /cart/12345 has a numeric identifier appended after the root URL of the shopping cart application. A unique URL does not need to have a numeric identifier appended, but it can be alphanumeric or some other identifier. A unique URL can support all HTTP verbs and depends entirely on the context. Each generated unique URL does not have to be identical in structure. For example, one application could use both URLs /cart/12234 and /big/cart/12/first. The uniquely generated URLs do not need to be tracked by the server, and often are the responsibility of the client. The server only needs to keep track of the unique URL for deletion purposes. For example, if the shopping cart has not been used for a certain period of time, the server deletes it. Algorithmically, the challenge lies in converting the action URL into a unique URL. One way of solving the problem is to create an HTTP request and then define the unique URL in the response. The HTTP 1.1 protocol provides the means to redirect the action URL to the unique URL. In HTTP protocol speak, this is called performing a redirection.

Understanding HTTP Redirection

HTTP redirection is a handshaking protocol. The client makes a request, and the server receives and processes the request. If the server indicates a redirection is in order, then an HTTP status code in the 300 range is returned. Upon receiving the 300-range status code, the client inspects the response and can take action by loading the redirected URL. The following is an example HTTP conversation that performs an HTTP redirection. As usual, a client makes an HTTP request:

   GET /resource/ HTTP/1.1
   Accept: */*
   Accept-Language: en
   Accept-Encoding: gzip, deflate
   User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac  OS X; en) 
   AppleWebKit/412.6.2 (KHTML, like Gecko)  Safari/412.2.2
   Connection: keep-alive
   Host: 192.168.1.242:8100
   The URL /resource is recognized by the HTTP server as a  generic URL that will redirect to
   a specific URL when called.  The HTTP server responds with an HTTP 302  to  indicate a redirection,
   as illustrated by the  following HTTP response:
   HTTP/1.1 302 Found
   Date: Tues, 05 Sep 2005 16:29:04 GMT
   Server: Apache/2.0.53 (Ubuntu)  PHP/4.3.10-10ubuntu4
   Location: /resource/joesmith
   Content-Length: 346
   Keep-Alive: timeout=15, max=100
   Connection: Keep-Alive
 Content-Type: text/html; charset=iso-8859-1

In the example, the specific URL sent to the client is defined as /resource/joesmith. When either aWeb browser or an XMLHttpRequest object receives a redirect, the client will recognize the redirect and attempt to retrieve the contents of the redirected URL, as illustrated by the following final request:

   GET /resource/joesmith HTTP/1.1
   Accept: */*
   Accept-Language: en
   Accept-Encoding: gzip, deflate
   User-Agent: Mozilla/5.0 (Macintosh; U; PPC Mac  OS X; en) 
   AppleWebKit/412.6.2 (KHTML, like Gecko)  Safari/412.2.2
   Connection: keep-alive
 Host: 192.168.1.242:8100

An HTTP redirection, whether executed by the Web browser or XMLHttpRequest, can be executed only if the redirection follows the same origin policy. If a redirection to another domain is attempted with XMLHttpRequest, the results vary. For example, Microsoft Internet Explorer returns a status code of 0 and no further data. Mozilla-based browsers return the status code 302 and the redirected URL.

Although using HTTP redirection can be effective, it can also be problematic from an Ajax perspective. When using the XMLHttpRequest object and calling a URL that generates a redirection, the redirected URL will be loaded automatically. This is bad because the script needs to know what the redirected URL is, but the XMLHttpRequest object doesn’t give that URL. Therefore, in the context of this article, you cannot use a 300-range HTTP status code.

legal notice

Our website is not responsible for the information contained by this article. Web-articles is a free articles resource.
Suggestion: If you need fresh, daily updated content for your website, feel free to use our service. Click here for more information.

Useful tools and features

link to this article    
If you like this article (tutorial), please link to it from your web page using the information above.

related articles

1. The Easiest Way to Get Started with Ajax and REST
The Easiest Way to Get Started with Ajax and REST Problem You want to know the best way to get started with writing Ajax and REST. Solution When developing an Ajax and REST application, you must decide on the tools and frameworks you’ll use. The choice is simple: Use whatever you’re using today, and write some Ajax applications. You don’t need to change the tools you’re using today. Whether you’re using ASP.NET, JavaServer Pages (JSP), PHP, Ruby, or Python, you...

2. Testing a Dynamic Contract with Ajax
Coding the Contract Using Test-Driven Development Techniques Coding the contract using agile and test-driven development techniques requires writing a number of tests and implementing aMock URL layer. Problem You want to code the contract using these development techniques. Solution To demonstrate, let’s define a use case, implement the use case as a contract, write a test case(s) to implement the contract, implement the contract in the Mock URL, and finally...

3. Testing the Client Side Logic
Problem You want to effectively test your application’s client-side logic. Theory Testing GUI code tends not to be a productive task because of the complications that arise. The main complication is how to test the correctness of a user interface. Imagine a situation where clicking a button causes a table to be filled with data. Now imagine that when a check box is checked and the button is clicked again, a different table is filled with content. The fact that clicking the same button results in two ...

4. Understanding JavaScript and Types
Understanding JavaScript and Types Problem You want to work around the fact that JavaScript does not have types declared for its variables. Theory JavaScript code does not have any variables with a declared type. The lack of typed variables is apparent when you declare functions. That said, not having typed variable declarations does not mean JavaScript has no types or no type safety. Let’s start out with the simple declaration of a function, as illustrated by the following ex...

5. Coding Using Conventions and Not Configurations
Coding Using Conventions and Not Configurations Problem You want to make your JavaScript constructs more efficient by applying the Rails “convention over configuration” principle to them. Theory You may already be familiar with the programming platform Ruby on Rails, which is used to build Web applications. The focus of this recipe is not Ruby on Rails, but one aspect of Ruby on Rails namely, convention over configuration (see http://en.wikipedia.org/wiki/ Ruby_on_Rails for m...

6. Advantage of parameterless functions in JavaScript
Using Parameterless Functions Problem You want to take advantage of parameterless functions in JavaScript. Theory JavaScript functions for the most part have parameters. You may think that the previous sentence states the obvious after all, without parameters, what data could be passed to a function? JavaScript has the ability to declare functions that have no parameters, even though the caller of the function has passed parameters to the function. For example, let’s look at...

7. JavaScripot Functions
Treating Functions Like Objects Problem You want to take advantage of the fact that functions are objects (remember, everything is an object in JavaScript). Theory Many people think that a function is some keyword used in JavaScript. A function is also an object that can be manipulated. Knowing that a function is an object makes it very interesting from the perspective of writing JavaScript code, because the code can treat the function like another other object. This mean...

8. Implementing an Error and Exception Handling Strategy
Implementing an Error and Exception Handling Strategy Problem You want to implement a clean error and exception handling strategy in your applications, to make them run more smoothly. Theory Of course, you might argue that one error is a dialog box and the other is generated in the JavaScript console. The fact that one browser uses a dialog box to show an error and the other does not is a browser issue, not an error issue. A concise way of classifying the two errors is to ...

9. Understanding the Behavior of Variables When Implementing Recursion
Understanding the Behavior of Variables When Implementing Recursion Problem You want to implement recursion in JavaScript, and you also want to understand how variables will behave under those circumstances. Theory In JavaScript, you do not need to declare the variable type, or even declare the variable. For example, the following code works perfectly: if( counter == 1) { buffer = "counter is 1"; } document.getEle...

10. Using Functions to Initialize and Make Decisions JavaScript
Using Functions to Initialize and Make Decisions Problem You want to use functions to initialize and make decisions. Theory Usually when you write a piece of code where a change of logic needs to take place based on a context, you use a decision structure. For example, say you are implementing a light switch using a program. You turn on the light if the light is off, and you turn off the light if the light is on. The behavior of the program is determined by the conditions. One example behavior t...