Sitemap    
  Home Food Photographs IT Parenting Resources Learning  
JAVASCRIPT
jQuery validate form using ajax 1
jQuery validate form using ajax 2
jQuery validate form using ajax 2

1. Download jQuery
2. Copy it to your javascript folder in my case folder "js"
3. Create separate jsp for error messages
4. Add jQuery code to jsp or html
5. Add logic to display error after server call
6. Run

1: FormValidationAjax.java

Only change is request.getRequestDispatcher("/jsp/ajaxformerrors.jsp").forward(request, response);.
package com.company.servlet;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class FormValidationAjax extends HttpServlet {
  public void doGet(HttpServletRequest request,
  HttpServletResponse response)
  throws javax.servlet.ServletException,
  java.io.IOException
  {
    process(request, response);
  }

  public void doPost(HttpServletRequest request,
  HttpServletResponse response)
  throws javax.servlet.ServletException, java.io.IOException
  {
    process(request, response);
  }

  public void process(HttpServletRequest request,
  HttpServletResponse response)
  throws javax.servlet.ServletException,
  java.io.IOException
  {
    System.out.println("Inside FormValidationAjax::process()");
    String errorMsg = "";
    String param1 = request.getParameter("param1");
    String param2 = request.getParameter("param2");
    String param3 = request.getParameter("param3");

    if(param1.length() < 9)
    {
      errorMsg = errorMsg+"Param1 must be > 8"+"
"; } if(param2.length() < 9) { errorMsg = errorMsg+"Param2 must be > 8"+"
"; } if(param3.length() < 9) { errorMsg = errorMsg+"Param3 must be > 8"+"
"; } if("".equals(errorMsg)) { errorMsg = "Form submitted successfully"+"
"; } request.setAttribute("errorMsg", errorMsg); request.getRequestDispatcher("/jsp/ajaxformerrors.jsp").forward(request, response); } }

2: ajaxformerrors.jsp
<%
  String errorMsg = (String) request.getAttribute("errorMsg");
%>
<%=errorMsg%>

3: NEW ajaxform.jsp

Add jquery-1.4.2.min.js
Capture button click event
Call servlet/php using jQuery ajax function
Get data in success and add error message to div using html jQuery method
<%
  String ctx = request.getContextPath();
  String errorMsg = (String) request.getAttribute("errorMsg");
  if (errorMsg == null) {
    errorMsg = "";
  }
%>
<html>
<head>
<script type="text/javascript" src="<%=ctx%>/js/jquery-1.4.2.min.js"></script>
<script type="text/javascript">
$(function() {
    var vParam1 = $("input#param1").val();
    var vParam2 = $("input#param2").val();
    var vParam3 = $("input#param3").val();

    var dataString = 'param1='+ vParam1 + '&param2=' +
    				vParam2 + '&param3=' + vParam3;
  $(".button").click(function() {
    $.ajax
    ({
          type: "POST",
        url: "<%=ctx%>/FormValidationAjax",
          data: dataString,
          success:
          function(data)
          {
            $('#errorSpanId').html("<span style='color:red'>"+data+"</span>");
            //alert(data);
          }
       });
      return false;
  });
});


</script>
<title>/jsp/ajaxform.jsp</title>
</head>
<body>
<form name="FormValidationAjax" method="post"
  action="<%=ctx%>/FormValidationAjax">
<div id="errorSpanId" ></div>
<div>Param1 (length must be > 8):
<input type="text" value="abc"
  name="param1" id="param1" /></div>
<div>Param2 (length must be > 8):
<input type="text" value="def"
  name="param2" id="param2" /></div>
<div>Param3 (length must be > 8):
<input type="text" value="ghi"
  name="param3" id="param3" /></div>
<div><input type="submit" name="submit" class="button" id="submit_btn" value="Test" /></div>
</form>
</body>
</html>

Now launch page and add data and submit
URL: http://servername:port/context/jsp/ajaxform.jsp


Servlet validates data. Please note URL does not change after submit because it is an AJAX call

ADD TO DEL.ICIO.US ADD TO DIGG ADD TO FURL ADD TO REDDIT ADD TO STUMBLEUPON ADD TO TECHNORATI FAVORITES ADD TO SQUIDOO ADD TO YAHOO MYWEB ADD TO ASK ADD TO GOOGLE
Post your comments:
Your Name: 
Security check:
Your Comment: 1500 chars
clmkvwxz2010-08-24 00:03:15
Comment deleted by admin

Nisha2010-11-10 11:24:52
Thank u very much. its very useful. can u help me to directly call the serlvet user defined (ex. process() from the above example) method from the jsp file using same jquery ajax in struts1.2

Trupti2010-11-26 23:15:00
Ajax is just a way to call a servlet/action without submitting the page. So let us say your URL is something like /FormValidationAjax/insert which calls insert function in your action. Struts will need to know on which condition this insert function gets called. So probably you need to pass some parameter with it.
There are multiple examples using jQuery on my other website. Please take a look
http://www.javasqlsecurity.com/2010/10/struts2-spring3-hibernate-jquery-working-together/4/
url: "<%=request.getContextPath()%>/employee/"+insUpdDel,
type: "GET",
data: $("form").serialize()

Trupti2010-11-26 23:17:02
I think this will also help you
http://www.javasqlsecurity.com/2010/10/how-to-populate-a-form-when-jsp-is-called-first-time/
Using HttpServlet – set bean in request if request parameter is NULL

Latest
How to loop arraylist JAVA6 Syntax
How to iterrate through ArrayList and display multiple rows using for loop JAVA6 syntax..
Java JSP  2010-Oct-12
How to loop arraylist
How to iterrate through ArrayList and display multiple rows using for loop, JSTL tags..
Java JSP  2010-Oct-12
Consumer using JAX WS Dispatch API and DOM parser 1
Access/Consume Webservice using Servlet, JAX-WS Dispatch API dynamic client and parsing SOAP response using DOM parser...
Java Webservice  2010-Sep-20
Simple Java first CXF Webservice 4
Building Simple Java first CXF webservice using CXFServlet, Spring, jaxws:endpoint, @WebService, @SOAPBinding, @WebResult
Java Webservice  2010-Sep-19
Simple Java first CXF Webservice 3
Building Simple Java first CXF webservice using CXFServlet, Spring, jaxws:endpoint, @WebService, @SOAPBinding, @WebResult
Java Webservice  2010-Sep-18
Simple Java first CXF Webservice 1
Building Simple Java first CXF webservice using CXFServlet, Spring, jaxws:endpoint, @WebService, @SOAPBinding, @WebResult
Java Webservice  2010-Sep-18
Simple Java first CXF Webservice 2
Building Simple Java first CXF webservice using CXFServlet, Spring, jaxws:endpoint, @WebService, @SOAPBinding, @WebResult
Java Webservice  2010-Sep-18
Encoding special characters in userinput or on server
Encoding can be done either in Javascript or JAVA encodeURIComponent, escape, java.net.URLEncoder..
Java JSP  2010-Aug-09
Jstl fmt tag i18n formatdate formatcurrency
fmt:setBundle, native2ascii.exe, fmt:message, fmt:setLocale, fmt:formatDate, fmt:formatNumber type=currency..
Java JSP  2010-Aug-05
How to read and write a file
How to read and write a file java.io.BufferedReader,java.io.FileReader, InputStreamReader ...
Java J2SE  2010-Aug-04
jQuery validate form using ajax 2
How to validate/submit form using ajax and jQuery input#, ($.ajax)..
Javascript  2010-Jul-23
jQuery validate form using ajax 1
How to validate/submit form using ajax and jQuery ($.ajax)..
Javascript  2010-Jul-23
How to create datasource in RAD Websphere
Create JDBC provider, datasource and JAAS security setup, JDBC connection URLs
Servers Websphere  2010-Jul-08
Get Started 4
Struts2 framework structure, how various components fit together
Java Struts2  2010-Jul-07
How to populate a form when JSP is called first time
This is achieved throught setting bean in request, using frameworks like Struts2, Spring3..
Java JSP  2010-Jul-07
Spring3 And Hibernate 4
Spring3 and Hibernate 3.5.3 working together @Controller, @RequestMapping, @InitBinder, HibernateTransactionManager, LocalSessionFactoryBean, HibernateTemplate
Java Spring  2010-Jul-07