How to Perform AJAX Form Validation in
How to Perform AJAX Form Validation in
Oracle JDeveloper
1. Introduction – What is AJAX?
AJAX is an acronym that stands for Asynchronous JavaScript and XML. AJAX is a web development technique that allows a developer to update parts of a page without refreshing the entire document. AJAX makes use of XHTML, the DOM object model, and XML to make changes or to act on changes made to a page.
2. Disadvantages and Advantages of Using AJAX
AJAX has advantages:
• Ajax is easy to program and add to an application
• Quicker and more responsive than some applications
• AJAX can improve throughput of an application by validating a form before it is entered into the database (as opposed to verification during database processing).
• AJAX can help reduce bad data by validating the input before it is actually submitted.
AJAX also has some disadvantages:
• AJAX can become too complex.
• Updates to the processing code may require multiple page updates.
3. Methods of Form Validation in AJAX
There are three types of form validation in AJAX
• Pure JavaScript – Uses JavaScript functions to validate data. Limited in form processing mainly to preventing null values from being entered.
• PHP back-end Processing – Incorporates better string comparison methods. Requires that a separate installation of PHP and a PHP-enabled web server installed. In terms of JDeveloper, the PHP plug-in must also be installed to forward the requests to the PHP executable.
• Servlet back-end Processing – More intensive programming. String comparison is more difficult. Can be archived with the JSP/HTML form as a web application and re-deployed.
4. Create a New Application from the Applications Navigator.
[pic]
5. Create the Project:
[pic]
6. Creating the Index.jsp File
Right-Click on the Project and Choose ‘New’. From the Web Tier, choose ‘JSP’.
[pic]
7. Follow the JSP Creation Wizard.
Accept the defaults (including J2EE 1.4 and No error handling). JDeveloper opens the new JSP in the visual editor. Using the Component library ‘HTML-Forms’ section drag and drop a new form onto the page. Change the ‘Action’ and the ‘Name’ of the Form and select the ‘Post’ Method.
[pic]
8. Creating the Table
Once the form is created, use the HTML-Common Component Library to drop a table onto the newly created form. The table should be three columns wide two rows deep. Use the Property Inspector to set the ‘border’ to 0. The JSP Page should now look similar to this:
[pic]
9. Adding the Pieces
Type the Label ‘User ID’ into the 1st column, first row. Use the HTML-Forms Component Library to drop a text field into the 2nd column of the first row. For this text field, set the name to “id” and set the size to 20. Under the advanced properties tab, set the id to “userid” and change the JavaScript ‘onkeyup’ event to validateUserId().
[pic]
10. Adding the placeholder
Click inside the cell in the 3rd column, 1st row and select the ‘Source’ Tab. Add the
following code:
This code snippet tells AJAX where we want to change the page.
11. Adding the Submit button
Click back to the Design View and drop a button onto the 1st column, 2nd row. Set the value of the button to “Create Account”. Use the Advanced Properties tab to set the id to “submit_btn”. Verify that the page runs (JDeveloper will produce an error on any input, since we have not defined the JavaScript function yet, but make sure the page displays correctly). Save the Page (Save All).
[pic]
12. Adding the JavaScript functions
Using the Source tab again to add the functions. JavaScript functions typically go in between the and tags. The first two functions are the core of AJAX functionality:
function AJAXInteraction(url, callback) {
var req = init();
req.onreadystatechange = processRequest;
function init() {
if (window.XMLHttpRequest) {
return new XMLHttpRequest();
} else if (window.ActiveXObject) {
return new ActiveXObject("Microsoft.XMLHTTP");
}
}
function processRequest () {
// readyState of 4 signifies request is complete
if (req.readyState == 4) {
// status of 200 signifies sucessful HTTP call
if (req.status == 200) {
if (callback) callback(req.responseXML);
}
}
}
this.doGet = function() {
req.open("GET", url, true);
req.send(null);
}
}
Since Netscape and Microsoft use different XML parsers in their browsers, the first function creates the HTTPrequest object and sets it to the appropriate type of object based on what the browser’s window environment calls for. The second function checks to see that a) the request was completed (‘readyState=4’) and b) data (‘status=200’) was received. The processRequest function then uses the servlet’s ‘doGet’ section to process the input. Note that the third argument in the req.open call is set to ‘true’. This identifies that the request is asynchronous, meaning that it does not wait for further input from the user, and continues processing the data.
13. Adding the final two JavaScript functions
Add the functions that actually process the page:
function validateUserId() {
var target = document.getElementById("userid");
var url = "validate?id=" + encodeURIComponent(target.value);
var target = document.getElementById("userid");
var ajax = new AJAXInteraction(url, validateCallback);
ajax.doGet();
}
function validateCallback(responseXML) {
var msg = responseXML.getElementsByTagName("valid")[0].firstChild.nodeValue;
if (msg == "false"){
var mdiv = document.getElementById("userIdMessage");
mdiv.innerHTML = "Invalid User Id";
var submitBtn = document.getElementById("submit_btn");
submitBtn.disabled = true;
} else {
var mdiv = document.getElementById("userIdMessage");
mdiv.className = "bp_valid";
mdiv.innerHTML = "Valid User Id";
var submitBtn = document.getElementById("submit_btn");
submitBtn.disabled = false;
}
}
The validateUserId() is what starts the AJAX process. This function is called when a key is released from within the form on the page. The validateCallback function is called when a response is received from the XMLHttpRequest. This function modifies the form based on the response received from the servlet processing.
14. Save the File (‘Save All’)
15. Creating the Servlet
The last thing we have to do is create the Servlet to handle the processing. Right-click the project and select ‘New’. Choose “Servlet” from the Web Tier.
[pic]
16. Servlet Details
Name the servlet ‘validate’ (to match the JavaScript call and the action of the form). Choose both a ‘doGet’ method and a ‘doPost’ method.
[pic]
[pic]
17. Change the servlet code’s init, doPost, and doGet functions to match the following:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.util.*;
public class ValidationServlet extends HttpServlet {
private ServletContext context;
private HashMap accounts = new HashMap();
public void init(ServletConfig config) throws ServletException {
super.init(config);
this.context = config.getServletContext();
accounts.put("greg","account data");
accounts.put("duke","account data");
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
String targetId = request.getParameter("id");
if ((targetId != null) && !accounts.containsKey(targetId.trim())) {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("true");
} else {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("false");
}
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
String targetId = request.getParameter("id");
if ((targetId != null) && !accounts.containsKey(targetId.trim())) {
accounts.put(targetId.trim(), "account data");
request.setAttribute("targetId", targetId);
context.getRequestDispatcher("/success.jsp").forward(request, response);
} else {
context.getRequestDispatcher("/error.jsp").forward(request, response);
}
}
}
18. What this does
Upon execution, the servlet will initialize (if it has not already done this). During initialization it will create a Hashtable (to store the account data) and a Servlet Context. In this example, it pre-populates the account Hashtable with “greg” and “duke”. When the servlet is stopped, the default values are returned. After initialization, the servlet waits for a doGet or a doPost response.
The doGet will verify that the input does not equal any values in the hashtable. As long as the field evaluates to true (the input is not equal), it will send and XML tag with a value of “true”. When doGet evaluates to false, it responds with an XML tag of “false”. The doPost in this example simply forwards the reponse to a success or failure jsp. The doPost is called when the Submit button of the form is pressed. The data is added to the hashtable, and the browser is forwarded to the success or error JSP pages (which have not been created yet).
19. Creation of the JSP pages
Create a JSP page like step 6. In this example, the JSP pages are very simple. It is just a message that the account creation was successful. In a real world application, the servlet would forward to a CGI script or servlet that would go out and create the account or update a database for example. The success.jsp page should look something like:
Account Created
Your account was created Successfully!
Click here to go back
20. Running the Page.
Right-Click the Index.jsp and ‘Run’ the File. Note: This form processes each character, not just the full input. A ‘valid’ message is produced after each letter.
[pic]
[pic]
21. Success.
If everything works out correctly, the user is forwarded to the success.jsp file:
[pic]
References
Example adapted from “Real Time Form Validation with Ajax’. Greg Murray. 2006.
Ajax Descriptions and function explanation from Professional AJAX. Zakas, McPeak, Fawcett. 2006. Wiley Publishing.
................
................
In order to avoid copyright disputes, this page is only a partial summary.
To fulfill the demand for quickly locating and searching documents.
It is intelligent file search solution for home and business.
Related download
- using ajax
- using ajax professional
- how to perform ajax form validation in
- cs 412 study guidelines for the midterm exam
- valdosta state university
- answers to final exams exinfm
- answers to chapters 1 2 3 4 5 6 7 8 9 end of chapter
- tutorial using ajax and the google calendar api
- build restful apis with wcf web api
Related searches
- how to perform homans sign
- how to calculate 2 s complement in excel
- how to change standard form to slope
- how to perform satanic rituals
- how to perform business analysis
- how to say master s degree in spanish
- how to perform chest physiotherapy
- how to perform chest percussion
- how to know if you re in love
- how to insert today s date in excel
- how to get today s date in excel
- how to perform homans test