2.6. Fallback Option 2: Sending a Request Using a Cookie
Listing 2-7. Cookie-Powered AJAX
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 3435).
Lines 3944 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 4549) works by setting the value of document.cookie to a urlencoded string in the format of cookie name=value. getCookie (lines 5059) 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 Listing 2-7 is shown in Listing 2-8. 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-8. 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 25 handle basic session setup, setting the counter to 0 if this is the first call. Lines 610 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 89). If you want to handle large server responses, you would need to include code to split the data among multiple cookies.