Ajax response doesn't display in JSP page - java

I'm Trying to Save small record using JSP ajax in technology. The project working procedure is like this.
01. index.jsp : Send data to SaveStudent servlet
02. SaveStudent : Get request form jsp and send it to validation java class
03. Validation : Validate data and Send to DaoImpl java class
04. DaoImpl : Override the method in StudentDAO, Do the save SQL query.
05. StudentDAO : A interface has all the database related methods.
Here is the image of the project.
Given below is index.jsp files source code.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script src="//code.jquery.com/jquery-migrate-1.2.1.min.js"></script>
</head>
<body>
<form action="SaveStudent" method="post">
<label>Enter Name:</label>
<input type="text" name="name" id="txtName"/>
<br/>
<label>Enter City:</label>
<input type="text" name="city" id="txtCity"/>
<br/>
<input type="submit" value="Send" id="btnSave"/>
<div id="response"></div>
</form>
<script type="text/javascript">
$(document).ready(function() {
$('#btnSave').click(function() {
var $name = $("#txtName").val();
var $city = $("#txtCity").val();
$.post('SaveStudent', {
name: $name,
city: $city
}, function(responseText) {
if (responseText !== null) {
$('#response').text(responseText);
} else {
alert("Invalid Name");
}
});
});
});
</script>
</body>
Here is SaveStudent java class's source code.
package Control;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Model.Validation;
public class SaveStudent extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
String record = "";
try {
Validation val = new Validation();
record = val.validateSave(request, response);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
if (record != null) {
out.write(record);
} else {
out.print("Error Occured..!");
}
} catch (Exception e) {
e.printStackTrace();
} finally {
out.close();
}
}
}
Save record is working fine. Database is also updating. But the problem is The "Save Successful" message is appears in servlet page. Not under the jsp page.
Please help me on this. Thank you.

I figure out a way. I put replace "submit" type to "button". Now working perfectly. Thank you for your Time.

Related

I am sending form data using jsp ajax to servlet and But ajax response gets disappear within nano seconds

I am sending form data using Jsp through AJAX on Servlet.
reg.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
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>Insert title here</title>
</head>
<body>
<form>
Enter name:<input type="text" id="name" /> <br />
<button onclick="callJqueryAjax()">Save</button>
</form>
<span id="result"></span>
<script
src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script type="text/javascript">
function callJqueryAjax() {
location.reload(false);
var name = $('#name').val();
console.log(name);
$.ajax({
url : 'Save',
method : 'POST',
data : {
name : name,
},
success : function(resultText) {
$("#result").html(resultText);
}
});
}
</script>
</body>
</html>
SaveMe.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/Save")
public class SaveMe extends HttpServlet {
private static final long serialVersionUID = 1L;
private Connection makeCon;
private Statement stmt;
public void init(ServletConfig config) throws ServletException {
JdbcCon jdbcCon = new JdbcCon();
makeCon = jdbcCon.makeCon();
try {
stmt = makeCon.createStatement();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
protected void doPost(HttpServletRequest request, HttpServletResponse res) throws ServletException, IOException {
String name = request.getParameter("name");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String sql = "insert into users (name) Values('" + name + "')";
System.out.println(sql);
try {
int result = stmt.executeUpdate(sql);
if (result > 0) {
out.print("Inserted");
} else
out.print("Not Inserted");
} catch (SQLException e) {
}
}
}
I receive the output in ajax but the thing is JSP gets reload by itself and removes the response as well as removes the data from Textbox from which my response gets disappear by itself.
Please provide me the solution and also a better way for writing an ajax call
First of all I didn't understand why you are using "location.reload(false);" in your JSP page before submitting the ajax request.
You could remove it.
In addition a good practice when using ajax request is to specify the "dataType", in your case "html".
Here is an example:
$.ajax( {
type : 'POST',
url : 'SaveMe',
success : function(result) {
$("#result").html(result);
},
dataType : "html"
});

How can I Post parameter from JSP to HTTP using Java

I want to sent parameter from JSP to HTTP Servlet. but it doesn't work:(
I would like create a button to sent information to disable/enable user.
I'm still new to JSP and HTTP.
I hope can some one help me.
I hope it's enough to Overview
here my code:
admin.jsp
<%#page import="model.*"%>
<%#page import="java.util.*"%>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%
List<Category> categories = (List<Category>) request.getAttribute("categories");
List<User> users = (List<User>) request.getAttribute("users");
User credentials = (User) request.getSession().getAttribute("credentials");
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<jsp:include page="header.jsp"></jsp:include>
<jsp:include page="/WEB-INF/navbar.jsp"></jsp:include>
<h1 style="color:green;">Admin Control Page</h1>
<h2>categories</h2>
<% for (Category category : categories) { %>
<%=category.getName()%><br/>
<% } %>
<form method="post" action="<%=request.getContextPath()%>/admin" accept-charset="iso-8859-1">
<br/>
add new category: <input name="categoryName" />
<input type="hidden" name="event" value="createCategory" />
<input type="submit" />
</form>
<h2>users</h2>
<% for (User user : users){
if(user.getRole().getId()!= 1){
out.println("<a href='"+request.getContextPath()+"/user/"+user.getUsername()+"'><b>"+user.getUsername()+"</b></a>");
int id = user.getId();
%>
<%if(user.isEnabled()){ %>
//My Problem is here
<form action="/admin" method="POST">
<input value="<%user.getId();%>">
<input type="submit" value="Submit" />
</form>
<%}else if(!user.isEnabled()){
%>
// TODO Button
<%}%>
<p><hr>
<%
}
}
%>
</body>
</html>
AdminController.java
package controller;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import dao.DatabaseManager;
import model.Category;
import model.User;
#WebServlet("/admin/*")
public class AdminController extends HttpServlet {
private DatabaseManager db = DatabaseManager.getInstance();
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// check admin, if not "error"
User user = (User) req.getSession().getAttribute("credentials");
if (user == null || !user.getRole().getName().equals("admin")) {
resp.sendError(403);
return;
}
// load page
req.setAttribute("categories", db.getCategoryDAO().findAll());
req.setAttribute("users", db.getUserDAO().findAll());
req.getRequestDispatcher("/WEB-INF/admin.jsp").forward(req, resp);
}
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// event
String event = req.getParameter("event");
// create new category
if (event.equals("createCategory")) {
String categoryName = req.getParameter("categoryName").trim();
try {
Category cat = new Category();
cat.setName(categoryName);
db.getCategoryDAO().create(cat);
} catch (IllegalArgumentException e) {
// error
req.setAttribute("msg", e.getMessage());
doGet(req, resp);
return;
}
// Create successful
resp.sendRedirect(req.getContextPath() + "/admin");
return;
}
String idTemp = req.getParameter("id");
try{
int id = Integer.parseInt(idTemp);
User user = db.getUserDAO().findById(id);
user.setEnabled(false);
} catch(IllegalArgumentException e){
e.getMessage();
return;
}
resp.sendRedirect(req.getContextPath() + "/admin");
return;
}
}
Change
#WebServlet("/admin/*")
To
#WebServlet("/admin")
And you can use either:
action="<%=request.getContextPath()%>/admin" or action="admin".
And if you are still having error then mention the error name :)

HttpServlet - add context to html page

I want to understand how a html page can call a servlet to add elements to its body but i can't find the right way to achieve that can you give me or refer me to an example of doing this?
Example:
lets suppose there is an html page with a form that contains a button with:
name="I am"
value="the button"
Example scenario:
click this button
call a servlet
add a message to this page saying "I am the button"
many thanks for any guidance.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script type="text/javascript">
$("#btn").click(function() {
$.post("buttonServlet", function (response) {
alert(response);
});
});
</script>
<!DOCTYPE HTML>
<html lang="en-US">
<head>
<meta charset="UTF-8">
<title>My Button</title>
</head>
<body>
<input type="button" name="btn" id ="btn" value="The Button" />
</body>
</html>
package servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/buttonServlet")
public class ButtonServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("I am the button");
}
}
You can do this by using Ajax.
In your html page contain a button ,
<input type="submit" id="button1" value="the button" name="I am" onclick="showMsg()" />
Implement ajax,
function showMsg() {
var buttonMsg = document.getElementById("button1").name + document.getElementById("button1").value;
$.ajax({
url: "yourservlet",
type: "post",
data:{'msgVar': buttonMsg} ,
cache: false,
success: function (data) {
//depends on the method you want to show your message
//the variable data contain the message you want
alert(data); //to show in popout message
}
});
}
Assuming your servlet POST method contain following variable
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String message = request.getparameter("msgVar");
out.println(message);

two jsp's that are mixed up in contents! (the second jsp loads over the first one)

I want to read in a textbox a name and I want to pass-it to the next form, and it would be a problem that the form doesn't reset to show only the second form, "basic.jsp". Is there any command to reset the form? Now it shows me the content of basic.jsp mixed up with the index.jsp (request of the name)...
-HelloWorld.java:
package javapapers.sample.ajax;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class HelloWorld extends HttpServlet {
public void doPost(HttpServletRequest req, HttpServletResponse res)
throws java.io.IOException, ServletException {
res.setContentType("text/html");
res.getWriter().write("Hey!");
String textNume = req.getParameter("userInput");
req.setAttribute("nume",textNume);
RequestDispatcher requestDispatcher = req.getRequestDispatcher("basic.jsp");
requestDispatcher.forward(req,res);
}
}
- index.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript" language="javascript" src="ajax.js"></script>
</head>
<body>
<BR>Please enter your name:<input type='text' id='userInput'/>
<div id="hello"><button type="button" onclick="makeRequest()">Adauga</button></div>
<div id="ttt"><input type="text"></input></div>
<p>Welcome to the site <b id='boldStuff'>dude</b> </p>
</script>
</body>
</html>
- ajax.js:
function getXMLHttpRequest() {
var xmlHttpReq = false;
// to create XMLHttpRequest object in non-Microsoft browsers
if (window.XMLHttpRequest) {
xmlHttpReq = new XMLHttpRequest();
} else if (window.ActiveXObject) {
try {
// to create XMLHttpRequest object in later versions of Internet Explorer
xmlHttpReq = new ActiveXObject("Msxml2.XMLHTTP");
} catch (exp1) {
try {
// to create XMLHttpRequest object in older versions of Internet Explorer
xmlHttpReq = new ActiveXObject("Microsoft.XMLHTTP");
} catch (exp2) {
xmlHttpReq = false;
}
}
}
return xmlHttpReq;
}
//AJAX call starts with this function
function makeRequest() {
var xmlHttpRequest = getXMLHttpRequest();
xmlHttpRequest.onreadystatechange = getReadyStateHandler(xmlHttpRequest);
xmlHttpRequest.open("POST", "helloWorld.do", true);
xmlHttpRequest.setRequestHeader("Content-Type","application/x-www-form-urlencoded");
var userInputValue = document.getElementById('userInput').value;
xmlHttpRequest.send("userInput=" + userInputValue);
}
function getReadyStateHandler(xmlHttpRequest) {
// an anonymous function returned it listens to the XMLHttpRequest instance
return function() {
if (xmlHttpRequest.readyState == 4) {
if (xmlHttpRequest.status == 200) {
var userInput = document.getElementById("userInput").value;
document.getElementById("hello").innerHTML = xmlHttpRequest.responseText; //"hey" def.in java!
document.getElementById("ttt").innerHTML = userInput;
} else {
alert("HTTP error " + xmlHttpRequest.status + ": " + xmlHttpRequest.statusText);
}
}
};
}
- basic.jsp:
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<HTML>
<HEAD>
<TITLE>Elemente de identificare</TITLE>
</HEAD>
<BODY>
<H1>Elemente de identificare</H1>
Domnule <%= request.getAttribute("nume") %> alegeti elementele de identificare:<br>
Felul notificarii<br>
<select name="fel_notif">
<option value="Prima notificare">Prima notificare</option>
<%--<option value="Monday" selected>Monday</option>--%>
</select><br>
Mailul dvs <br><textarea rows="1" cols="30" name="mail"></textarea><br>
Caracterizare <br><textarea rows="3" cols="30" name="caract"></textarea><br>
Circumstante <br><textarea rows="3" cols="30" name="circ"></textarea><br>
Masuri de atenuare <br><textarea rows="3" cols="30" name="masuri"></textarea><br>
Cod notificare: <input type="text" name="cod" value="scot din BD" readonly><br>
<INPUT TYPE="SUBMIT" value="Trimite">
<%--<script type="text/javascript" language="javascript" src="ajax.js"></script>
<div id="pdf"><button type="button" onclick="makeRequest()">Creaza PDF</button></div>--%>
</BODY>
</HTML>
Your not sending userInput to the server. You have to add it to the request to be able to receive it in the servlet. Now you're just doing xmlHttpRequest.send(null). Instead, send the parameter string representing the data from your input. Something like:
xmlHttpRequest.send("userInput=" + userInputValue);

upload image with imagename using jquery file upload

I'm using AjaxFileUpload for uploading a file with some data (inputbox). Whenever I'm trying to upload the file, it shows File Uploading... and then gets stuck for a while. I checked my database, but found there was no effect on it.
Below is what I've done so far.
index.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>
<title>Ajax File Upload</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="ajaxfileupload.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$("#login_frm").submit(function(){
//remove previous class and add new "myinfo" class
// e.preventDefault();
$("#msgbox1").removeClass().addClass('myinfo').text('Uploading .... ').fadeIn(1000);
$.ajaxFileUpload({
url :'AddPhoto',
secureuri:false,
fileElementId:'image',
dataType: 'json',
success: function(msg){
// alert(msg.MSG)
$("#msgbox1").removeClass().addClass('myinfo').text(msg.MSG).fadeIn(1000);
if(msg.MSG=="Image Successfully Uploaded!!")
{
document.getElementById("image").disabled="disabled";
}
}
});
return false;
});
});
</script>
<link href="style.css" rel="stylesheet" type="text/css" />
<link href="login_style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<form name="login_frm" id="login_frm" action="" method="post">
<div id="login_box">
<div id="login_header"> Citizen Login </div>
<div id="form_val" style="background-color:black">
<div class="label">Image Name :</div>
<div class="control"><input type="text" name="imgname" id="imgname"/></div>
<div style="clear:both;height:0px;"></div>
<div id="msgbox"></div>
<div class="label">Photograph :</div>
<div class="control"><input type="file" name="image" id="image"/></div>
<div style="clear:both;height:0px;"></div>
<div id="msgbox1"></div>
</div>
<div id="login_footer">
<label>
<input type="submit" name="upload" id="upload" value="Upload" class="send_button" />
</label>
</div>
</div>
</form>
</body>
AddPhoto.java
package fileupload;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class AddPhoto extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
try {
// Apache Commons-Fileupload library classes
DiskFileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sfu = new ServletFileUpload(factory);
if (!ServletFileUpload.isMultipartContent(request)) {
out.print("{MSG:'File Not Uploaded !!'}");
return;
} else {
// parse request
out.print("{MSG:'File Uploading....'}");
List items = sfu.parseRequest(request);
FileItem file = (FileItem) items.get(0);
String type = file.getContentType();
int size = (int) (file.getSize() / 1024);
//String name="images";
String name = file.getFieldName();
out.println("{MSG:'Error" +size+ "'}");
if (name.equals("image")) {
if ((type.equals("image/jpeg")) && ((size < 201) && (size > 10))) {
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe", "epolicia", "admin");
con.setAutoCommit(false);
PreparedStatement ps = con.prepareStatement("insert into images(image) values(?)");
ps.setBinaryStream(1, file.getInputStream(), (int) file.getSize());
ps.executeUpdate();
con.commit();
con.close();
out.println("{MSG:'ID Proof Successfully Uploaded !!'}");
} else {
out.print("{MSG:'ID Proof is not jpg or its more than 200kb!!'}");
}
} else {
out.print("{MSG:'File Not Uploaded !!'}");
}
}
} catch (Exception ex) {
out.println("{MSG:'Error" + ex.getMessage() + "'}");
}
}
}
Regarding to your question, I have 2 points:
Check there: Asynchronous file upload (AJAX file upload) using jsp and javascript.
Ajax File uploader is no good choice if you use JSP. Read that topic.
An advice: do not use
if(msg.MSG=="Image Successfully Uploaded!!")
to compare results. Just try
if(msg.MSG === 1) { // or msg.MSG === true
//process and show the successfully uploaded string
}
That's all. I hope these could help you.

Categories

Resources