here i am trying to submit a form request through jquery but i don't know why i am unable to do so it just executes the code and nothing is visible on my console.when i try to submit form normally through form action it is successful.any help is thank full.
Jquery & jsp form:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.util.List,beans.Country,mainclasses.CountryListing" errorPage=""%>
<!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=ISO-8859-1">
<title>Post a property</title>
<jsp:useBean id="CNY" class="beans.Country" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js">
</script>
<script type="text/javascript" src="js/combochange.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#contact_details_submit").click(function() {
var companyname = $("#company_name").val();
var officeaddress = $("#office_address").val();
var countryname = $("#country_name option:selected").val();
var statename = $("#state_name option:selected").val();
var cityname = $("#city_name option:selected").val();
var mobile_num = $("#mobilenum").val();
alert(companyname+" : "+officeaddress);
$.get("conatctDetailsInsert.jsp",
{
company_name : companyname,
office_address:officeaddress,
country_name:countryname,
state_name:statename,
city_name:cityname,
mobilenum:mobile_num} ,function(data){
alert(data);
});//end get
});
});
</script>
</head>
<body>
<form action="">
<table cellpadding="0" cellspacing="0" border="1" width="500">
<tbody id="contact_details">
<tr>
<td>i am a
<select>
<option>Agent/broker</option>
<option>Builder/Pvt.Ltd company</option>
</select>
</td>
</tr>
<tr>
<td><h3>Contact Details</h3></td></tr>
<tr>
<td>
Company Name:<input type="text" value="" id="company_name" name="company_name"/>
</td></tr>
<tr>
<td>Office Address:<input type="text" value="" id="office_address" name="office_address"/><br>
Country:
<select id="country_name" name="country_name">
<option>-Select-</option>
<%
mainclasses.CountryListing CNY_CL = new mainclasses.CountryListing();
List<Country> CNY_List=CNY_CL.getCountry();
for(int i=0; i < CNY_List.size(); i++ ){
CNY=(beans.Country)CNY_List.get(i);
%>
<option value="<%=CNY.getIdCountry() %>"><%=CNY.getCountryName() %></option>
<%} %>
</select><br>
State:<select id="state_name" name="state_name"><option></option></select><br>
City:<select id="city_name" name="city_name"><option></option></select><br>
</td>
</tr>
<tr>
<td>
Contact Number:
<input type="tel" id="mobilenum" value="" name="mobilenum"/>
</td>
</tr>
<tr>
<td>
<input type="submit" id="contact_details_submit" name="contact_details_submit"/>
</td>
</tr>
</tbody>
</table>
</form>
</body>
</html>
Request handling jsp:
<%#page import="beans.ConatctDetailsService"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%boolean x=false;
String company_name =request.getParameter("company_name");
String office_address =request.getParameter("office_address");
String country_name =request.getParameter("country_name");
String state_name =request.getParameter("state_name");
String city_name =request.getParameter("city_name");
String mobilenum =request.getParameter("mobilenum");
beans.ConatctDetailsService CTD = new beans.ConatctDetailsService();
CTD.setCompanyName(company_name);
CTD.setCompanyName(office_address);
CTD.setIdCountry(country_name);
CTD.setIdState(state_name);
CTD.setCity(city_name);
CTD.setMobNum(mobilenum);
x=CTD.insert();
System.out.println(x);
CTD.geterror();
if(x){
out.println("done");
}
else{
out.println("no");
}
%>
Try adding an id to the form tag e.g.
<form id='myForm'>
And change to a on form submit.
$(document).ready(function(){
$("#myForm").on('submit', function(e) {
e.preventDefault();
try putting AJAX request to check what's happening:
$.ajax({
type:'GET',
url: 'conatctDetailsInsert.jsp',
data: {company_name : companyname,
office_address:officeaddress,
country_name:countryname,
state_name:statename,
city_name:cityname,
mobilenum:mobile_num},
success: function(data) {
console.log(data);
}, error: function(jqXHR, textStatus, errorThrown) {
console.log(err);
}
});
I would do it this way, much cleaner.
$("form").submit(function(e) {
var formData = $(this).serialize();
$.get("conatctDetailsInsert.jsp",formData, function(data){
alert(data);
});//end get
return false;
});
Related
I have 3 pages, I want to do that when I enter name in textbox. Email and Phone display in different textbox using ajax. It displays both values in 1 textbox but I want both values in two different textboxes.
HTML
This is my html page:
<%--
Document : Test
Created on : Oct 10, 2017, 9:59:46 PM
Author : Lenovo
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="Bootstrap/bootstrap.css"/>
<title>JSP Page</title>
</head>
<body>
<form action="NameDB.jsp" method="post" name="add_name" id="add_name">
<table class="table table-bordered" border="1" id="dynamic_field">
<tr>
<th>Enter Name</th>
<th>Enter email</th>
</tr>
<tr>
<td><input type="text" name="name_1" placeholder="Enter Name" size="25" class="searchName" id="search1"/></td>
<td><input type="text" name="email_1" id="esearch1"/></td>
<td><input type="text" name="phone_1" id="psearch1"/></td>
<td>
<button type="button" name="add" id="add">Add More</button>
</td>
</tr>
</table>
<input type="submit" name="submit" value="Submit"/>
</form>
JQuery
This is my Jquery and Ajax
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
$(document).ready(function()
{
var i=1;
$('#add').click(function()
{
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><input type="text" id="search'+i+'" class="searchName" name="name_'+i+'" placeholder="Enter Name"/></td>\n\
<td><input type="text" id="esearch'+i+'" class="searchEmail" name="email_'+i+'"/></td>\n\
<td><input type="text" id="psearch'+i+'" class="searchPhone" name="phone_'+i+'" placeholder="Enter Phone"/></td>\n\
<td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td>\n\
<td><input type="hidden" name="count" value="'+i+'"/></td></tr>');
});
$(document).on('click','.btn_remove',function()
{
var button_id=$(this).attr("id");
$('#row'+button_id+'').remove();
});
$(document).on('change','.searchName',function()
{
var id=$(this).attr("id");
var name=$('#'+id).val();
//var email=$('#e'+id).val();
$.ajax({
url:"AjaxDB.jsp",
type:"post",
dataType:"text",
data:{name:name},
cache:false,
success:function(data)
{
//$('#show').html(data);
$('#e'+id).val(data);
}
});
});
});
AjaxDB.JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page language="java"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%
try
{
String name=request.getParameter("name");
String email=null;
String phone=null;
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/atm","root","root");
Statement st=con.createStatement();
ResultSet rs;
rs=st.executeQuery("SELECT * FROM test where name='"+name+"'");
while(rs.next())
{
email=rs.getString("email");
phone=rs.getString("phone");
out.print(email);
out.print(phone);
}
}
catch(Exception e)
{
System.out.println(e);
}
%>
If you want to receive data from server, then it is recommend to use JSON. You are sending data as plain text from "AjaxDB.JSP"
If response is by using JSON, then you should Servlet instead of JSP page.
Both following points are explained through code:
Your servlet code might be following:
import javax.servlet.http.*;
import javax.servlet.*;
import java.io.*;
import org.json.simple.*;
public class DemoServlet extends HttpServlet {
public void doGet(HttpServletRequest req,HttpServletResponse res)
throws ServletException,IOException
{
res.setContentType("application/json");//setting the content type
PrintWriter pw=res.getWriter();//get the stream to write the data
JSONObject response = new JSONObject();
try {
String name=request.getParameter("name");
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/atm","root","root");
Statement st=con.createStatement();
ResultSet rs;
rs=st.executeQuery("SELECT * FROM test where name='"+name+"'");
JSONArray list = new JSONArray();
while(rs.next()) {
JSONObject obj = new JSONObject();
obj.put("email",rs.getString("email"));
obj.put("email",rs.getString("phone"));
list.add(obj);
}
response.put("response", list);
} catch(Exception e) {
System.out.println(e);
}
pw.println(response.toJSONString());
pw.close();//closing the stream
}
}
And your client side code can be following:
$.ajax({
url:"AjaxDB.jsp",
type:"post",
dataType:"json",
data:{name:name},
cache:false,
success:function(data) {
console.log(data);
console.log(data.response[0].email);
console.log(data.response[0].phone);
}
});
});
Special Note: The code is untested. So debug if any error found!
I am creating a web application in java jsp using Eclipse and Tomcat.but I am stock unable to insert the data in to my local SQL server. The Form of the page is coded in HTML then I want the Java code part to get the data entered and insert the data in to the database but when I click the submit button absolutely nothing happens, no error message, no warning so far I am only able to type and clear the form. I am very new in Java. I just pick up this codding language recently but I am determine to learn it.
Help please here is my full code.
<%# page import="java.text.*,java.util.*" session="false"%>
<%# page import="java.sql.*" %>
<%#page import="javax.swing.JOptionPane" %>
<%#page import="java.util.Date" %>
<%#page import ="java.io.IOException" %>
<%#page import ="javax.servlet.ServletException" %>
<%#page import ="javax.servlet.http.HttpServlet" %>
<%#page import ="javax.servlet.http.HttpServletRequest" %>
<%#page import ="javax.servlet.http.HttpServletResponse" %>
<% Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert Laptops Data</title>
<link rel="stylesheet" href="Style.css" type="text/css">
</head>
<body>
<%!public class Insert extends HttpServlet {
String dbURL = "jdbc:sqlserver://localhost\\SQLYRSIN";
String user = "pass";
String pass = "pass";
Connection conn = null;
PreparedStatement InsertLaptops = null;
ResultSet resultSet = null;
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String LaptopMake, LaptopModel, LaptopServicetag, LaptopDatein, LaptopNotes, LaptopType;
LaptopMake = req.getParameter("iMake");
LaptopModel = req.getParameter("iModel");
LaptopServicetag = req.getParameter("iServiceTag");
LaptopDatein = req.getParameter("iDatein");
LaptopNotes = req.getParameter("iNotes");
LaptopType = req.getParameter("iType");
try {
conn = DriverManager.getConnection(dbURL, user, pass);
Statement st = conn. createStatement();
st.executeUpdate("INSERT INTO LaptopsTable (Make, Model, [Service Tag], Datein, Notes, Type)"
+ " VALUES ('"+LaptopMake+"','"+LaptopModel+"','"+LaptopServicetag+"','"+LaptopDatein +"','"+LaptopNotes+"','"+LaptopType+"')");
JOptionPane.showConfirmDialog(null, "Your Data Has been Inserted", "Result", JOptionPane.DEFAULT_OPTION,
JOptionPane.PLAIN_MESSAGE);
st.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}%>
<div id="header">
<div class="logo">
<span> Resident Screening</span> Jinventory
</div>
</div>
<div id="container">
<div class="content">
<h1>Add New Laptop</h1>
<p>Make sure all Service Tag Enter in here are Laptops</p>
<div id="box">
<form name="LaptopsForm" method="get" class="contentfonts"
action="LaptopsInsert2.jsp" method="Post">
<table>
<tbody>
<tr>
<td>Service Tag</td>
<td><input type="text" name="iServiceTag" size="40"></td>
</tr>
<tr>
<td>Make</td>
<td><input type="text" name="iMake" size="40"></td>
</tr>
<tr>
<td>Model</td>
<td><input type="text" name="iModel"></td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="iDate"></td>
</tr>
<tr>
<td>Type</td>
<td><input type="text" name="iTyped" Value="Laptop"
disabled="disabled"></td>
</tr>
<tr>
<td>Notes</td>
<td><input Type="text" name="iNotes" size="30" height="40"></td>
</tr>
<tr>
<td><input type="reset" name="Reset"></td>
<td><input type="submit" name="submit"></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
Here's a draft which you could use as a starting point.
As mentioned before, you should seriously consider some changes to your design:
Separate View (.jsp) from Business-Logic (SQL-Statements etc.)
Don't use scriptlets ( <% and so on )
Creating a Servlet within JSP is overkill - a JSP is compiled into a servlet by the servlet container.
Don't create Connections one-by-one. Use a connection pool. This will pay off quickly.
In the code you'll see some changes to your setup:
form is submitted per POST
instead of subclass, JSP checks for methods POST and only then tries the insert.
never ever use Swing inside Webapps. If that JOptionPane was opened, your webapp would block at that point, while the Dialog was shown somewhere on your server.
Use of PreparedStatement instead of Statement this prevents SQL injection. You'll still want to check against Cross-Site-Scripting if you plan on displaying the inserted values in your webapp again.
Disclaimer: I haven't tested or even tried to compile this code. Edit was done only to point you in the right direction.
Here it goes
<%#page import="java.text.*,java.util.*" session="false"%>
<%#page import="java.sql.*" %>
<%#page import="java.util.Date" %>
<%#page import ="java.io.IOException" %>
<%#page import ="javax.servlet.ServletException" %>
<%#page import ="javax.servlet.http.HttpServlet" %>
<%#page import ="javax.servlet.http.HttpServletRequest" %>
<%#page import ="javax.servlet.http.HttpServletResponse" %>
<% Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver"); %>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert Laptops Data</title>
<link rel="stylesheet" href="Style.css" type="text/css">
</head>
<body>
<%
if("POST".equals(request.getMethod()) {
String dbURL = "jdbc:sqlserver://localhost\\SQLYRSIN";
String user = "pass";
String pass = "pass";
Connection conn = null;
PreparedStatement InsertLaptops = null;
ResultSet resultSet = null;
String LaptopMake, LaptopModel, LaptopServicetag, LaptopDatein, LaptopNotes, LaptopType;
LaptopMake = req.getParameter("iMake");
LaptopModel = req.getParameter("iModel");
LaptopServicetag = req.getParameter("iServiceTag");
LaptopDatein = req.getParameter("iDatein");
LaptopNotes = req.getParameter("iNotes");
LaptopType = req.getParameter("iType");
try {
conn = DriverManager.getConnection(dbURL, user, pass);
PreparedStatement st = conn.prepareStatement("INSERT INTO LaptopsTable (Make, Model, [Service Tag], Datein, Notes, Type) VALUES (?,?,?,?,?,?)");
st.setString(1, LaptopMake);
st.setString(2, LaptopModel);
st.setString(3, LaptopServicetag);
st.setString(4, LaptopDatein);
st.setString(5, LaptopNotes);
st.setString(6, LaptopType);
st.executeUpdate();
//This is SWING - and would at best popup a Dialog ON YOUR SERVER
//JOptionPane.showConfirmDialog(null, "Your Data Has been Inserted", "Result", JOptionPane.DEFAULT_OPTION,
// JOptionPane.PLAIN_MESSAGE);
//Alternative: Show some HTML.
%>
<h1>Your Data has been inserted.</h1>
<%
st.close();
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
} //END of Method.equals("POST")
%>
<div id="header">
<div class="logo">
<span> Resident Screening</span> Jinventory
</div>
</div>
<div id="container">
<div class="content">
<h1>Add New Laptop</h1>
<p>Make sure all Service Tag Enter in here are Laptops</p>
<div id="box">
<form name="LaptopsForm" method="POST" class="contentfonts"
action="" method="POST">
<table>
<tbody>
<tr>
<td>Service Tag</td>
<td><input type="text" name="iServiceTag" size="40"></td>
</tr>
<tr>
<td>Make</td>
<td><input type="text" name="iMake" size="40"></td>
</tr>
<tr>
<td>Model</td>
<td><input type="text" name="iModel"></td>
</tr>
<tr>
<td>Date</td>
<td><input type="date" name="iDate"></td>
</tr>
<tr>
<td>Type</td>
<td><input type="text" name="iTyped" Value="Laptop"
disabled="disabled"></td>
</tr>
<tr>
<td>Notes</td>
<td><input Type="text" name="iNotes" size="30" height="40"></td>
</tr>
<tr>
<td><input type="reset" name="Reset"></td>
<td><input type="submit" name="submit"></td>
</tr>
</tbody>
</table>
</form>
</div>
</div>
</div>
</body>
</html>
Now i am doing this code which is working on submit button click.
<%#page import="java.sql.CallableStatement"%>
<%#page import="javax.imageio.ImageIO"%>
<%#page import="java.io.ByteArrayOutputStream"%>
<%#page import="java.awt.image.BufferedImage"%>
<%#page import="java.io.InputStream"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="connectionss.Connectionss"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="ShowUSerInfo.jsp" method="post">
<input type="text" name="tagID">
<input type="submit" value="Search" name="submit" >
</form>
<%
String TAGID="";
String y=request.getParameter("submit");
if("Search".equals(y))
{
TAGID = request.getParameter("tagID");
out.println(TAGID);
String GetUserpass = "{call sp_USerInfoByTagID(?)}";
//Connection conn = Connection.GetConnection();
CallableStatement cs;
cs = Connectionss.GetConnection().prepareCall(GetUserpass);
cs.setString(1,TAGID);
%>
<table border="1">
<th>First Name</th>
<th>last Name Name</th>
<th>Student ID</th>
<th>Address</th>
<th>NIC</th>
<%
ResultSet rs1;
rs1=cs.executeQuery();
while(rs1.next()){
String UserName=rs1.getString("fId_FirstName");
String UserID= rs1.getString("fId_User_UniversityID");
String Adress = rs1.getString("fId_Address");
String NIC = rs1.getString("fId_NIC");
String lastName = rs1.getString("fId_LastName");
%>
<tr >
<td><span style="color:red;"><%= UserName %></span></td>
<td> <span style="color:red;"><%= lastName %></span></td>
<td><span style="color:red;"><%= UserID %></span></td>
<td><span style="color:red;"><%= Adress %></span></td>
<td><span style="color:red;"><%= NIC %></span></td>
</tr>
</table>
<%}} %>
</body>
</html>
But i want to execute this code when text changes on input box. Basically text box is getting value from NFC cards. so when i tap my NFC card on Reader value is transfer to text box and at this time i want to execute my sql query that will take the user information against TAGID.
since jsp is server side you'll need to collect the input on client and make a ajax call.
<form action="ShowUSerInfo.jsp" method="post">
<input type="text" id="text" name="tagID">
<input type="submit" value="Search" name="submit" >
</form>
<div id="#res></div>
javascript :
$('#text').change(function(e){
$.ajax({url: "someurl", success: function(result){
$("#res").html(result);
}});
});
});
this will perfectly work in your case,
Let's say our HTML looks something like,
<form>
<input id="txt" type="text" name="name"/>
<input id="btn" type="button" value="change"/>
</form>
Java-Script like,
$(document).ready(function(){
$('#txt').keypress(function(e){
ontextchange();
});
$('#txt').keyup(function(e){
if(e.keyCode == 8)
{
//if user erase from text-box then comes here...
}
});
function ontextchange(){
//do whatever while text change, i.e. ajax call or something else...
}
});
I have one demo code where I have three jsp named arabic1.jsp, arabic2.jsp, arabic3.jsp and one servlet named ArabicServlet.
Inside arabic1.jsp I have one textbox where I entered arabic value and submitted the page by calling ArabicServlet servlet, which forward same content to arabic2.jsp, where I have displayed the same content inside textbox which is correctly displayed.
Now I have one link on arabic2.jsp to forward request on arabic3.jsp using same servlet and content, here on arabic3.jsp I have displayed same arabic content inside textbox but I got wrong characters.
I am entering value on first jsp as محمد , It is shown on third jsp as ÙØÙد
arabic1.jsp
<%# page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
</head>
<body>
<form action="/test/ArabicServlet" method="post">
<table name="tbl1" id="tbl1">
<tr>
<td>
<input type="hidden" id="page" name="page" value="1"/>
</td>
<td>
Name :
</td>
<td>
<input type="text" id="arabic" name="arabic">
</td>
<td>
<input type="submit" id="arabic" name="arabic">
</td>
</tr>
</table>
</form>
</body>
</html>
arabic2.jsp
<%# page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<%
Map map = (Hashtable)request.getAttribute("arabic");
String arabicvalue = (String)map.get("arabicmap");
System.out.println("Arabic Value on jsp = "+arabicvalue);
String url = "/test/ArabicServlet?page=2&arabicvalue="+arabicvalue;
%>
</head>
<body>
<form action="/test/ArabicServlet" method="post">
<table name="tbl1" id="tbl1">
<tr>
<td>
Name :
</td>
<td>
<input type="text" id="arabic" name="arabic" value="<%=arabicvalue%>">
</td>
<td>
Test
</td>
</tr>
</table>
</form>
</body>
</html>
arabic3.jsp
<%# page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<html>
<head>
<%
Map map = (Hashtable)request.getAttribute("arabic");
String arabicvalue = (String)map.get("arabicmap");
System.out.println("Arabic Value on jsp = "+arabicvalue);
String url = "/test/ArabicServlet?page=2&arabicvalue="+arabicvalue;
%>
</head>
<body>
<form action="/test/ArabicServlet" method="post">
<table name="tbl1" id="tbl1">
<tr>
<td>
Name :
</td>
<td>
<input type="text" id="arabic" name="arabic" value="<%=arabicvalue%>">
</td>
</tr>
</table>
</form>
</body>
</html>
ArabicServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
request.setCharacterEncoding("UTF-8");
String page = request.getParameter("page");
System.out.println("Page Number = "+page);
if(page.equals("1")){
String arabic = (String)request.getParameter("arabic");
System.out.println("Arabic Value from first page = "+arabic);
Map map = new java.util.Hashtable();
map.put("arabicmap",arabic);
request.setAttribute("arabic",map);
request.getRequestDispatcher("arabic2.jsp").forward(request,response);
}else{
String arabic = (String)request.getParameter("arabicvalue");
Map map = new java.util.Hashtable();
map.put("arabicmap",arabic);
request.setAttribute("arabic",map);
System.out.println("Arabic Value from first page = "+arabic);
request.getRequestDispatcher("arabic3.jsp").forward(request,response);
}
}
I resolve similar problem by putting these lines in my code:
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
Objective: If I type an email id, in the html form it has to send the request to jsp where it does the logic and has to print(in the html form) whether the email is available or not. I have the following code. Please do help me which part I am doing wrong.
CreateAccount.html
<!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=ISO-8859-1">
<script type="text/javascript" src="emailStore.js"></script>
</head>
<body onload="process()">
<form name="login">
<table align="center">
<tr>
<td>Email*</td>
<td><input type="text" name="userinput" id="userinput"/></td>
<td><div id = "underInput"></div></td>
</tr>
<tr>
<td>Password*</td>
<td><input type="password" name="pswrd" /></td>
</tr>
<tr>
<td>Repeat Password*</td>
<td><input type="password" name="pswrd1" /></td>
</tr>
<tr>
<td>First Name*</td>
<td><input type="text" name="userid" /></td>
</tr>
<tr>
<td>Last Name*</td>
<td><input type="text" name="userid" /></td>
</tr>
<tr>
<td>Phone Number</td>
<td><input type="text" name="userid" /></td>
</tr>
</table>
<div style="text-align: center">
<input type="submit" value="Create Account"/>
</div>
</form>
</body>
</html>
The ajax part in a javascript file. emailStore.js
var xmlHttp = createXmlHttpRequestObject();
function createXmlHttpRequest()
{
var xmlHttp;
if(window.ActiveXObject)
{
try
{
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch(e)
{
xmlHttp = false;
}
}
else
{
try
{
xmlHttp = new ActiveXObject();
}
catch(e)
{
xmlHttp = false;
}
}
if(!xmlHttp)
{
alert("can't create that object");
}
else
{
return xmlHttp;
}
}
function process()
{
if(xmlHttp.readyState==0 || xmlHttp.readyState==4)
{
email = encodeURIComponent(document.getElementById("userinput").value);
xmlHttp.open("GET", "emailStore.jsp?email=" + email, true);
xml.onreadystatechange = handle.ServerResponse;
xmlHttp.send(null);
}
else
{
setTimeout('process()', 1000);
}
}
function handleServerResponse()
{
if(xmlHttp.readyState==4)
{
if(xmlHttp.status==200)
{
xmlResponse = xmlHttp.responseXML;
xmlDocumentElement = xmlResponse.documentElement;
message = xmlDocumentElement.firstChild.data;
document.getElementById("underInput").innerHTML = '<span style = "color:blue">' + message + '</span>';
setTimeout('process()',1000);
}
else
{
alert('Something went Wrong');
}
}
}
And the logic part in a jsp file- emailStore.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.util.ArrayList"%>
<!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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<%
String email = request.getParameter("userinput");
ArrayList<String> emails = new ArrayList<String>();
emails.add("something#gmail.com");
if (emails.contains(email)) {
out.println("Email already taken!");
} else {
out.println("Email available");
}
%>
</body>
</html>
I would advise you of the following:
Use library JQuery;
Use Servlet instead of the JSP;
Keep a list in the session;
Do not use a tabular layout. Instead, use div- layers, and cascading style sheets.
Here is a simple example, front- end part is ..
<head>
...
<script>
$(document).ready(function() {
$('#submit').click(function(event) {
var input=$('#userinput').val();
$.get('ActionServlet',{userinput:input},function(responseText) {
$('#underInput').text(responseText);
});
});
});
</script>
...
</head>
<body>
...
<form id="form1">
...
Email
<input type="text" id="userinput"/>
<input type="button" id="submit" value="Submit"/>
<br/>
<div id="underInput">
</div>
...
</form>
...
</body>
</html>
..and server side -
...
public class ActionServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ActionServlet() {
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String answer = "Something went Wrong";
String userinput = request.getParameter("userinput").toString();
HttpSession httpSession = request.getSession(true);
if(httpSession.isNew()) {
httpSession.setAttribute("sessionVar", new ArrayList<String>());
}
List<String> arrayList = (ArrayList<String>)httpSession.getAttribute("sessionVar");
if(userinput != null && !userinput.equals("")) {
if(arrayList.contains(userinput)) {
answer = "Email already taken!";
} else {
arrayList.add(userinput);
answer = "Email available";
}
}
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(answer);
}
...