In: Categories » Computers and technology » AJAX » AJAX Fallback Option 2 ~ Sending a Request Using a Cookie
|
You can transfer data to your server using cookies, but any implementation using them will be severely limited. Cookies have a maximum size of 4k, and each domain can set only 20 of them, which means that each request is going to be size-limited. Cookie-based AJAX is most useful when your site is designed for it, because its limitations make it hard to use it as a fallback. The basic functionality is provided by setting a cookie, loading an image, and then polling on an interval while waiting for the response to appear. The implementation is simple; to do something besides alerting the contents of the result, you just set your own custom onComplete event handler. An example where the server returns the input and the number of times it has been called is shown in the following 2 listings. The example's JavaScript is shown in Listing 1 and the PHP code, which reads the cookie and then sets a response, is shown in Listing 2. Listing 1- Cookie-Powered AJAX
In Listing 1, the cookie-powered AJAX functionality is wrapped inside the JavaScript class CookieRequest. Requests to the server are made with the call method (lines 11-19). The call method takes a URL to which to send the request. It also takes a payload (the content we want to send to the server), which is sent in the request cookie. The method then uses the setCookie method to set a cookie named CR (line 14); it then creates a new Image object and sets its src to the requested URL (line 15). The method finishes by starting a timer, which runs the read method every 500 milliseconds. The read method (lines 2038) checks for the presence of the CR cookie (lines 2324). If it exists, the data in it is passed to the onComplete method (line 26). If the data isn't present, we check for errors; this is done by comparing the number of checks we've completed against the max checks set in the attempts property (line 31). If there is an error, the onError method is called (line 32). If no error is present, we start another timer to do the next check (lines 34-35). Lines 39-44 contain methods that you'll override when using the class. The onComplete method is called when data is successfully loaded. This is the equivalent of the callback property in the HttpClient class. The onError method is called if the request doesn't complete successfully; of course, you could leave this as an alert, but, in most cases, you'll want to provide a more understandable error message to your users or even retry the request. The CookieRequest class also contains helper methods for dealing with getting and setting cookies. setCookie (lines 45-49) works by setting the value of document.cookie to a urlencoded string in the format of cookie name=value. getCookie (lines 50-59) works by splitting document.cookie into one part for each cookie (the cookies are separated by ";") and then looping over these parts looking for a cookie with the specified name. If a matching name is found, the value is returned; otherwise, false is returned. The PHP page that is used with Listing1 is shown in Listing2. It is used as the URL in the call method and processes the payload that is set; it then sets a response for read to grab. Listing 2 - PHP Server Page for Handling a Cookie AJAX Request
This PHP code provides the basic functionality needed to interact with cookie-based AJAX requests. It uses PHP sessions to store a counter and increments it as each request is made. As you extend this code, you could use different PHP pages to decide which action to perform, or you could include that information in the cookie that is sent from the client. Lines 2-5 handle basic session setup, setting the counter to 0 if this is the first call. Lines 6-10 handle the checking of the client cookie and the sending of the response. This is done by setting a cookie that then will be sent with the response (line 8-9). If you want to handle large server responses, you would need to include code to split the data among multiple cookies.
|
legal disclaimer
1) Our website is not responsible for the information contained by this article as well for any and all copyright infringements by authors and writers. E-articles is a free information resource. If you suspect this article for any copyright infringements, please read the Terms of service and contact us to investigate the problem.
2) The E-articles directory team is not responsible for inaccuracies, falsehoods, or any other types of misinformation this tutorial may contain and will not be liable for any loss or damage suffered by a user through the user's reliance on the information gained here. Please read the Terms of service
Useful tools and features
related articles
The company I work for, Uversa Inc., is based around General Public License (GPL) software, so when I pick any library, it first needs to be compatible with the GPL. Because the GPL is so widespread, many licenses are compatible with it. (See www.fsf.org/licensing/licenses/index_html#GPLCompatibleLicenses for more information.) However, because licensing is a hard rule, you should always start your search by limiting it to the ones th...
2. Goals of AJAX
First and foremost, AJAX is about improving user experience; user experience improvements fall into two categories: making current tasks easier and making previously impossible tasks possible. Obviously, it is easier to focus on making current tasks easier. In Web development environments, this can be further broken down into two main goals: increasing interactivity and decreasing the time required to perform a task. In nonintranet cases, you may also have a related technical goal of reducing bandwidth use; by transferring less...
3. XMLHttpRequest Overview
Originally, Microsoft designed XMLHttpRequest to allow Internet Explorer (IE) to load XML documents from JavaScript. Even though it has XML in its name, XMLHttpRequest really is a generic HTTP client for JavaScript. With it, JavaScript can make GET and POST HTTP requests. (For POST requests, data can be sent to the server in a format of your choosing.) The main limitations to XMLHttpRequest are due to the browser security sandbox. It can make only HTTP(S) requests (file URLs, for example, won't work), and it can make requests o...
4. Promises and Problems of Combining AJAX with Other New Technologies
As you work with AJAX, you may hear of related technologies that you can use with AJAX. They fit into two main groups: mature technologies that are widely available in many browsers today, and new technologies that are available only on a specific browser. The mature technologies include Java and Flash. (Flash is the most important because its plug-in is widely installed, and its design is optimized for providing interactive elements and animations to Web sites.) Java can also be used to add interactivity to sites, but its popula...
JavaScript is a powerful scripting language, but deserved or undeserved, it has gained a bad reputation. If you take some time to look at JavaScript with a fresh eye, you will notice that most of its problems no longer exist. The core language is now standardized with the European Computer Manufacturer's Association (ECMA) standards group and is supported on all modern browsers. Of course, these browsers also support older proprietary syntaxes, and you should avoid these as much as possible. Keeping to the standardized interfac...
6. What Is Ajax
Ajax stands for Asynchronous Javascript And XML. Although strictly speaking Ajax itself is not a technology, it mixes well-known programming techniques in an uncommon way to enable web developers to build Internet applications with much more appealing user interfaces than those to which we have become accustomed. When using popular desktop applications, we expect the results of our work to be made available immediately, without fuss, and without us having to wait for the whole screen to be redrawn by the program. While us...
7. Integrating AJAX into a Framework
Whether you're planning to add only a few simple AJAX features or use AJAX throughout your site, integrating it into your current Web site design is a must. The more formal the framework, the harder the process isespecially if your framework provides a front controller that is heavily optimized for generating HTML. Frameworks without a front controller have an easier time incorporating AJAX because they can add a new entry point just for AJAX; many AJAX Remote Procedure Call (RPC) implementations provide code to help do this....
8. Technologies of AJAX
If you search the Internet for AJAX, you are likely to notice a large number of items popping up under the AJAX name that don't seem to fit my definition. In most cases, these libraries provide the related functionality needed to finish your AJAX application, but other times, these libraries are just someone trying to jump on the AJAX bandwagon. When looking at these libraries and techniques, I divide them into three groups: Those directly used in AJAX Those closely related to AJAX ...
9. Cross Browser XMLHttpRequest
One of the attributes that have made XMLHttpRequest such a popular transport for AJAX requests is that it is easy to use in a way that is compatible across multiple browsers. The big two browsers, IE and Firefox, provide the same basic API. This consistency makes for a similar development experience. Opera and Safari also support the same basic API, but only in their more recent versions. When you are writing cross-browser, the first problem you need to overcome is that XMLHttpRequest is an ActiveX object in IE, and it's ...










