AJAX and REST

The following introduction shows how the Barracuda server is used in designing AJAX and RESTful web-services.

AJAX

The AJAX example below
runs on our online server.

An Ajax web application retrieves data from the server asynchronously in the background without interfering with the display and behavior of the existing page. Ajax applications are typically designed for enhancing standard web-applications and are designed to gracefully degrade to a standard web application when the browser does not support JavaScript or if JavaScript is disabled.

In the following example, a basic calculator is designed as a standard web application, and we will later enhance this calculator by using Ajax. To keep it simple, the calculator will be designed to add two numbers only.

   1   
<?lsp 2 3 local var1 4 local var2 5 local result = "" 6 7 -- Fetch all URL encoded (POST'ed form) data sent from client as a Lua table. 8 local d = request:data() 9 if d.var1 and d.var2 then -- If client sends data 10 -- Convert URL encoded data to numbers 11 var1 = tonumber(d.var1) 12 var2 = tonumber(d.var2) 13 -- var1 and/or var2 are nil if data could not be converted to a number. 14 -- Set result = var1+var2 if var1 and var2 are OK, otherwise set result to 15 -- "???" 16 result = var1 and var2 and (var1+var2) or "???" 17 end 18 -- Else, a standard browser GET 19 20 ?>
21 <html> 22 <head> 23 <title>Addition</title> 24 </head> 25 <body> 26 <form method="post"> 27 <input type="text" name="var1" value="<?lsp=var1 and var1 or ""?>"/> 28 + 29 <input type="text" name="var2" value="<?lsp=var2 and var2 or ""?>"/> 30 = <span id="result"><?lsp=result?></span> 31 <br/> 32 <input type="submit" value="Submit"/> 33 </form> 34 </body> 35 </html>

The html form starts on line 26 and ends on line 33. The user enters a number into the two text fields (line 27 and 29). The data is sent as URL encoded data to the server when the user presses the submit button on line 32. The URL-encoded data for the above form is sent as: var1=10&var2=11, where 10 and 11 are numbers entered into the text fields.

Lua script code starting on line 1 and ending on line 20 is executed by the server every time the browser sends a request to the LSP page. If the browser sends the two URL-encoded variables var1 and var2, line 9 to 17 in the above code is executed on the server. The server side code extracts the variables and converts the variables to numbers.

The "result" is dynamically inserted into the generated HTML on line 30. We also update the value attributes on line 27 and 29. Updating the value fields make the input variables persistent -- i.e. the HTML code returned in response to a "browser POST request" have the text fields set to the previous value.

Lets's go ahead and enhance the web-application using Ajax, but at the same time, make sure the application still works when JavaScript is disabled in the browser.

   1   
<?lsp 2 3 local var1 4 local var2 5 local result = "" 6 7 -- Fetch all URL encoded (POST'ed form) data sent from the browser. 8 -- The data, if any, is returned as a Lua table. 9 local d = request:data() 10 if d.var1 and d.var2 then -- If browser sent data to server 11 -- Convert URL encoded data (strings) to numbers 12 var1 = tonumber(d.var1) 13 var2 = tonumber(d.var2) 14 -- var1 and/or var2 are nil if data could not be converted to a number. 15 -- Set result = var1+var2 if var1 and var2 are OK, 16 -- otherwise set result to "???" 17 result = var1 and var2 and (var1+var2) or "???" 18 19 -- Is this a standard POST or is this an AJAX call? 20 if request:header"x-requested-with" == "XMLHttpRequest" then 21 -- YES, AJAX call. 22 response:write(json.encode({result=result})) 23 return -- We are done. 24 end 25 -- Fall through if not AJAX call, i.e. if standard POST. 26 end 27 -- Else, a standard browser GET 28 29 ?>
30 <html> 31 <head> 32 <script type="text/javascript" src="/rtl/jquery.js"></script> 33 <script type="text/javascript"> 34 35 /* Extract the two elements var1 and var2 from the html form and send 36 * the data to server. 37 */ 38 function sendAJAX() 39 { 40 // The data sent to the server looks like a standard browser POST message. 41 var urlEncData = { 42 var1:$("input[name='var1']").val(), // var1 = value of html input var1 43 var2:$("input[name='var2']").val() 44 }; 45 /* The AJAX call. Note that we use an anonymous function for the 46 * asynchronous response. 47 */ 48 $.getJSON(location.href , urlEncData, function(json) { 49 /* This asynchronous callback function is triggered when the 50 * server sends the JSON response data. Convert the 'result' 51 * number to a string and set the data for the html span 52 * element. 53 */ 54 $("#result").html(json.result+""); 55 }); 56 }; 57 58 /* Called when user clicks the submit button. 59 */ 60 function submit() 61 { 62 sendAJAX(); 63 // Prevents browser from sending a standard POST request to the server. 64 return false; 65 }; 66 67 68 $(function() { 69 // Bind the submit function to the html form "submit" button. 70 $("input[type='submit']").click(submit); 71 /* Bind the sendAJAX function to the change and keyup elements in 72 * the form. This creates a realtime update of the "result" value 73 * -- i.e. AJAX calls are issued for each change of the input 74 * elements. 75 */ 76 $("input[type='text']").change(sendAJAX).keyup(sendAJAX); 77 }); 78 </script> 79 </head> 80 <body> 81 <form method="post"> 82 <input type="text" name="var1" value="<?lsp=var1 and var1 or ""?>"/> 83 + 84 <input type="text" name="var2" value="<?lsp=var2 and var2 or ""?>"/> 85 = <span id="result"><?lsp=result?></span> 86 <br/> 87 <input type="submit" value="Submit"/> 88 </form> 89 </body> 00 </html>

If you take a look at the above code, you will see that we have not changed the original code, but we have added additional code. The new Lua code starts on line 20 and ends on line 24. The bulk of the new code is the added JavaScript code that is executed by the browser as soon as the page is loaded. The code starts on line 32 and ends on line 78.

It is common to send Ajax data from the browser to the client as URL-encoded data. The server side code for extracting the URL-encoded data and calculating the result (line 12-17) can therefore be used as it was in the original page. The new Lua code starting on line 20 checks if the request is from an Ajax call. If it is, the result is assembled into a Lua table, converted to JSON, and sent to the browser.

The JavaScript code starting on line 48 uses the JQuery function $.getJSON for sending the XMLHttpRequest to the server. The second parameter to $.getJSON is a JavaScript table that automatically converts to URL-encoded data by $.getJSON. The asynchronous callback function extracts the JSON encoded data sent from the server and updates the display with the result.

Notice how we extract data from the text fields on line 42 and 43 by using JQuery selectors. We use the data to create a JavaScript table that is sent as URL-encoded data to the server.

The code starting on line 68 uses the JQuery ready event to automatically execute the code at startup when the page is loaded by the browser.

We use JQuery selectors on line 76 to bind event functions to the two text input fields. The change event is fired every time the fields are changed and the keyup is fired when the keybord key is released. We bind a click event to the submit button on line 70. The submit function returns false after the Ajax call is activated, thus preventing the browser from sending the form data to the server. Binding the click event function to the submit button will not work if JavaScript is disabled and the form gracefully degrades to a standard web-form.

RESTful Web-Services

RESTful web-services can easily be designed using the directory type. The getting started guide includes an example of how one can create RESTful web-services and use logical URL's.