In my previous article I have explained about the very basic article about accessing file in the server using dojo/request. In this post, I would go further on passing the parameter values to the server and return the response that will be printed on the screen. Even this is not a advanced tutorial on using AJAX calls. It is intended for a beginner to learn how to send a simple parameter values to server and get the response. For advanced users can skip this article.You may read some good dojo tutorials published in JavaBeat.
DOJO AJAX Call Example Listing 1 – dojoajax.jsp
<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"> <title>Insert title here</title> <script> var dojoConfig = { baseUrl : "src", packages : [ { name : "dojo", location : "dojo" }, { name : "dijit", location : "dijit" }, { name : "dojox", location : "dojox" }, { name : "app", location : "app" }, ], parseOnLoad : true, async : true }; </script> <script src="src/dojo/dojo.js"></script> <script> require([ "dojo/dom", "dojo/on", "dojo/request", "dojo/dom-form" ], function(dom, on, request, domForm) { var form = dom.byId('frmNode'); on(form, "submit", function(evt) { evt.stopPropagation(); evt.preventDefault(); request.post("server.jsp", { data : domForm.toObject("frmNode"), timeout : 2000 }).then(function(response) { dom.byId('msg').innerHTML = response; }, function (error){ alert('error'); } ); }); }); </script> </head> <body> <div id="result"> <div> <label>Message:</label><span id="msg"></span> </div> </div> <form id="frmNode"> <div> <label>Username: </label><input type="text" name="username" /> </div> <div> <label>Password: </label><input type="password" name="password" /> </div> <button type="submit">Login</button> </form> </body> </html>
DOJO AJAX Call Example Listing 2 – server.jsp
<% String user = request.getParameter("username"); String pass = request.getParameter("password"); if (user.equals(pass)){ %> Success!! <% }else{ %> Fails!! <% } %>
First one is the mandatory parameters which takes the URL of the server resource. Compare to the previous example, this one uses the specific HTTP request methods for posting the details to the server. It supports the methods request.get, request.post, request.put and request.del.data attribute takes the key value pairs of values and post to the server.
The above example takes the input from the login screen and upon user clicking the submit button, the values are sent to server.jsp where the values are compared and returns a string value. That value will be printed on the screen. The entire process is through AJAX request. In my next example, I would be moving little advanced with using the handleAs attribute for accepting the different return values. The out on the screen looks like below.