Javascript pop up message in JSP - javascript

Without creating a new page jsp file, is there a way I can make a popup "Data inserted successfully" message appear after I have inserted registration data into a table successfully.
Pop up in the sense that no new browser window is created but the message appears in a new box within the current web page and when clicked "Ok", redirects me to the next web page in the TRY SECTION.
<%#page import="com.mysql.jdbc.Statement"%>
<%#page import="com.mysql.jdbc.Connection"%>
<%#page import="java.sql.DriverManager"%>
<%Class.forName("com.mysql.jdbc.Driver");%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration Page</title>
</head>
<body>
<%!
String firstname, lastname, address, phoneNo;
String sex, password;
%>
<%
firstname = lastname = address = phoneNo= "";
sex = ""; password = "";
firstname = request.getParameter("firstname");
lastname = request.getParameter("lastname");
address= request.getParameter("address").trim();
phoneNo = request.getParameter("phoneNo");
sex = request.getParameter("Sex");
password = request.getParameter("password");
if(firstname.equals("")|| lastname.equals("")|| phoneNo.equals("")||
sex.equals("")|| password.equals(""))
{
out.write("Empty fields, make sure you input data into all field before pushing the " +
"REGISTER button");
}
else
{
String sql1="INSERT INTO customer_details VALUES('"+firstname+"', '"+lastname+"','"+address+"', '" +phoneNo+"',' "+sex+ "','"+password+"')";
String sql2 = "INSERT INTO verification VALUES('"+firstname+"', '"+password+"')";
try{
Connection conn = (Connection) DriverManager.getConnection("jdbc:mysql://localhost/" + "onlineburgerapp","root", "root");
Statement st = (Statement) conn.createStatement();
st.executeUpdate(sql1);
st.executeUpdate(sql2);
conn.setAutoCommit(true);
conn.close();
response.sendRedirect("availableBurgers.jsp");
}
catch(Exception e){
e.printStackTrace();}
}
%>
</body>

You can insert JavaScript code into JSP code.
For example:
<%
try{
%>
<script type="text/javascript">
alert("Inserted Successfully");
</script>
<%
}catch(Exception e){
}
%>

If i understand properly your problem: if your SQL requests are successful, you want to display a 'success' message/popup to the user.
How do you request this JSP you show here?
If it is a classic webbrowser request (let's assume), since at the end, it redirects to the availableBurgers.jsp, this page won't send any content to your browser.
I would just set the success popup in the availableBurgers.jsp since this is your success page.

An improvement to the selected good answer:
if you want to customize your message with some variables you have:
<%
try {
String myVariable = "Successfully";
%>
<script type="text/javascript">
var myMessage;
<%
out.println("myMessage = \"I have inserted "+myVariable+"\"");
%>
alert(myMessage);
</script>
<%
} catch(Exception e) {
}
%>

Related

how to make jquery autocomplete ui using ajax in jsp

My problem is that jQuery UI AutoComplete is not working using AJAX in my JSP. I find many guides, but I cannot find the solution to my problem.
What I can do in this condition?
<%--
Document : Auto
Created on : Feb 13, 2018, 4:24:31 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" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<title>JSP Page</title>
</head>
<body>
<div class="ui-widget">
<input type="text" id="auto"/>
</div>
<script type="text/javascript">
$(function()
{
$('#auto').autocomplete(
{
source:function(request,response)
{
//Fetch data
$.ajax({
url:"Fetch.jsp",
method:"post",
dataType:'json',
data:{search:request.term},
success:function(data)
{
response(data.name);
}
});
}
});
});
</script>
</body>
</html>
This is my Fetch.jsp file:
<%#page import="org.json.JSONArray"%>
<%#page import="org.json.JSONObject"%>
<%# page contentType="text/html; charset=iso-8859-1" language="java"%>
<%#page language="java" %>
<%#page import="java.sql.*" %>
<%
try
{
String query = (String)request.getParameter("search");
JSONObject json=new JSONObject();
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/sample","root","root");
Statement st=con.createStatement();
ResultSet rs;
rs=st.executeQuery("select name from user2 where name like '"+query+"%'");
while(rs.next())
{
json.put("name",rs.getString("name"));
out.print(json.toString());
}
}
catch(Exception e1)
{
out.println(e1);
}
%>
Fetch.jsp should print a json array, not an object.
You are actually not printing a valid json, but json objects in sequence. You should print an array of the strings you got from the database.
Change:
JSONObject json=new JSONObject();
to
JSONArray json=new JSONArray();
and also change
while(rs.next())
{
json.put("name",rs.getString("name"));
out.print(json.toString());
}
to
while(rs.next())
{
json.put(rs.getString("name"));
}
out.print(json.toString());
And finally in your js:
success:function(data)
{
response(data);
}
From the docs:
A response callback, which expects a single argument: the data to suggest to the user. This data should be filtered based on the provided term... It's important, when providing a custom source callback, to handle errors during the request. You must always call the response callback even if you encounter an error. This ensures that the widget always has the correct state.
References
Jquery UI Autocomplete API source: array, string or callback

send parameter from js file to jsp file with ajax

Here is my js file where my goal is to send variable va to jsp file and output it. The problem I can't find the bug.
$(function(){
$("td").click(function(){
var date = $(this).html();
var message = prompt(year+"year "+month+"month "+ date+"day","null!");
this.append(message);
var variable = "mememem";
var sendData = new XMLHttpRequest();
sendData.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
alert("connected to server");
}
};
sendData.open('GET','dataFile.jsp?na='+variable,true);
sendData.send(null);
window.location = "dataFile.jsp";
})
});
///////////////////////////javascript file//////////////////////
<%# page language="java" contentType="text/html; charset=EUC-KR"
pageEncoding="EUC-KR"%>
<!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=EUC-KR">
<title>Insert title here</title>
</head>
<body>
<%
String name = request.getParameter("na");
out.print(name);
%>
</body>
</html>
///////////////////jsp file
I think the problem is you're sending variable instead of va.
This line:
sendData.open('GET','dataFile.jsp?na='+variable,true);
Hope that is the root cause of your problem.

Why is not the control moving to the script method "checkExistence()"?

I am doing a file upload program in which i am using ajax call to check whether any file exists with the same name.
Here is the code
jsp page
<%# taglib prefix = "form" uri = "http://www.springframework.org/tags/form"%>
<%# 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>File Upload Example</title>
<script src="/AjaxWithSpringMVC2Annotations/js/jquery.js"></script>
<script type="text/javascript">
function checkExistence() {
var name = $('#file').val();
File f=new File(name);
var filename=f.getOriginalFileName();
document.write(filename);
$.ajax({
type: "POST",
url: "/FileController/fileexists",
data: "filename=" + filename,
success: function(response){
if(response==0)
{
ch="zero";
document.fileform.choice.value=ch;
document.fileform.submit();
}
else if(response==1)
{
alertchoice=alert("File already exists !! Do you want me to overwrite it ?");
if(alertchoice==true || alertchoice.equals(true))
{
ch="one";
document.fileform.choice.value=ch;
document.fileform.submit();
}
else {
ch="two";
alert("Upload suspended as requested by the user ");
} }
},
error: function(e){
alert('Error: ' + e);
}
});
}
</script>
</head>
<body style="background-color:powderblue;color:Tomato">
<br>
<br>
<center><form name="fileform" action="savefile" method = "POST" modelAttribute = "fileUpload"
enctype = "multipart/form-data">
Please select a file to upload :
<input type = "file" name = "file" id="file"><br><br><br>
<input type="hidden" name="choice">
<input type = "button" value ="upload" onClick="checkExistence()">
<input type="reset" value="Reset">
</form></center>
<br>
<br>
<br>
<center><b> ${message} </b></center>
</body>
</html>
//controller class
#RequestMapping(value="/fileexists",method = RequestMethod.POST)
#ResponseBody public String checkingForDuplicates(HttpServletRequest req, HttpServletResponse res){
String filename=req.getParameter("filename");
int i=isDuplicate(filename);
return i+"";
}
Here when i am clicking the button upload , control should go to the function checkExistence() . But it is not moving. Is something wrong with my code ? And i am using
File f=new File(name);
var filename=f.getOriginalFileName();
in javascript function to get the name of the file being uploaded. Does it work ?
I got the answer by making the following corrections.
Including jquery plugin
changing ajax call url from
url: "/FileController/fileexists"
to
url: "fileexists"
In jsp page to get name of the file being uploaded
var name = $('#file').val();
File f=new File(name);
var filename=f.getOriginalFileName();
modified :
var filename=document.getElementById('file').value;
var lastIndex = filename.lastIndexOf("\\");
if (lastIndex >= 0) {
originalfilename = filename.substring(lastIndex +1);
}
In controller to get the file name(for checking duplicates)
previous : String filename=req.getParameter("filename");
modified : String filename=req.getParameter("originalfilename");

how to get error message if record is already present in table in jsp page

I have an index.jsp page from where I am inserting name and id into oracle table. I am able to insert successfully, but when user enters same employee id again index.jsp page redirects to tomcat error page says
HTTP Status 500 javax.servlet.ServletException: java.sql.SQLIntegrityConstraintViolationException: ORA-00001: unique constraint
I want to display an error note within index.jsp when user enters id which is already present in database.
<%# 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><center>
<H1>Inserting record into a Database</H1>
<%# page language="java" %>
<%# page import="java.sql.*" %>
<%# page import="java.sql.DriverManager.*" %>
<%
int flag=0;
PreparedStatement ps=null;
Connection con= null;
ResultSet rs= null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("hostname","user","admin");
Statement st=con.createStatement();
String id = request.getParameter("id");
String name= request.getParameter("name");
ResultSet resultset =
rs=st.executeQuery("INSERT INTO employee (employeeid,employeename)VALUES ('"+id+"','"+name+"");
out.println("Data is successfully inserted!");
%>
</center>
</body>
</html>
Use the try-catch block to handle the exception.
What you can do to prevent it from coming is to check if the record is already present in table or not.
If the same id is present then do not execute the insert operation.
try{
int flag=0;
PreparedStatement ps=null;
Connection con= null;
ResultSet rs= null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("hostname","user","admin");
Statement st=con.createStatement();
String id = request.getParameter("id");
String name= request.getParameter("name");
// Check if the "id" is already present in table or not
rs = st.executeQuery("SELECT * FROM employee WHERE employeeid" = id );
if (!rs.next() ) {
// id is not present then insert the new record
rs = st.executeQuery("INSERT INTO employee (employeeid,employeename)VALUES ('"+id+"','"+name+"");
System.out.println("Data is successfully inserted!");
} else{
// id is already present then show the error message
System.out.println("Data is already present in table!");
}
} catch(Exception e){
// Handle any other exception occuring
System.out.println("Exception : " + e.printStackTrace());
}
Enclose the code in try and catch block ,when the control goes to catch block handle the exception and display the message you want to display.
To be more specific, handle the exception SQLIntegrityConstraintViolationException. This exception indicates that an integrity constraint (foreign key, primary key or unique key) has been violated.
try{
int flag=0;
PreparedStatement ps=null;
Connection con= null;
ResultSet rs= null;
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("hostname","user","admin");
Statement st=con.createStatement();
String id = request.getParameter("id");
String name= request.getParameter("name");
ResultSet resultset =
rs=st.executeQuery("INSERT INTO employee (employeeid,employeename)VALUES ('"+id+"','"+name+"");
out.println("Data is successfully inserted!");
}catch(SQLIntegrityConstraintViolationException e ){
//Duplicate entry '' for key 'PRIMARY'
System.out.println(e.getMessage());//you can modify the output as per your requirement.
} catch (Exception e) {
e.printStackTrace();
}

Cannot clear session using javascript in jsp

created session from login.jsp page using servlet
String msg = "";
HttpSession sess = request.getSession();
// if(sess != null)
//sess.invalidate();
if (sess.getId() != null) {
sess.setAttribute("uname", uname);
sess.setAttribute("pwd", pwd);
}
retrived session in other jsp page using
<b> Welcome ${uname}</b>
logout hyperlink
<a href="login_ml.jsp" id="logout_link" onclick='lgt()'>Logout</a></td>
javascript to clear session
function lgt(){
var logout = document.getElementById("logout_link");
logout.session.clear();
alert("logout");
}
We cannot clear session directly from JS code . You have to call another JSP page will invalidate that session :
Javascript Function :
function destroySession() {
window.location = "killSession.jsp";
}
killSession.jsp
<%# 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>Log out</title>
</head>
<body>
<%
session.invalidate();
%>
User has been Logged out sucessfully!!!!
</body>
</html>

Categories