Monday 28 February 2011

Simple CRUD with JQuery-4

The underlying mechanism to be used as database is the Data Access Object.
It is defined in the source Packages.daoPackage
daoPackage.PersonDAO.java
-------------------------
package daoPackage;

import java.util.Collection;
import mainPackage.*;

public interface PersonDAO {

public void createRec(int id, String firstName,
String lastName, String hobby)
throws PersonDAOSysException;

public Person readRec(int personId)
throws PersonDAOSysException;

public void updateRec(int id, String firstName,
String lastName, String hobby)
throws PersonDAOSysException;

public void deleteRec(int personId)
throws PersonDAOSysException;
}

daoPackage.PersonDAOSysException
--------------------------------
package daoPackage;

public class PersonDAOSysException extends RuntimeException {
public PersonDAOSysException (String str) {
super(str);
}
public PersonDAOSysException () {
super();
}
}

daoPackage.PersonDAOVectorImpl.java
-----------------------------------
package daoPackage;

import java.util.*;
import javax.naming.*;
import java.sql.*;
import javax.sql.*;
import mainPackage.*;

public class PersonDAOVectorImpl implements PersonDAO {

private static Vector<Person> personVect;
private static int personNextId = 1;
private static int personCurrentId = 1;

public PersonDAOVectorImpl() {
System.out.println("PersonDAOVectorImpl constructor began.");
//check if it exists as serialized
//if not
// personelVectDB.populate();
// if it exists deserialize and populate?
// personelVectDB.deserialize();

personVect = new Vector<Person>();
Person personalData;

personalData = new Person();
personalData.setId(1);
personalData.setName("Ali");
personalData.setLast("SARAL");
personalData.setHobby("Music Composition");
personVect.add(personalData);

personalData = new Person();
personalData.setId(2);
personalData.setName("Tamer");
personalData.setLast("ÜNAL");
personalData.setHobby("Folk Music");
personVect.add(personalData);

personalData = new Person();
personalData.setId(3);
personalData.setName("Ekrem");
personalData.setLast("CANBEK");
personalData.setHobby("Violin");
personVect.add(personalData);

personalData = new Person();
personalData.setId(4);
personalData.setName("Turan");
personalData.setLast("MUTLUAY");
personalData.setHobby("Choir");
personVect.add(personalData);

personalData = new Person();
personalData.setId(5);
personalData.setName("Rengin");
personalData.setLast("AHISKALI");
personalData.setHobby("Literature");
personVect.add(personalData);

Enumeration vEnum = personVect.elements();
while (vEnum.hasMoreElements()) {
Person person = (Person) vEnum.nextElement();
System.out.println("ARSmsg: PersonDAOVectorImpl constructor person.name=" + person.getName() + " person.id=" + person.getId());
}

personNextId = 6;
personCurrentId = 1;
}

public void createRec(int id, String firstName, String lastName, String hobby)
throws PersonDAOSysException {
System.out.println("ARSmsg : createRec began.");
Person person = new Person();
try {
//getDBConnection();
person.setId(id);
person.setName(firstName);
person.setLast(lastName);
person.setHobby(hobby);
personVect.add(personVect.size(), person);
personCurrentId = personNextId;
personNextId++;
} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
} finally {
//closeDBConnection();
}
}

public void deleteRec(int personId) throws PersonDAOSysException {
System.out.println("ARSmsg : deleteRec began.");
int posVect = 0;
try {
//getDBConnection();
posVect = findRecSeq(personId);
System.out.println("personCurrentId=" + personCurrentId);
System.out.println("posVect=" + posVect);
if (posVect != -1) {
personVect.removeElementAt(posVect);
reorganiseVect();
} else {
System.out.println("ARSmsg: Delete - Not found!");
}
} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
} finally {
closeDBConnection();
}
}

public Person readRec(int personId)
throws PersonDAOSysException {
System.out.println("ARSmsg : readRec began.");
Person person = new Person();
int posVect = 0;
try {
//getDBConnection();
posVect = findRecSeq(personId);
System.out.println("personCurrentId=" + personCurrentId);
System.out.println("posVect=" + posVect);
if (posVect == -1) {
posVect = personCurrentId;
} else {
personCurrentId = posVect + 1;
}

return personVect.elementAt(posVect);
} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
} finally {
//closeDBConnection();
}
}

public Person readNextRec()
throws PersonDAOSysException {
System.out.println("ARSmsg : readNextRec began.");
Person person = new Person();
int posVect = 0;
try {
//getDBConnection();
personCurrentId++;
posVect = findRecSeq(personCurrentId);
System.out.println("personCurrentId=" + personCurrentId);
System.out.println("posVect=" + posVect);
if (posVect == -1) {
posVect = personVect.size() - 1;
personCurrentId--;
}
person = (Person) personVect.elementAt(posVect);
System.out.println("readNextRec person.name =" + (String) person.getName());
return person;

} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
} finally {
//closeDBConnection();
}
}

public Person readPrevRec() throws PersonDAOSysException {
System.out.println("ARSmsg : readPrevRec began.");
Person person = new Person();
int posVect = 0;
try {
//getDBConnection();
personCurrentId--;
posVect = findRecSeq(personCurrentId);
System.out.println("personCurrentId=" + personCurrentId);
System.out.println("posVect=" + posVect);
if (posVect == -1) {
posVect = 0;
personCurrentId++;
}
person = (Person) personVect.elementAt(posVect);
System.out.println("readPrevRec person.name =" + (String) person.getName());
return person;

} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
} finally {
//closeDBConnection();
}
}

public void updateRec(int id, String firstName, String lastName,
String hobby) throws PersonDAOSysException {
System.out.println("ARSmsg : updateRec began.");
int posVect = 0;
Person person = new Person();

try {
//getDBConnection();

posVect = findRecSeq(id);
System.out.println("personNextId=" + personNextId);
System.out.println("posVect=" + posVect);
if (posVect == -1) {
posVect = personNextId - 1;
personNextId++;
}
else {
personVect.remove(posVect);
}
System.out.println("posVect=" + posVect);

person.setId(id);
person.setName(firstName);
person.setLast(lastName);
person.setHobby(hobby);
personVect.add(posVect, person);
} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
} finally {
closeDBConnection();
}
}

private int findRecSeq(int id) {
int posVect = 0;
Person person;
Iterator itr = personVect.iterator();
while (itr.hasNext()) {
person = (Person) itr.next();
//System.out.println("person.name=" + person.getName() + " person.id=" + person.getId());
if (person.getId() == id) {
return posVect;
}
posVect = posVect + 1;
}
return (-1);
}

private void reorganiseVect() {
int posVect = 0;
Person person;
Iterator itr = personVect.iterator();
while (itr.hasNext()) {
person = (Person) itr.next();
person.setId(posVect + 1);
posVect = posVect + 1;
}
personNextId = posVect + 1;
//personCurrentId = 1;
}

private void getDBConnection() throws PersonDAOSysException {
try {
if (personVect == null) {
//personVect = new Personel();
}
} catch (Exception ex) {
throw new PersonDAOSysException("\\DAOException:" + ex.getMessage() + " " + ex.toString());
}
}

private void closeDBConnection()
throws PersonDAOSysException {
try {
//personelVectDB.close();
} catch (Exception ex) {
throw new PersonDAOSysException("DAOException:" + ex.getMessage());
}
}

public Vector<Person> getPersonVect() {
return personVect;
}

public void addPerson(Person personalData) {
personVect.add(personalData);
personNextId++;
}

public int getPersonNextId() {
return personNextId;
}

public int getPersonCurrentId() {
return personCurrentId;
}
}


The daoPackage uses the Person.java definition as record definition and
it is located in the source Packages.mainPackage
mainPackage.Person.java
-----------------------

package mainPackage;

/**
*
* @author Ali Riza SARAL
*/
public class Person {

private String name;
private String last;
private String hobby;
private int id;

public Person(){}
public Person(int id, String name, String last, String hobby){
this.name = name;
this.last = last;
this.hobby = hobby;
this.id = id;
}
public String getName() {
return this.name;
}

public void setName(String name) {
this.name = name;
}

public String getLast() {
return this.last;
}

public void setLast(String last) {
this.last = last;
}

public String getHobby() {
return this.hobby;
}

public void setHobby(String hobby) {
this.hobby = hobby;
}

public int getId() {
return this.id;
}

public void setId(int id) {
this.id = id;
}
}

The servlets use a utility program for processing escapes which resides
in the source Packages.util. This program uses commons-lang...jar
which has to be put on the classpath somewhere.
util.Escape.java
----------------
package util;

import org.apache.commons.lang.*;

public class Escape {
public static String html(String input) {
return StringEscapeUtils.escapeHtml(input);
}

public static String javaScript(String input) {
return StringEscapeUtils.escapeJavaScript(input);
}

public static String lineBreakToBr(String input) {
return input.replaceAll("\\n", "<br />");
}

public static String paragraphBreakToBrs(String input) {
return input.replaceAll("\\n\\s*\\n", "<br /><br />");
}
}

Simple CRUD with JQuery-3

--------------
Each AJAX call triggers a corresponding URL of a servlet that are
defined in the web.xml

web.xml
-------
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Simple CRUD of ARS</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>new</servlet-name>
<servlet-class>servletPackage.createServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>readnext</servlet-name>
<servlet-class>servletPackage.readNextServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>readprev</servlet-name>
<servlet-class>servletPackage.readPrevServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>save</servlet-name>
<servlet-class>servletPackage.updateServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>delete</servlet-name>
<servlet-class>servletPackage.deleteServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>list</servlet-name>
<servlet-class>servletPackage.listServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>selectlist</servlet-name>
<servlet-class>servletPackage.selectListServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>new</servlet-name>
<url-pattern>/new</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>readnext</servlet-name>
<url-pattern>/readnext</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>readprev</servlet-name>
<url-pattern>/readprev</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>save</servlet-name>
<url-pattern>/save</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>delete</servlet-name>
<url-pattern>/delete</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>list</servlet-name>
<url-pattern>/list</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>selectlist</servlet-name>
<url-pattern>/selectlist</url-pattern>
</servlet-mapping>
</web-app>


Each servlet is defined in the source Packages.servletPackage
createServlet.java
------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package servletPackage;

import java.io.*;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import mainPackage.*;
import daoPackage.*;

import util.Escape;

public class createServlet extends HttpServlet {

public void init()
throws ServletException {
System.out.println("ARSmsg: createServlet began to work");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/json;charset=UTF-8");
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
PersonDAOVectorImpl personDAO;
HttpSession session = request.getSession();
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");

try {
String id = String.valueOf(personDAO.getPersonNextId());
String name = "Please enter data here";
String last = "Regards. ";
String hobby = "Ali R+";
System.out.println("ProcessData began");
name = name+ " new,";

id = Escape.html(id);
name = Escape.html(name);
last = Escape.html(last);
hobby = Escape.html(hobby);

// for JSON output
id = Escape.javaScript(id);
name = Escape.javaScript(name);
last = Escape.javaScript(last);
hobby = Escape.javaScript(hobby);

out.println(
"{"
+ " \"id\":" + '"' + id + '"' + ","
+ " \"name\":" + '"' + name + '"' + ","
+ " \"last\":" + '"' + last + '"' + ","
+ " \"hobby\":" + '"' + hobby + '"'
+ "}");
System.out.println("ProcessData out id="+name);
} finally {
out.close();
}

}
}

deleteServlet.java
------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package servletPackage;

import java.io.*;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import mainPackage.*;
import daoPackage.*;

import util.Escape;

public class deleteServlet
extends HttpServlet
{
/**
* Called once at startup
*/
public void init()
throws ServletException
{
System.out.println("ARSmsg: deleteServlet began to work");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

PersonDAOVectorImpl personDAO;
Person person= new Person();
HttpSession session = request.getSession();

try {
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");
personDAO.deleteRec(personDAO.getPersonCurrentId());
person = personDAO.readRec(personDAO.getPersonCurrentId());

String id = String.valueOf(person.getId());
String name = person.getName();
String last = person.getLast();
String hobby = person.getHobby();

id = Escape.html(id);
name = Escape.html(name);
last = Escape.html(last);
hobby = Escape.html(hobby);

// for JSON output
id = Escape.javaScript(id);
name = Escape.javaScript(name);
last = Escape.javaScript(last);
hobby = Escape.javaScript(hobby);

out.println(
"{"
+ " \"id\":" + '"' + id + '"' + ","
+ " \"name\":" + '"' + name + '"' + ","
+ " \"last\":" + '"' + last + '"' + ","
+ " \"hobby\":" + '"' + hobby + '"'
+ "}");
System.out.println("ProcessData out id="+name);
} finally {
out.close();
}

}


}


listServlet.java
----------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package servletPackage;

import java.io.*;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import util.Escape;

public class listServlet
extends HttpServlet
{
/**
* Called once at startup
*/
public void init()
throws ServletException
{
System.out.println("ARSmsg: listServlet began to work");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/json;charset=UTF-8");
response.setContentType("text/html;charset=UTF-8");
//response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Enumeration e =request.getParameterNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key);
}
StringBuffer s =request.getRequestURL();
System.out.println(s.toString());

String id = request.getParameter("id");
String name = request.getParameter("name");
String last = request.getParameter("last");
String hobby = request.getParameter("hobby");
System.out.println("ProcessData began");
name = name+ " list,";

id = Escape.html(id);
name = Escape.html(name);
last = Escape.html(last);
hobby = Escape.html(hobby);

// for JSON output
id = Escape.javaScript(id);
name = Escape.javaScript(name);
last = Escape.javaScript(last);
hobby = Escape.javaScript(hobby);

out.println(
"{"
+ " \"id\":" + '"' + id + '"' + ","
+ " \"name\":" + '"' + name + '"' + ","
+ " \"last\":" + '"' + last + '"' + ","
+ " \"hobby\":" + '"' + hobby + '"'
+ "}");
System.out.println("ProcessData out id="+name);
} finally {
out.close();
}

}
}


readNextServlet.java
--------------------
package servletPackage;

import java.io.*;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import mainPackage.*;
import daoPackage.*;

import util.Escape;

public class readNextServlet extends HttpServlet {

public void init()
throws ServletException
{
System.out.println("ARSmsg: readNextServlet began to work");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

PersonDAOVectorImpl personDAO;
Person person= new Person();
HttpSession session = request.getSession();

try {
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");
person = personDAO.readNextRec();


String id = String.valueOf(person.getId());
String name = person.getName();
String last = person.getLast();
String hobby = person.getHobby();
System.out.println("next id="+personDAO.getPersonNextId());

id = Escape.html(id);
name = Escape.html(name);
last = Escape.html(last);
hobby = Escape.html(hobby);


// for JSON output
id = Escape.javaScript(id);
name = Escape.javaScript(name);
last = Escape.javaScript(last);
hobby = Escape.javaScript(hobby);

out.println(
"{"
+ " \"id\":" + '"' + id + '"' + ","
+ " \"name\":" + '"' + name + '"' + ","
+ " \"last\":" + '"' + last + '"' + ","
+ " \"hobby\":" + '"' + hobby + '"'
+ "}");
System.out.println("ProcessData out id="+name);
} finally {
out.close();
}

}

}


readPrevServlet.java
--------------------
package servletPackage;

import java.io.*;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import mainPackage.*;
import daoPackage.*;

import util.Escape;

public class readPrevServlet extends HttpServlet {

public void init()
throws ServletException
{
System.out.println("ARSmsg: readPrevServlet began to work");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

PersonDAOVectorImpl personDAO;
Person person= new Person();
HttpSession session = request.getSession();

try {
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");
person = personDAO.readPrevRec();

if (person != null){
session.removeAttribute("personDAOsess");
session.setAttribute("personDAOsess", personDAO);
String id=String.valueOf(person.getId());
String name =person.getName();
String last =person.getLast();
String hobby=person.getHobby();

id = Escape.html(id);
name = Escape.html(name);
last = Escape.html(last);
hobby = Escape.html(hobby);

// for JSON output
id = Escape.javaScript(id);
name = Escape.javaScript(name);
last = Escape.javaScript(last);
hobby = Escape.javaScript(hobby);

out.println(
"{"
+ " \"id\":" + '"' + id + '"' + ","
+ " \"name\":" + '"' + name + '"' + ","
+ " \"last\":" + '"' + last + '"' + ","
+ " \"hobby\":" + '"' + hobby + '"'
+ "}");
}
} finally {
out.close();
}

}
}


updateServlet.java
------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package servletPackage;

import java.io.*;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import mainPackage.*;
import daoPackage.*;

import util.Escape;

public class updateServlet extends HttpServlet {

public void init()
throws ServletException
{
System.out.println("Init() worked");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();

PersonDAOVectorImpl personDAO;
Person person= new Person();
HttpSession session = request.getSession();

try {
String id = request.getParameter("id");
String name = request.getParameter("name");
String last = request.getParameter("last");
String hobby = request.getParameter("hobby");
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");
personDAO.updateRec(Integer.valueOf(id), name, last, hobby);

if (person != null){
session.removeAttribute("personDAOsess");
session.setAttribute("personDAOsess", personDAO);

id = Escape.html(id);
name = Escape.html(name);
last = Escape.html(last);
hobby = Escape.html(hobby);

// for JSON output
id = Escape.javaScript(id);
name = Escape.javaScript(name);
last = Escape.javaScript(last);
hobby = Escape.javaScript(hobby);

out.println(
"{"
+ " \"id\":" + '"' + id + '"' + ","
+ " \"name\":" + '"' + name + '"' + ","
+ " \"last\":" + '"' + last + '"' + ","
+ " \"hobby\":" + '"' + hobby + '"'
+ "}");
System.out.println("ProcessData out id="+name);
}
} finally {
out.close();
}

}
}

Simple CRUD with JQuery-2

The main screen is index.jsp . This screen has the new, save, delete,
next, prev and list buttons. The list button is not functional at
this moment. I will provide that in the near future.

index.jsp
----------

<%--
Document : index
Created on : 24.Sub.2011, 18:23:21
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<%@ page import="mainPackage.*" %>
<%@ page import="daoPackage.*" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>ARS's Simple JQ CRUD</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript" src="js/JQmultiAJAXCalls.js"></script>
<%
System.out.println("index.jsp JSP script began here.");
PersonDAOVectorImpl personDAO;

if (session.getAttribute("personDAOsess") == null){
System.out.println("index.jsp personDAOsess == null ");
personDAO = new PersonDAOVectorImpl();
session.setAttribute("personDAOsess", personDAO);
}
else {
System.out.println("index.jsp personDAOsess!!!!=null");
personDAO = (PersonDAOVectorImpl) session.getAttribute("personDAOsess");
}
%>
<SCRIPT>
function InitScr() {
alert ("Merhaba from Ali R+ with best wishes! ");
$("input#Prev").click()
}

</SCRIPT>
</head>
<body style="background-color:yellow" onLoad="InitScr()">


<h1>The Simplest JQuery CRUD Application</h1>

<br />

<form name="theDetail" action="" method="get">
<input type="hidden" id="id" name="id"/><br />
First name: <input type="text" id ="name" name="name"/><br />
Last name : <input type="text" id="last" name="last"/><br />
Hobby : <input type="text" id="hobby" name="hobby"/><br />
<br />
<INPUT TYPE="button" id="New" VALUE="New">
<INPUT TYPE="button" id="Save" VALUE="Save">
<INPUT TYPE="button" id="Delete" VALUE="Delete">
<INPUT TYPE="button" id="Next" VALUE="Next">
<INPUT TYPE="button" id="Prev" VALUE="Prev">
<INPUT TYPE="button" id="List" VALUE="List">
</form>
</body>
</html>

Each button is linked to an event handler in the java script file
JQmultiAJAXCalls.js
-------------------
$(document).ready(function() {
// Handler for .ready() called.
$(function() {
$("input#New").click(function() {
var id = $("input#id").val();
var name = $("input#name").val();
var last = $("input#last").val();
var hobby = $("input#hobby").val();
//alert('New is clicked dataString='+name);
var aoData = [];
aoData.push( { "name": "id", "value": id },
{ "name": "name", "value": name },
{"name": "last", "value": last },
{"name": "hobby", "value": hobby }
);
$.ajax({
type:"POST",
url: "./new",
contentType: "application/x-www-form-urlencoded",
dataType: "JSON",
data: aoData,
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown)},

success: function(data) {
var jsonData = $.parseJSON(data);
$("input#id").val(jsonData.id)
$("input#name").val(jsonData.name)
$("input#last").val(jsonData.last)
$("input#hobby").val(jsonData.hobby)
}
})
return false;
})
})

$(function() {
$("input#Save").click(function() {
var id = $("input#id").val();
var name = $("input#name").val();
var last = $("input#last").val();
var hobby = $("input#hobby").val();
//alert('Save is clicked name='+name);
var aoData = [];
aoData.push( {"name": "id", "value": id },
{"name": "name", "value": name },
{"name": "last", "value": last },
{"name": "hobby", "value": hobby }
);
$.ajax({
type:"POST",
url: "./save",
contentType: "application/x-www-form-urlencoded",
dataType: "JSON",
data: aoData,
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown)
},
success: function(data) {
var jsonData = $.parseJSON(data);
$("input#id").val(jsonData.id)
$("input#name").val(jsonData.name)
$("input#last").val(jsonData.last)
$("input#hobby").val(jsonData.hobby)
}
})
return false;
})
})

$(function() {
$("input#Delete").click(function() {
var id = $("input#id").val();
var name = $("input#name").val();
var last = $("input#last").val();
var hobby = $("input#hobby").val();
//alert('Delete is clicked name='+name);
var aoData = [];
aoData.push( {"name": "id", "value": id },
{"name": "name", "value": name },
{"name": "last", "value": last },
{"name": "hobby", "value": hobby }
);
$.ajax({
type:"POST",
url: "./delete",
contentType: "application/x-www-form-urlencoded",
dataType: "JSON",
data: aoData,
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown)
},
success: function(data) {
var jsonData = $.parseJSON(data);
$("input#id").val(jsonData.id)
$("input#name").val(jsonData.name)
$("input#last").val(jsonData.last)
$("input#hobby").val(jsonData.hobby)
}
})
return false;
})
})
$(function() {
$("input#Next").click(function() {
var id = $("input#id").val();
var name = $("input#name").val();
var last = $("input#last").val();
var hobby = $("input#hobby").val();
//alert('Next is clicked name='+name);
var aoData = [];
aoData.push( {"name": "id", "value": id },
{ "name": "name", "value": name },
{"name": "last", "value": last },
{"name": "hobby", "value": hobby }
);
$.ajax({
type:"POST",
url: "./readnext",
contentType: "application/x-www-form-urlencoded",
dataType: "JSON",
data: aoData,
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown)
},
success: function(data) {
var jsonData = $.parseJSON(data);
$("input#id").val(jsonData.id)
$("input#name").val(jsonData.name)
$("input#last").val(jsonData.last)
$("input#hobby").val(jsonData.hobby)
}
})
return false;
})
})

$(function() {
$("input#Prev").click(function() {
var id = $("input#id").val();
var name = $("input#name").val();
var last = $("input#last").val();
var hobby = $("input#hobby").val();
//alert('Prev is clicked name='+name);
var aoData = [];
aoData.push( {"name": "id", "value": id },
{"name": "name", "value": name },
{"name": "last", "value": last },
{"name": "hobby", "value": hobby }
);
$.ajax({
type:"POST",
url: "./readprev",
contentType: "application/x-www-form-urlencoded",
dataType: "JSON",
data: aoData,
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown)
},
success: function(data) {
var jsonData = $.parseJSON(data);
$("input#id").val(jsonData.id)
$("input#name").val(jsonData.name)
$("input#last").val(jsonData.last)
$("input#hobby").val(jsonData.hobby)
}
})
return false;
})
})

$(function() {
$("input#List").click(function() {
var id = $("input#id").val();
var name = $("input#name").val();
var last = $("input#last").val();
var hobby = $("input#hobby").val();
//alert('List is clicked name='+name);
var aoData = [];
aoData.push( {"name": "id", "value": id },
{"name": "name", "value": name },
{"name": "last", "value": last },
{"name": "hobby", "value": hobby }
);
$.ajax({
type:"POST",
url: "./list",
contentType: "application/x-www-form-urlencoded",
dataType: "JSON",
data: aoData,
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown)
},
success: function(data) {
var jsonData = $.parseJSON(data);
$("input#id").val(jsonData.id)
$("input#name").val(jsonData.name)
$("input#last").val(jsonData.last)
$("input#hobby").val(jsonData.hobby)
}
})
return false;
})
})


});

Simple CRUD with JQuery

This tutorial will explain the construction of a simple CRUD
with vector based DAO using JQuery. This is the JQuery
version of my 'Simple CRUD Tutorial' at
http://tekne-techne.blogspot.com/2011/01/simple-crud-tutorial-intro.html


The main screen is index.jsp

This screen has the new, save, delete, next, prev and list buttons. The list button is not functional at this moment. I will provide that in the near future.

Each button is linked to an event handler in the java script file JQmultiAJAXCalls.js

Each AJAX call triggers a corresponding URL of a servlet that are defined in the web.xml


Each servlet is defined in the source Packages.servletPackage

The underlying mechanism to be used as database is the Data Access Object. It is defined in the source Packages.daoPackage

The daoPackage uses the Person.java definition as record definition and it is located in the source Packages.mainPackage

The servlets use a utility program for processing escapes which resides in the source Packages.util. This program uses commons-lang...jar which has to be put on the classpath somewhere.

Once again, I will provide the list and select Row in an other tutorial. I will provide the related source codes with the same explanation above at the required points. The source code is complete and working...

Kind regards.

Ali R+

Sunday 27 February 2011

Multi Actions with JQuery - 2

This is a little bit more difficult than simple.
This example shows
1- how to define a servlet with web.xml and JAVA source lib
2- how to call this servlet via AJAX
3- how to pass values to the servlet via AJAX
4- how to receive returned values from the called servlet via AJAX
5- how to do all of these many times at the same JSP


web.xml
-------
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_9" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Simple CRUD of ARS</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>new</servlet-name>
<servlet-class>servletPackage.createServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>readnext</servlet-name>
<servlet-class>servletPackage.readNextServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>readprev</servlet-name>
<servlet-class>servletPackage.readPrevServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>save</servlet-name>
<servlet-class>servletPackage.updateServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>delete</servlet-name>
<servlet-class>servletPackage.deleteServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>list</servlet-name>
<servlet-class>servletPackage.listServlet</servlet-class>
</servlet>
<servlet>
<servlet-name>selectlist</servlet-name>
<servlet-class>servletPackage.selectListServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>new</servlet-name>
<url-pattern>/new</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>readnext</servlet-name>
<url-pattern>/readnext</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>readprev</servlet-name>
<url-pattern>/readprev</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>save</servlet-name>
<url-pattern>/save</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>delete</servlet-name>
<url-pattern>/delete</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>list</servlet-name>
<url-pattern>/list</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>selectlist</servlet-name>
<url-pattern>/selectlist</url-pattern>
</servlet-mapping>
</web-app>



createServlet.java
------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package servletPackage;

import java.io.*;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import util.Escape;

public class createServlet extends HttpServlet {

public void init()
throws ServletException {
System.out.println("ARSmsg: createServlet began to work");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/json;charset=UTF-8");
response.setContentType("text/html;charset=UTF-8");
//response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Enumeration e =request.getParameterNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key);
}
StringBuffer s =request.getRequestURL();
System.out.println(s.toString());

String name = request.getParameter("name");
String last = request.getParameter("last");
String hobby = request.getParameter("hobby");
System.out.println("ProcessData began");
name = name+ " new,";

name = Escape.html(name);
last = Escape.html(last);
hobby = Escape.html(hobby);

// for JSON output
name = Escape.javaScript(name);
last = Escape.javaScript(last);
hobby = Escape.javaScript(hobby);

out.println(
"{"
+ " \"name\":" + '"' + name + '"' + ","
+ " \"last\":" + '"' + last + '"' + ","
+ " \"hobby\":" + '"' + hobby + '"'
+ "}");
System.out.println("ProcessData out id="+name);
} finally {
out.close();
}

}
}



updateServlet.java
------------------
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/

package servletPackage;

import java.io.*;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.*;

import util.Escape;

public class updateServlet extends HttpServlet {

public void init()
throws ServletException
{
System.out.println("Init() worked");
}

protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//response.setContentType("text/json;charset=UTF-8");
response.setContentType("text/html;charset=UTF-8");
//response.setContentType("application/json;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
Enumeration e =request.getParameterNames();
while (e.hasMoreElements()) {
String key = (String) e.nextElement();
System.out.println(key);
}
StringBuffer s =request.getRequestURL();
System.out.println(s.toString());

String name = request.getParameter("name");
String last = request.getParameter("last");
String hobby = request.getParameter("hobby");
System.out.println("ProcessData began");
name = name+ " save,";

name = Escape.html(name);
last = Escape.html(last);
hobby = Escape.html(hobby);

// for JSON output
name = Escape.javaScript(name);
last = Escape.javaScript(last);
hobby = Escape.javaScript(hobby);

out.println(
"{"
+ " \"name\":" + '"' + name + '"' + ","
+ " \"last\":" + '"' + last + '"' + ","
+ " \"hobby\":" + '"' + hobby + '"'
+ "}");
System.out.println("ProcessData out id="+name);
} finally {
out.close();
}

}
}

deleteServlet.java
listServlet.java
readNextServlet.java
readPrevServlet.java
...
these are similar for the time being.
They will vary when I implement the CRUD using this substructure.




JQMultiAJAXCalls.jsp
--------------------
<%--
Document : index
Created on : 24.Sub.2011, 18:23:21
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>ARS's Simple JQ CRUD</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript" src="js/JQmultiAJAXCalls.js"></script>
<%
System.out.println("index.jsp JSP script began here.");
%>
<SCRIPT>
function InitScr() {
alert ("Merhaba from Ali R+ with best wishes! ");
}

</SCRIPT>
</head>
<body style="background-color:yellow" onLoad="InitScr()">


<h1>The Simplest JQuery CRUD Application</h1>

<br />

<form name="theDetail" action="" method="get">
<input type="hidden" name="id"/><br />
First name: <input type="text" id ="name" name="name"/><br />
Last name : <input type="text" id="last" name="last"/><br />
Hobby : <input type="text" id="hobby" name="hobby"/><br />
<br />
<INPUT TYPE="button" id="New" VALUE="New">
<INPUT TYPE="button" id="Save" VALUE="Save">
<INPUT TYPE="button" id="Delete" VALUE="Delete">
<INPUT TYPE="button" id="Next" VALUE="Next">
<INPUT TYPE="button" id="Prev" VALUE="Prev">
<INPUT TYPE="button" id="List" VALUE="List">
</form>
</body>
</html>


JQMultiAJAXCalls.js
-------------------
$(document).ready(function() {
// Handler for .ready() called.
$(function() {
$("input#New").click(function() {
var name = $("input#name").val();
var last = $("input#last").val();
var hobby = $("input#hobby").val();
alert('New is clicked dataString='+name);
var aoData = [];
aoData.push( { "name": "name", "value": name },
{"name": "last", "value": last },
{"name": "hobby", "value": hobby }
);
$.ajax({
type:"POST",
url: "./new",
contentType: "application/x-www-form-urlencoded",
dataType: "JSON",
data: aoData,
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown)},

success: function(data) {
var jsonData = $.parseJSON(data);
$("input#name").val(jsonData.name)
$("input#last").val(jsonData.last)
$("input#hobby").val(jsonData.hobby)
}
})
return false;
})
})

$(function() {
$("input#Save").click(function() {
var name = $("input#name").val();
var last = $("input#last").val();
var hobby = $("input#hobby").val();
alert('Save is clicked name='+name);
var aoData = [];
aoData.push( { "name": "name", "value": name },
{"name": "last", "value": last },
{"name": "hobby", "value": hobby }
);
$.ajax({
type:"POST",
url: "./save",
contentType: "application/x-www-form-urlencoded",
dataType: "JSON",
data: aoData,
error : function (XMLHttpRequest, textStatus, errorThrown) {
alert(XMLHttpRequest);
alert(textStatus);
alert(errorThrown)
},
success: function(data) {
var jsonData = $.parseJSON(data);
$("input#name").val(jsonData.name)
$("input#last").val(jsonData.last)
$("input#hobby").val(jsonData.hobby)
}
})
return false;
})
})

$(function() {
$("input#Delete").click(function() {
...
$(function() {
$("input#Next").click(function() {
...

$(function() {
$("input#Prev").click(function() {
...

$(function() {
$("input#List").click(function() {
...


});

package util;

import org.apache.commons.lang.*;

public class Escape {
public static String html(String input) {
return StringEscapeUtils.escapeHtml(input);
}

public static String javaScript(String input) {
return StringEscapeUtils.escapeJavaScript(input);
}

public static String lineBreakToBr(String input) {
return input.replaceAll("\\n", "<br />");
}

public static String paragraphBreakToBrs(String input) {
return input.replaceAll("\\n\\s*\\n", "<br /><br />");
}
}

Multi Actions with JQuery - 1

This is a small tutorial about a simple multi-button JQuery
application. The first part will demonstarte how to handle
multi buttons and the second part will demonstrate:
1. How to handle multi actions
2. How to handle an action with AJAX and a servlet.

The multi-button simple example follows:

JQMultiButton.jsp
-----------------
<%--
Document : index
Created on : 24.Sub.2011, 18:23:21
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>ARS's Simple JQ CRUD</title>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript" src="js/jquery.form.js"></script>
<script type="text/javascript" src="js/JQmultiButton.js"></script>
<%
System.out.println("index.jsp JSP script began here.");
%>
<SCRIPT>
function InitScr() {
alert ("Merhaba from Ali R+ with best wishes! ");
}

</SCRIPT>
</head>
<body style="background-color:yellow" onLoad="InitScr()">


<h1>The Simplest JQuery CRUD Application</h1>

<br />

<form name="theDetail" action="" method="get">
<input type="hidden" name="id"/><br />
First name: <input type="text" id ="name" name="name"/><br />
Last name : <input type="text" id="last" name="last"/><br />
Hobby : <input type="text" id="hobby" name="hobby"/><br />
<br />
<INPUT TYPE="button" id="New" VALUE="New">
<INPUT TYPE="button" id="Save" VALUE="Save">
<INPUT TYPE="button" id="Delete" VALUE="Delete">
<INPUT TYPE="button" id="Next" VALUE="Next">
<INPUT TYPE="button" id="Prev" VALUE="Prev">
<INPUT TYPE="button" id="List" VALUE="List">
</form>
</body>
</html>



JQmultiButton.js
----------------
$(document).ready(function() {
// Handler for .ready() called.

$(function() {
$("input#New").click(function() {
alert('New is clicked');
})
})

$(function() {
$("input#Save").click(function() {
alert('Save is clicked');
})
})

$(function() {
$("input#Delete").click(function() {
alert('Delete is clicked');
})
})
$(function() {
$("input#Next").click(function() {
alert('Next is clicked');
})
})

$(function() {
$("input#Prev").click(function() {
alert('Prev is clicked');
})
})

$(function() {
$("input#List").click(function() {
alert('List is clicked');
})
})


});

Friday 25 February 2011

JQuery how to pass data to a servlet on the server via AJAX

This is a short note about passing data to a servlet on the server.
using AJAX on JQuery. The problem is you can not find the required
format written anywhere.

-The passed data must be in the name-value format as seen below.
-The content type is indicated wrong in many internet references,
probably version difference.
-The JQuery version I used is jQuery JavaScript Library v1.4.4
-be careful dataType "json" does not work it has to be capitolized.

The complete application uses multiple buttons that trigger multiple
AJAX calls. I will provide the full working code as I make progress.
Calling and returning back from AJAX driven servlets is working now.

Cheers.

Ali R+

Here is the solution:
...
...
...
var name = $("input#name").val();
var last = $("input#last").val();
var hobby = $("input#hobby").val();

var aoData = [];

aoData.push( { "name": "name", "value": name },
{"name": "last", "value": last },
{"name": "hobby", "value": hobby }
);
$.ajax({
type:"POST",
url: "./new",
contentType: "application/x-www-form-urlencoded",
dataType: "JSON",
data: aoData,
success: function(data) {
var jsonData = $.parseJSON(data);
$("input#name").val(jsonData.name)
$("input#last").val(jsonData.last)
$("input#hobby").val(jsonData.hobby)
}
})
return false;
...
...
...

Sunday 20 February 2011

JQ Forms with AJAX-JSP8

This is basicly the same as Sample4 but there is a small addition to
demonstrate fieldSerialize and fieldValue Form Plugin methods.

sample8.java
------------
<%--
Document : sample4
Created on : 19.Şub.2011, 20:17:55
Originally : belongs to "jQuery Form Plugin"
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
// bind form using ajaxForm
$('#jsonForm').ajaxForm({
// dataType identifies the expected content type of the server response
dataType: 'json',

// success identifies the function to invoke when the server response
// has been received
success: processJson
});
});

function processJson(data) {
// 'data' is the json object returned from the server
alert(data.message);
var queryString = $('#jsonForm :text').fieldSerialize();
var pwd = $('#jsonForm :text').fieldValue()[0];
alert(queryString);
}
</script>
</head>
<body>
<div id="sample4">
<p />
This page shows how to handle JSON data returned from the server.
<p />
The form below submits a message to the server and the server
echos it back in JSON format.
<br />
<p />
<form id="jsonForm" action="json-echo.jsp" method="post"><div>
Message: <input type="text" name="message" value="Hello JSON" />
<input type="submit" value="Echo as JSON" />
</div></form>
<br />
</div>
</body>
</html>

json-echo.java
--------------
<%
out.print("{ \"message\": \"" + request.getParameter("message") + "\" }");
%>

JQ Forms with AJAX-JSP6

This example demonstrates the use of ajaxForm with HTML data.

Sample6.jsp
-----------
<%--
Document : sample6.jsp
Created on : 19.Şub.2011, 21:09:26
Originally : belongs to "jQuery Form Plugin"
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>

<script type="text/javascript">
// prepare the form when the DOM is ready
$(document).ready(function() {
// bind form using ajaxForm
$('#htmlForm').ajaxForm({
// target identifies the element(s) to update with the server response
target: '#htmlExampleTarget',

// success identifies the function to invoke when the server response
// has been received; here we apply a fade-in effect to the new content
success: function() {
$('#htmlExampleTarget').fadeIn('slow');
}
});
});
</script>
</head>
<body>

<div id="sample6">
<p />
This page shows how to handle HTML data returned from the server.
<p />
The form below submits a message to the server and the server
echos it back in an HTML div. The response is added to this
page in the <code class="inline">htmlExampleTarget</code> div below.
<br />
<form id="htmlForm" action="html-echo.jsp" method="post"><div>
Message: <input type="text" name="message" value="Hello HTML" />
<input type="submit" value="Echo as HTML" />
</div></form>

<br />
<h3>htmlExampleTarget (output will be added below):</h3>
<div id="htmlExampleTarget"></div>
</div>


</body>
</html>


html-echo.jsp
-------------
<%
out.print("<div style=\"background-color:#ffa; padding:20px\">" + request.getParameter("message") + "</div>");
%>

JQ Forms with AJAX-JSP5

This example demonstrates the use of ajaxForm with XML data.

Sample5.jsp
-----------
<%--
Document : sample5.jsp
Created on : 19.Şub.2011, 20:38:10
Originally : belongs to "jQuery Form Plugin"
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>

<script type="text/javascript">
$(document).ready(function() {
// bind form using ajaxForm
$('#xmlForm').ajaxForm({
// dataType identifies the expected content type of the server response
dataType: 'xml',

// success identifies the function to invoke when the server response
// has been received
success: processXml
});
});
function processXml(responseXML) {
// 'responseXML' is the XML document returned by the server; we use
// jQuery to extract the content of the message node from the XML doc
var message = $('message', responseXML).text();
alert(message);
}
</script>
</head>
<body>
<div id="sample5">
<p />
This page shows how to handle XML data returned from the server.
<p />
The form below submits a message to the server and the server
echos it back in XML format.
<br />

<form id="xmlForm" action="xml-echo.jsp" method="post"><div>
Message: <input type="text" name="message" value="Hello XML" />
<input type="submit" value="Echo as XML" />
</div></form>
</div>

</body>
</html>

xml-echo.jsp
------------
<%@page contentType="text/xml" pageEncoding="UTF-8"%>
<%

// !!! IMPORTANT !!! - the server must set the content type to XML
out.print("<root><message>" + request.getParameter("message") + "</message></root>");
%>

JQ Forms with AJAX-JSP4

This example demonstrates the use of ajaxForm with JSON data.

Sample4.jsp
-----------
<%--
Document : sample4
Created on : 19.Şub.2011, 20:17:55
Originally : belongs to "jQuery Form Plugin"
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
// bind form using ajaxForm
$('#jsonForm').ajaxForm({
// dataType identifies the expected content type of the server response
dataType: 'json',

// success identifies the function to invoke when the server response
// has been received
success: processJson
});
});

function processJson(data) {
// 'data' is the json object returned from the server
alert(data.message);
}
</script>
</head>
<body>
<div id="sample4">
<p />
This page shows how to handle JSON data returned from the server.
<p />
The form below submits a message to the server and the server
echos it back in JSON format.
<br />
<p />
<form id="jsonForm" action="json-echo.jsp" method="post"><div>
Message: <input type="text" name="message" value="Hello JSON" />
<input type="submit" value="Echo as JSON" />
</div></form>
<br />
</div>
</body>
</html>

json-echo.jsp
-------------
<%
out.print("{ \"message\": \"" + request.getParameter("message") + "\" }");
%>

JQ Forms with AJAX-JSP3

There are three slightly different examples of validation here. The first uses the forData array.


FIRST EXAMPLE:
--------------

Sample3_1.jsp
-------------
<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
// wait for the DOM to be loaded
var x=0;
$(document).ready(function() {
// bind form using ajaxForm
$('#validateForm1').ajaxForm( { beforeSubmit: validate } );
});
function validate(formData, jqForm, options) {
// formData is an array of objects representing the name and value of each field
// that will be sent to the server; it takes the following form:
//
// [
// { name: username, value: valueOfUsernameInput },
// { name: password, value: valueOfPasswordInput }
// ]
//
// To validate, we can examine the contents of this array to see if the
// username and password fields have values. If either value evaluates
// to false then we return false from this method.
for (var i=0; i < formData.length; i++) {
if (!formData[i].value) {
alert('Please enter a value for both Username and Password');
return false;
}
}
alert('Both fields contain values.');
}
</script>
</head>
<body>
<div id="sample3">
<h3>Validate Using the <code>formData</code> Argument</h3>
<form id="validateForm1" action="dummy.jsp" method="post"><div>
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="submit" value="Submit" />
</div></form>
</div>

</body>
</html>

dummy.jsp
---------
<%--
Document : dummy
Created on : 19.?ub.2011, 09:30:16
Author : Ali Riza SARAL
--%>
<%
out.print("Hello world");
%>


The second uses the jqform element to acces the DOM elemnts directly.


SECOND EXAMPLE:
---------------

Sample3_2.jsp
-------------
<%--
Document : sample3
Created on : 19.Şub.2011, 10:38:01
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
// bind form using ajaxForm
$('#validateForm2').ajaxForm( { beforeSubmit: validate } );
})

function validate(formData, jqForm, options) {
// jqForm is a jQuery object which wraps the form DOM element
//
// To validate, we can access the DOM elements directly and return true
// only if the values of both the username and password fields evaluate
// to true

var form = jqForm[0];
if (!form.username.value || !form.password.value) {
alert('Please enter a value for both Username and Password');
return false;
}
alert('Both fields contain values.');
}

</script>
</head>
<body>
<div id="sample3">
<h3>Validate Using the <code>jqForm</code> Argument</h3>
<form id="validateForm2" action="dummy.jsp" method="post"><div>
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="submit" value="Submit" />
</div></form>
</div>

</body>
</html>


The third example uses the fieldValue is a Form Plugin method.

THIRD EXAMPLE:
--------------

Sample3_3.jsp:
--------------
<%--
Document : sample3
Created on : 19.Şub.2011, 10:38:01
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>
<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
// bind form using ajaxForm
$('#validateForm3').ajaxForm( { beforeSubmit: validate } );
})

function validate(formData, jqForm, options) {
// fieldValue is a Form Plugin method that can be invoked to find the
// current value of a field
//
// To validate, we can capture the values of both the username and password
// fields and return true only if both evaluate to true

var usernameValue = $('input[name=username]').fieldValue();
var passwordValue = $('input[name=password]').fieldValue();

// usernameValue and passwordValue are arrays but we can do simple
// "not" tests to see if the arrays are empty
if (!usernameValue[0] || !passwordValue[0]) {
alert('Please enter a value for both Username and Password');
return false;
}
alert('Both fields contain values.');
}
</script>
</head>
<body>
<div id="sample3">
<h3>Validate Using the <code>fieldValue</code> Method</h3>
<form id="validateForm3" action="dummy.jsp" method="post"><div>
Username: <input type="text" name="username" />
Password: <input type="password" name="password" />
<input type="submit" value="Submit" />
</div></form>


</div>

</body>
</html>

JQ Forms with AJAX-JSP2

This example demonstarates the use of ajaxSubmit() and pre- / post- submit callback.

Sample2.jsp
-----------
<%--
Document : sample2
Created on : 19.Şub.2011, 09:56:09
Originally : belongs to "jQuery Form Plugin"
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>JSP Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>

<script type="text/javascript">
$(document).ready(function() {
var options = {
target: '#output2', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback

// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit

// $.ajax options can be used here too, for example:
//timeout: 3000
};

// bind to the form's submit event
$('#myForm2').submit(function() {
// inside event callbacks 'this' is the DOM element so we first
// wrap it in a jQuery object and then invoke ajaxSubmit
$(this).ajaxSubmit(options);

// !!! Important !!!
// always return false to prevent standard browser submit and page navigation
return false;
});
});

// pre-submit callback
function showRequest(formData, jqForm, options) {
// formData is an array; here we use $.param to convert it to a string to display it
// but the form plugin does this for you automatically when it submits the data
var queryString = $.param(formData);

// jqForm is a jQuery object encapsulating the form element. To access the
// DOM element for the form do this:
// var formElement = jqForm[0];

alert('About to submit: \n\n' + queryString);

// here we could return false to prevent the form from being submitted;
// returning anything other than false will allow the form submit to continue
return true;
}

// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
// for normal html responses, the first argument to the success callback
// is the XMLHttpRequest object's responseText property

// if the ajaxSubmit method was passed an Options Object with the dataType
// property set to 'xml' then the first argument to the success callback
// is the XMLHttpRequest object's responseXML property

// if the ajaxSubmit method was passed an Options Object with the dataType
// property set to 'json' then the first argument to the success callback
// is the json data object returned by the server

alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}

</script>
</head>
<body>
<div id="sample2" class="sampleTabContent" data-tabid="ajaxSubmit">
<p />
The following code controls the HTML form beneath it. It uses <code class="inline">ajaxSubmit</code>
to submit the form.
<pre><code class="mix">// prepare the form when the DOM is ready

</code></pre>
<form id="myForm2" action="dummy.jsp" method="post"><div>

<input type="hidden" name="Hidden" value="hiddenValue" />
<table>
<tr><td>Name:</td><td><input name="Name" type="text" value="MyName2" /></td></tr>
<tr><td>Password:</td><td><input name="Password" type="password" /></td></tr>
<tr><td>Multiple:</td><td><select name="Multiple" multiple="multiple">
<optgroup label="Group 1">
<option value="one" selected="selected">One</option>

<option value="two">Two</option>
<option value="three">Three</option>
</optgroup>
<optgroup label="Group 2">
<option value="four">Four</option>
<option value="five">Five</option>
<option value="six">Six</option>

</optgroup>
</select></td></tr>
<tr><td>Single:</td><td><select name="Single">
<option value="one" selected="selected">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</select></td></tr>

<tr><td>Single2:</td><td><select name="Single2">
<optgroup label="Group 1">
<option value="A" selected="selected">A</option>
<option value="B">B</option>
<option value="C">C</option>
</optgroup>
<optgroup label="Group 2">

<option value="D">D</option>
<option value="E">E</option>
<option value="F">F</option>
</optgroup>
</select></td></tr>
<tr><td>Check:</td><td>
<input type="checkbox" name="Check" value="1" />

<input type="checkbox" name="Check" value="2" />
<input type="checkbox" name="Check" value="3" />
</td></tr>
<tr><td>Radio:</td><td>
<input type="radio" name="Radio" value="1" />
<input type="radio" name="Radio" value="2" />
<input type="radio" name="Radio" value="3" />
</td></tr>
<tr><td>Text:</td><td><textarea name="Text" rows="2" cols="20">This is Form2</textarea></td></tr>

</table>
<input type="reset" name="resetButton " value="Reset" />
<input type="submit" name="submitButton" value="Submit1" />
<input type="image" name="submitButton" value="Submit2" src="submit.gif" />
</div></form>
<h1>Output Div (#output2):</h1>
<div id="output2">AJAX response will replace this content.</div>
</div>

</body>
</html>

dummy.jsp
---------
<%--
Document : dummy
Created on : 19.?ub.2011, 09:30:16
Author : Ali Riza SARAL
--%>
<%
out.print("Hello world");
%>

JQ Forms with AJAX-JSP1

This tutorial is based on the examples given at "jQuery Form Plugin" page. I tried to remain as loyal as possible to the originals which belong to the official JQuery site.

My contribution although not big is:
1- I extracted the examples from the gorgious example frame of JQuery and made them simple easy to copy and use seperate examples.

2- I changed the PHP AJAX calls to JSP AJAX calls.

Kind regards.


This example demonstarates the use of ajaxForm() and pre- / post- submit callback.


Sample1.jsp
-----------
<%--
Document : sample1
Created on : 19.Şub.2011, 09:19:43
Originally : belongs to "jQuery Form Plugin"
Author : Ali Riza SARAL
--%>

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>JSP Page</title>

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="jquery.form.js"></script>

<script type="text/javascript">
// wait for the DOM to be loaded
$(document).ready(function() {
var options = {
target: '#output1', // target element(s) to be updated with server response
beforeSubmit: showRequest, // pre-submit callback
success: showResponse // post-submit callback

// other available options:
//url: url // override for form's 'action' attribute
//type: type // 'get' or 'post', override for form's 'method' attribute
//dataType: null // 'xml', 'script', or 'json' (expected server response type)
//clearForm: true // clear all form fields after successful submit
//resetForm: true // reset the form after successful submit

// $.ajax options can be used here too, for example:
//timeout: 3000
};

// bind form using 'ajaxForm'
$('#myForm1').ajaxForm(options);
});

// pre-submit callback
function showRequest(formData, jqForm, options) {
// formData is an array; here we use $.param to convert it to a string to display it
// but the form plugin does this for you automatically when it submits the data
var queryString = $.param(formData);

// jqForm is a jQuery object encapsulating the form element. To access the
// DOM element for the form do this:
// var formElement = jqForm[0];

alert('About to submit: \n\n' + queryString);

// here we could return false to prevent the form from being submitted;
// returning anything other than false will allow the form submit to continue
return true;
}

// post-submit callback
function showResponse(responseText, statusText, xhr, $form) {
// for normal html responses, the first argument to the success callback
// is the XMLHttpRequest object's responseText property

// if the ajaxForm method was passed an Options Object with the dataType
// property set to 'xml' then the first argument to the success callback
// is the XMLHttpRequest object's responseXML property

// if the ajaxForm method was passed an Options Object with the dataType
// property set to 'json' then the first argument to the success callback
// is the json data object returned by the server

alert('status: ' + statusText + '\n\nresponseText: \n' + responseText +
'\n\nThe output div should have already been updated with the responseText.');
}
</script>
</head>
<body>
<div id="sample1">
<form id="myForm1" action="dummy.jsp" method="post"><div>
<input type="hidden" name="Hidden" value="hiddenValue" />
<table>
<tr><td>Name:</td><td><input name="Name" type="text" value="MyName1" /></td></tr>
<tr><td>Password:</td><td><input name="Password" type="password" /></td></tr>
<tr><td>Multiple:</td><td><select name="Multiple" multiple="multiple">

<optgroup label="Group 1">
<option value="one" selected="selected">One</option>
<option value="two">Two</option>
<option value="three">Three</option>
</optgroup>
<optgroup label="Group 2">
<option value="four">Four</option>

<option value="five">Five</option>
<option value="six">Six</option>
</optgroup>
</select></td></tr>
<tr><td>Single:</td><td><select name="Single">
<option value="one" selected="selected">One</option>
<option value="two">Two</option>

<option value="three">Three</option>
</select></td></tr>
<tr><td>Single2:</td><td><select name="Single2">
<optgroup label="Group 1">
<option value="A" selected="selected">A</option>
<option value="B">B</option>
<option value="C">C</option>
</optgroup>
<optgroup label="Group 2">
<option value="D">D</option>
<option value="E">E</option>
<option value="F">F</option>
</optgroup>
</select></td></tr>

<tr><td>Check:</td><td>
<input type="checkbox" name="Check" value="1" />
<input type="checkbox" name="Check" value="2" />
<input type="checkbox" name="Check" value="3" />
</td></tr>
<tr><td>Radio:</td><td>
<input type="radio" name="Radio" value="1" />
<input type="radio" name="Radio" value="2" />

<input type="radio" name="Radio" value="3" />
</td></tr>
<tr><td>Text:</td><td><textarea name="Text" rows="2" cols="20">This is Form1</textarea></td></tr>
</table>
<input type="reset" name="resetButton " value="Reset" />
<input type="submit" name="submitButton" value="Submit1" />
<input type="image" name="submitButton" value="Submit2" src="submit.gif" />
<input type="image" name="submitButton" value="Submit3" src="submit.gif" />
<input type="image" name="submitButton" value="Submit4" src="submit.gif" />
<button type="submit" name="submitButton" value="Submit5"><span>submit 5</span></button>
</div></form>
<h1>Output Div (#output1):</h1>
<div id="output1">AJAX response will replace this content.</div>
</div>


</body>
</html>

dummy.jsp
---------
<%--
Document : dummy
Created on : 19.?ub.2011, 09:30:16
Author : Ali Riza SARAL
--%>
<%
out.print("Hello world");
%>