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

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");

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.

How to dynamically upload multi-part form data using JavaScript

I am trying to upload a file to server using JavaScript as dynamically generating a form along with input file while clicking a button.
But here, uploading File is not appending to form tag inside the script, so that upload function not works.
My code in html file as follows,
<!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</title>
</head>
<body>
<div id="formActive">
<button onclick="imageContent();">click</button>
</div>
<script>
function imageContent(){
var imgContent = "file";
var fileContent = document.createElement('input');
fileContent.name = 'file';
fileContent.type = 'hidden';
var lastImageFile = "imageName";
var boundary=Math.random().toString().substr(2);
multipart = "--" + boundary
+ "\r\nContent-Disposition: form-data; name=" + lastImageFile
+ "\r\nContent-type: application/octet-stream"
+ "\r\n\r\n" + imgContent + "\r\n";
multipart += "--"+boundary+"--\r\n";
fileContent.value = imgContent;
var form = document.createElement('form');
form.method = "POST";
form.action = "mydomain.com/upload";
form.enctype = "multipart/form-data";
form.appendChild(fileContent);
document.getElementById("formActive").appendChild(form);
form.submit();
}
</script>
</body>
</html>
While looking into the upload servlet, I didn't get any file name in request.
Can anyone assist that where I did mistake?

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>

how to return the ajax response as an array of javascript

I'm learning how to use jquery autocomplete, I make an example about the $.get method in ajax.
I take a look at http://jqueryui.com/autocomplete/ to make this example.
In my jsp page:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>AJAX calls using Jquery in Servlet</title>
<link rel="stylesheet" href="jquery-ui.css" />
<script src="jquery-1.9.1.js"></script>
<script src="jquery-ui.js"></script>
<script>
$(function(){
$('#user').autocomplete({
source: function (request, response) {
var username = $('#user').val();
$.get('autocompleteServlet', {user : username}, function(responseText){
$('#welcometext').text(responseText);
var value = [responseText];
response(value);
});
}
});
});
</script>
</head>
<body>
<form id="form1">
<h1>AJAX Demo using Jquery in JSP and Servlet</h1>
Enter your Name: <input type="text" id="user" /> <input type="button"
id="submit" value="Ajax Submit" /> <br />
<div id="welcometext"></div>
</form>
</body>
</html>
In servlet :
#Override
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String value = request.getParameter("user");
System.out.println("user : "+ value);
try {
Connection cnn = XJdbc.getConnection();
String sql = "SELECT Name FROM reported_tasks WHERE Name LIKE '%"+ value + "%'";
Statement stm = cnn.createStatement();
ResultSet rs = stm.executeQuery(sql);
String result = "";
while (rs.next()) {
result = result + rs.getString("Name") + ",";
}
cnn.close();
System.out.println("Request :" + result);
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().print(result);
} catch (Exception e) {
System.out.println("Error : " + e.getMessage());
}
}
I think that the problem is how to return ajax response as an array type of javascript.
Please help me how to fix that, thanks all
Your servlet's response currently will produce something like:
name1,name2,name3,...
The response function is looking for an array of strings in your case, though it can take an array of objects in other formats.
I would recommend having your servlet output something like this:
{ "names" : ["name1","name2","name3"...,"nameX"] }
Your Javascript to process the above response would be
$.get('autocompleteServlet', {user : username}, function(responseText){
// I assume the next line is for debugging?
$('#welcometext').text(responseText);
var obj = $.parseJSON(responseText);
response(obj.names);
});

Categories