how to make jquery autocomplete ui using ajax in jsp - javascript

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

Related

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

Javascript pop up message in JSP

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) {
}
%>

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>

Typeahead.js Basic With MySQL DB

I am following a tutorial online (http://mycodde.blogspot.co.uk/2013/12/typeaheadjs-autocomplete-tutorial-ajax.html#comment-form) which invloves typeahead.js and a simple MySQL DB and I cannot get it to work.
Using typeahead.js v10.2 jQuery v1.9.1 and Bootstrap v3.2.0
I have included the necessary css and js files, I have also created a connection.php file, which successfully connects to my localhost db.
The problem is that the auto-suggest box doesn't auto-suggest anything. I am possibly doing something silly as I am new to js and programming.
I have included my files below if anybody would be kind enough to point me in the right direction I would appreciate it.
index.php
<!DOCTYPE>
<html lang="en">
<head>
<link rel="stylesheet" href="//netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<title>Typeahead.js Tutorial with Mysql Database</title>
<meta http-equiv="content-type" content="text/html;charset=utf-8" />
<meta name="generator" content="Geany 1.23.1" />
</head>
<body>
<input type="text" name="search" id="search"></div>
</body>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.1/jquery.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.2.0/js/bootstrap.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.2/bloodhound.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.2/typeahead.bundle.min.js"></script>
<script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/typeahead.js/0.10.2/typeahead.jquery.js"></script>
<script>
$("document").ready(function(){
$("#search").typeahead({
name : 'sear',
remote: {
url : '/connection.php?query=%QUERY'
}
});
});
</script>
</html>
connection.php
<?php
$con=mysqli_connect("localhost","myuser","mypassword","mydb");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT first_name,last_name FROM actor");
while($row = $result->fetch_object()){
$user_arr[] = $row->first_name;
$user_arr2[] = $row->last_name;
}
mysqli_close($con);
?>
When I check the firebug console I get an Uncaught TypeError: undefined is not a function appears at line 22 which is;
$("#search").typeahead({
Can anybody lend some assistance?
Thanks
You need to add the following code in your .js file:
var search = new Bloodhound({
datumTokenizer: Bloodhound.tokenizers.obj.whitespace('sear'),
queryTokenizer: Bloodhound.tokenizers.whitespace,
limit: 10,
remote: {
url: '/connection.php?query=%QUERY',
filter: function(list) {
return $.map(list, function(search) {
return {
name: sear
};
});
}
}
});
The json file contains an array of strings, but the Bloodhound
suggestion engine expects JavaScript objects so this converts all of those strings.
Check you jquery DOM Ready bind handler syntax here:
$("document").ready(...
It must be
$( document ).ready(...
Read more:
http://learn.jquery.com/using-jquery-core/document-ready/

Categories