Sunteți pe pagina 1din 14

AJAX and jQuery

CSCI 201
Principles of Software Development

Jeffrey Miller, Ph.D.


jeffrey.miller@usc.edu
Outline
• AJAX
• Program

USC CSCI 201L


AJAX
▪ AJAX stands for Asynchronous JavaScript and XML
▪ AJAX uses a combination of
› A browser built-in XMLHttpRequest object to request data from a web server
› JavaScript and HTML DOM to display the data
▪ AJAX allows for just part of a page to be reloaded with direct access
to the server
› There is another JavaScript API called fetch that performs similarly to AJAX

USC CSCI 201L 3/14


My First AJAX
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <script>
5 function loadDoc() {
6 var xhttp = new XMLHttpRequest();
7 xhttp.onreadystatechange = function() {
8 document.getElementById("demo").innerHTML = this.responseText;
9 };
10 xhttp.open("GET", "csci201.txt", true);
11 xhttp.send();
12 }
13 </script>
14 </head>
15 <body>
16 <div id="demo">
17 <h1>The Magic of AJAX</h1>
18 <button type="button" onclick="loadDoc()">Click To Be Amazed</button>
19 </div>
20 </body>
21 </html>

USC CSCI 201L 4/14


AJAX/JSP Form Validation
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>Sample Form</title>
5 <script>
6 function validate() {
7 var xhttp = new XMLHttpRequest();
8 xhttp.open("GET", "validate.jsp?fname=" + document.myform.fname.value +
9 "&lname=" + document.myform.lname.value, false);
10 xhttp.send();
11 if (xhttp.responseText.trim().length > 0) {
12 document.getElementById("formerror").innerHTML = xhttp.responseText;
13 return false;
14 }
15 return true;
16 }
17 </script>
18 </head>
19 <body>
20 <form name="myform" method="GET" action="form.jsp" onsubmit="return validate();">
21 <div id="formerror"></div>
22 First Name <input type="text" name="fname" /><br />
23 Last Name <input type="text" name="lname" /><br />
24 <input type="submit" name="submit" value="Submit" />
25 </form>
26 </body>
27 </html>

USC CSCI 201L 5/14


AJAX/JSP Form Validation
1 <%-- validate.jsp --%>
2 <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
3 pageEncoding="ISO-8859-1"%>
4 <%
5 String fname = request.getParameter("fname");
6 String lname = request.getParameter("lname");
7 System.out.println(fname + "." + lname);
8 if (fname == null || fname.length() == 0) {
9 %>
10 <font color="red"><strong>First name needs a value.</strong></font><br />
11 <%
12 }
13 if (lname == null || lname.length() == 0) {
14 %>
15 <font color="red"><strong>Last name needs a value.</strong></font><br />
16 <%
17 }
18 %>

USC CSCI 201L 6/14


AJAX/JSP Form Action
1 <%-- form.jsp --%>
2 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" %>
3 <!DOCTYPE html>
4 <html>
5 <head>
6 <title>Form Data Processing</title>
7 </head>
8 <body>
9 <%
10 String fname = request.getParameter("fname");
11 String lname = request.getParameter("lname");
12 %>
13 <h1>Submitted Data</h1>
14 First Name:<strong><%= fname %></strong><br />
15 Last Name:<strong><%= lname %></strong>
16 </body>
17 </html>

USC CSCI 201L 7/14


AJAX/Servlet Form Validation
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>AJAX Form</title>
5 <script>
6 function validateUsername() {
7 var xhttp = new XMLHttpRequest();
8 xhttp.open("POST", "Validate", true);
9 xhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
10 xhttp.onreadystatechange = function() {
11 document.getElementById("usernameMsg").innerHTML = this.responseText;
12 }
13 xhttp.send("field=username&username=" + document.myform.username.value);
14 }
15 function validatePassword() {
16 var xhttp = new XMLHttpRequest();
17 xhttp.open("GET", "Validate?field=password&password=" + document.myform.pass.value, true);
18 xhttp.onreadystatechange = function() {
19 document.getElementById("passwordMsg").innerHTML = this.responseText;
20 }
21 xhttp.send();
22 }
23 </script>
24 </head>
25 <body>
26 <form name="myform" action="SubmitServlet" method="POST">
27 Username <input type="text" name="username" value="jeff" onblur="validateUsername();"/>
28 <strong><div id="usernameMsg"></div></strong><br />
29 Password <input type="password" name="pass" value="test" onblur="validatePassword();"/>
30 <strong><div id="passwordMsg"></div></strong><br />
31 <input type="submit" name="submit" value="Authenticate" />
32 </form>
33 </body>
34 </html>

USC CSCI 201L 8/14


AJAX/Servlet Form Validation
1 @WebServlet("/Validate")
2 public class Validate extends HttpServlet {
3 private static final long serialVersionUID = 1L;
4
5 protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
6 String fieldToValidate = request.getParameter("field");
7 PrintWriter out = response.getWriter();
8 if(fieldToValidate != null && fieldToValidate.equals("username")) {
9 String username = request.getParameter("username");
10 if(username != null && username.length() > 0) {
11 out.println("Valid Username");
12 }
13 else {
14 out.println("Invalid Username");
15 }
16 }
17 if(fieldToValidate != null && fieldToValidate.equals("password")) {
18 String password = request.getParameter("password");
19 if(password != null && password.length() > 0) {
20 out.println("Valid Password");
21 }
22 else {
23 out.println("Invalid Password");
24 }
25 }
26 }
27 }

USC CSCI 201L 9/14


jQuery
▪ Description from jQuery website

› You need to include a .js file in your code, and then jQuery can be used
› http://jquery.com

10/14
jQuery/Servlet Form Validation
1 <!DOCTYPE html>
2 <html>
3 <head>
4 <title>AJAX Form</title>
5 <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
6 <script>
7 function validateUsername() {
8 $.ajax({
9 url: "Validate",
10 data: {
11 username: document.myform.username.value,
12 field: "username"
13 },
14 success: function( result ) {
15 $( "#usernameMsg").html(result);
16 }
17 });
18 }
19 function validatePassword() {
20 $.ajax({
21 url: "Validate",
22 data: {
23 password: document.myform.pass.value,
24 field: "password"
25 },
26 success: function( result ) {
27 $( "#passwordMsg").html(result);
28 }
29 });
30 }
31 </script>
32 </head>
33 <body>
34 <form name="myform" action="SubmitServlet" method="POST">
35 Username <input type="text" name="username" value="jeff" onblur="validateUsername();"/>
36 <strong><div id="usernameMsg"></div></strong>
37 <br />
38 Password <input type="password" name="pass" value="test" onblur="validatePassword();"/>
39 <strong><div id="passwordMsg"></div></strong>
40 <br />
41 <input type="submit" name="submit" value="Authenticate" />
42 </form>
43 </body>
44 </html>

USC CSCI 201L 11/14


More AJAX
▪ For more information on AJAX
› Go to http://www.w3schools.com/js/js_ajax_intro.asp
› View the source of any web page to see the JavaScript that was
used on that page
› Go through one of many tutorials you find online

12/14
Outline
• AJAX
• Program

USC CSCI 201L


Program
▪ Write a program that validates the form based on rules for different types of fields, but
have it to do this through AJAX without submitting the form if there are any errors
› Email should have an @ with at least one . After
› Passwords should be at least 8 characters long with at least 1 number
› Birthday must be a date in the past
› New Student must have one option selected
› College must have a value
› Favorite color must have a value other than Black
› Terms and Conditions must be checked
▪ Do not allow the form to be submitted
otherwise.
▪ Put a message next to each field that is not
formatted correctly

• Program USC CSCI 201L 14/14

S-ar putea să vă placă și