send parameter from js file to jsp file with ajax - javascript

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.

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

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 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>

Pass json var to php

Friends be patient with me. I'm not even a newbie. I'm developping a website that accesses MySQL database and I'm using this code:
File getdata.php
<?PHP
require_once("php/simfatic-RegistrationForm-dc288cf/source/include/membersite_config2.php");
$mycon = mysqli_connect("localhost", "dbuser", "ammr4024", "gadgetbid") or die("Erro! " . mysqli_error($mycon));
$myque = "SELECT * FROM leilaov WHERE numero12345 = 1";
$resul = $mycon->query($myque);
if(!$resul) {
die("Erro no query!" . $fgmembersite->UserId());
}
$myrow = mysqli_fetch_array($resul);
$variarr = array('0' => $myrow['fotodet'], '1' => $myrow['anoini'], '2' => $myrow['mesini'], '3' => $myrow['diaini'], '4' => $myrow['horaini'], '5' => $myrow['minutoini']);
echo json_encode($variarr);
?>
File getdatamain.php
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
<script>
function reqListener () {
console.log(this.responseText);
}
function teste() {
var oReq = new XMLHttpRequest();
oReq.onload = function() {
var variarr = JSON.parse(this.responseText);
alert(variarr[0]+" em "+variarr[1]+"-"+variarr[2]+"-"+variarr[3]+" às "+variarr[4]+":"+variarr[5]);
};
oReq.open("GET", "getdata.php", true);
oReq.send();
}
</script>
</head>
<body>
Botanito
<input type="submit" name="botao" id="botao" value="Largar bosta" onclick="teste()" />
</body>
</html>
This works perfect! Clicking the button retrieves the information I want from MySQL table.
My question is:- Is it possible to pass a variable to getdata.php?
As you can see in this file I have
$myque = "SELECT * FROM leilaov WHERE numero12345 = 1";
Well, I want to pass a variable and use it in this "SELECT" (instead of "1")
Here's some of my trials that didn't work.
var indice = 1;
oReq.open("POST", "getdata.php", true);
oReq.send(indice);
var indice = {
object: { child:1 }
}
oReq.open("POST", "getdata.php", true);
oReq.send(indice);
When I print the $POST the result is always the same
Array
(
)
Can anybody help me?

Categories