0% found this document useful (0 votes)
156 views14 pages

How To Perform Ajax Form Validation in Oracle Jdeveloper: 1. Introduction - What Is Ajax?

This document provides instructions for creating an AJAX form validation application in Oracle JDeveloper. It involves 20 steps: 1) creating a new project and JSP file for the form, 2) adding form fields and JavaScript functions for validation, 3) creating a servlet to process the validation requests asynchronously, and 4) creating success/error JSP pages. The application demonstrates validating a user ID field using AJAX to check against a list in memory and update the form without reloading the page.

Uploaded by

Rama Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
156 views14 pages

How To Perform Ajax Form Validation in Oracle Jdeveloper: 1. Introduction - What Is Ajax?

This document provides instructions for creating an AJAX form validation application in Oracle JDeveloper. It involves 20 steps: 1) creating a new project and JSP file for the form, 2) adding form fields and JavaScript functions for validation, 3) creating a servlet to process the validation requests asynchronously, and 4) creating success/error JSP pages. The application demonstrates validating a user ID field using AJAX to check against a list in memory and update the form without reloading the page.

Uploaded by

Rama Krishna
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOC, PDF, TXT or read online on Scribd
You are on page 1/ 14

Lance Berry CIS 764 Fall 06

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.

Lance Berry CIS 764 Fall 06

4. Create a New Application from the Applications Navigator.

5. Create the Project:

Lance Berry CIS 764 Fall 06

6. Creating the Index.jsp File


Right-Click on the Project and Choose New. From the Web Tier, choose JSP.

Lance Berry CIS 764 Fall 06

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 HTMLForms section drag and drop a new form onto the page. Change the Action and
the Name of the Form and select the Post Method.

Lance Berry CIS 764 Fall 06

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:

Lance Berry CIS 764 Fall 06

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().

Lance Berry CIS 764 Fall 06

10. Adding the placeholder


Click inside the cell in the 3rd column, 1st row and select the Source Tab. Add the
following code:
<div id=userIdMessage></div>
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).

12. Adding the JavaScript functions


Using the Source tab again to add the functions. JavaScript functions typically go in
between the <head> and </head> tags. The first two functions are the core of AJAX
functionality:
<script type="text/javascript">
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) {

Lance Berry CIS 764 Fall 06

}
}

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 browsers 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 servlets 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.

Lance Berry CIS 764 Fall 06

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. Rightclick the project and select New. Choose Servlet from the Web Tier.

Lance Berry CIS 764 Fall 06

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.

Lance Berry CIS 764 Fall 06

17. Change the servlet codes init, doPost, and doGet functions to match
the following:
import
import
import
import

java.io.*;
javax.servlet.*;
javax.servlet.http.*;
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");

Lance Berry CIS 764 Fall 06

response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<valid>true</valid>");
} else {
response.setContentType("text/xml");
response.setHeader("Cache-Control", "no-cache");
response.getWriter().write("<valid>false</valid>");
}

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 <valid> tag
with a value of true. When doGet evaluates to false, it responds with an XML <valid>
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:
<body><h1>Account Created</h1>
<P>Your account was created Successfully!</P>
<P>Click <a href=index.jsp>here</a> to go back </P></body>

Lance Berry CIS 764 Fall 06

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.

Lance Berry CIS 764 Fall 06

21. Success.
If everything works out correctly, the user is forwarded to the success.jsp file:

References
Example adapted from Real Time Form Validation with Ajax. Greg
Murray. 2006.
http://java.sun.com/developer/technicalArticles/J2EE/AJAX/RealtimeValidation/
Ajax Descriptions and function explanation from Professional AJAX. Zakas,
McPeak, Fawcett. 2006. Wiley Publishing.

You might also like