i am doing an autocomplete. it works nicely. but i wanted the second jsp file as .java file. i tried my best. i cant change it.please help me. the main problem is request.getparameter();
JSP Ajax Autocomplete box
autocomplete.jsp:
<%#page import="java.sql.*"%>
<html>
<head>
<script type="text/javascript">
function showData(value){ ``
xmlHttp=GetXmlHttpObject()
var url="auto.jsp";
url=url+"?name="+value;
xmlHttp.onreadystatechange=stateChanged
xmlHttp.open("GET",url,true)
xmlHttp.send(null)
}
function stateChanged() {
if(xmlHttp.readyState==4 || xmlHttp.readyState=="complete"){
var showdata = xmlHttp.responseText;
document.getElementById("mydiv").innerHTML= showdata;
}
}
function GetXmlHttpObject(){
var xmlHttp=null;
try {
xmlHttp=new XMLHttpRequest();
}
catch (e) {
try {
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
}
return xmlHttp;
}
</script>
</head>
<body>
<form name="employee">
<input type="text" name="name" id="name" onkeyup="showData(this.value);"><br>
<div id="mydiv"></div>
</table>
</body>
</html>
auto.jsp (second jsp file)
<%# page import="java.sql.*" %>
<%
String name = request.getParameter("name").toString();
String buffer="<div>";
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "root");
Statement st=con.createStatement();
ResultSet rs=st.executeQuery("select * from data where name like '"+name+"%'");
while(rs.next())
{
buffer=buffer+rs.getString("name")+"<br>";
}
buffer=buffer+"</div>";
response.getWriter().println(buffer);
}
catch (Exception e) {
System.out.println(e);
}
%>
I think you want a java file for search response while typing.
You can do this by creating a Servelet file.
Create a servelt for /auto?name=value and map using web.xml.
Related
I am currently trying to use a Ajax in netbeans using JavaScript and PHP file. The following code I should click the button and the contents of the php fill should appear but it doesn't. When I use firebug in firefox the response shows the full php file has returned but will not display on webpage. Why???
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<script>
function getXMLHttp() {
var xmlHttp
try {
//Firefox, Opera 8.0+, Safari
xmlHttp = new XMLHttpRequest();
}
catch (e) {
//Internet Explorer
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e) {
alert("Your browser does not support AJAX!")
return false;
}
}
}
return xmlHttp;
}
function MakeRequest() {
var xmlHttp = getXMLHttp();
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == 4) {
HandleResponse(xmlHttp.responseText);
}
}
xmlHttp.open("GET", "ajax.php", true);
xmlHttp.send(null);
}
function HandleResponse(response) {
document.getElementById('ResponseDiv').innerHTML = response;
}
</script>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<input type='button' onclick='MakeRequest();' value='Use AJAX!!!!'/>
<div id='ResponseDiv'>
This is a div to hold the response.
</div>
</body>
</html>
My PHP file is
<?php
echo "This is a php response to your request!!!!!!";
?>
Apart from the fact that HTML code is barely decent, why not use jQuery?
<button id="get" onClick="return false;">jQuery get</button>
<div id="result"></div>
<script type="text/javascript">
$("#get").click(function() {
$.get( "ajax.php", function( data ) {
$( "#result" ).html( data );
});
});
</script>
PHP is server side and is not made to be run on the client side. Your response should come from a URL and not the contents of a file. Ensuring that your response contains on HTML and not PHP should lead you to your solution.
Try replacing your PHP file with
<p>This is a php response to your request!!!!!!</p>
If this enables you to show your content, you have your problem and solution.
I need to send a mail with jsp, but the page itself mustn't reload. The whole implementation is working fine when reloading on the POST-event, but adjusting the code to work with ajax breaks it. It seems that the jsp-Code within the index.jsp is not executed, when the ajax event is triggerd.
I am gonna show some snippets:
index.jsp
<%
String result = "=(";
String to = request.getParameter("rec_mail");
if(to != null) {
String from = request.getParameter("sendermail");
String host = "mailserver";
Properties properties = System.getProperties();
properties.setProperty("mail.smtp.host", host);
Session mailSession = Session.getDefaultInstance(properties);
try{
MimeMessage message = new MimeMessage(mailSession);
message.setFrom(new InternetAddress(from));
message.addRecipient(Message.RecipientType.TO,
new InternetAddress(to));
message.setSubject("Feedback");
message.setText(request.getParameter("feedbackinput"));
Transport.send(message);
result = "Sucess!";
}catch (MessagingException e) {
e.printStackTrace();
result = "failed!";
}
}
out.println(request.getParameter("sendermail"));
out.println(result);
%>
<input id="bsend" class="fbutton" type="submit" name="send" value="Send" onclick="loadContent()" style="float:right; width:18%; height:35%;" >
ajax.js
var xmlhttp
function loadContent() {
xmlhttp=GetXmlHttpObject();
if (xmlhttp==null)
{
alert ("Your browser does not support Ajax!");
return;
}
var url="./index.jsp";
xmlhttp.open("post",url,true);
xmlhttp.send(null);
xmlhttp.onreadystatechange=getOutput;
}
function getOutput()
{
if (xmlhttp.readyState==4)
{
alert("Message sent!");
}
}
function GetXmlHttpObject()
{
if (window.XMLHttpRequest)
{
return new XMLHttpRequest();
}
if (window.ActiveXObject)
{
return new ActiveXObject("Microsoft.XMLHTTP");
}
return null;
}
(just showing the relevant parts, everywhere)
I get the alert-message, but no mail is sent ... I hope it is clear, what I am trying to do..
Thank you!
Best regards
Don't you also need to set a header for a HTTP Post
xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
also, not sure if it will make a difference but I would make "post" to "POST".
Currently I am working on static HTML website. Now I am using following javascript code to read server side text file:
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) {// code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else {// code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "results.txt", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv"><h2>content</h2></div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Here on click event data is just displayed.But now I want to change the content of text file on click event.I want to increment the number by 1 which resides in the file as content.
Please help me to do this...Thank you so much in advance.!!
EDIT:
I am using windows hosting.
You may do it like this
This is the index page. I have done it in JSP.
index.jsp
<!DOCTYPE html>
<html>
<head>
<script>
function loadXMLDoc() {
var xmlhttp;
if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
xmlhttp = new XMLHttpRequest();
}
else { // code for IE6, IE5
xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
}
xmlhttp.onreadystatechange = function () {
if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
document.getElementById("myDiv").innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", "newjsp.jsp", true);
xmlhttp.send();
}
</script>
</head>
<body>
<div id="myDiv">
<h2>content</h2>
</div>
<button type="button" onclick="loadXMLDoc()">Change Content</button>
</body>
</html>
Then the server side coding
newjsp.jsp
<%#page contentType="text/html" pageEncoding="UTF-8" import="java.io.*"%>
<%
try {
BufferedReader in = new BufferedReader(new FileReader("C:/Users/sar/Documents/NetBeansProjects/WebApplication1/web/results.txt"));
// change the path to the txt file
String line;
int a = 0;
if((line = in.readLine()) != null)
a = Integer.parseInt(line)+1;
else
a = 1;
PrintWriter pw = new PrintWriter(new FileOutputStream("C:/Users/sar/Documents/NetBeansProjects/WebApplication1/web/results.txt"));
// change the path to the txt file
pw.println(a);
pw.close();
out.println(a);
}
catch(Exception e)
{
e.printStackTrace();
}
%>
You will have to create a results.txt file at the location specified.
I have create a javascript in an html (using xmlHttp.responseText) page where I am requesting a value from an aspx page that queries for a usernumber of a username in the database (MSSQL). when i load the html (IE8), i got this "Unknown Runtime Error Line: 30". What supposed to be causing the problem? need help. Here is my code:
Here is the HTML page and the Javascript:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function showUsernum(str)
{
var xmlHttp;
if (str=="")
{
document.getElementById("textExists").innerHTML="";
return;
}
if (window.xmlHttpRequest)
{// code for IE7+, Firefox, Chrome, Opera, Safari
xmlHttp=new xmlHttpRequest();
}
else
{// code for IE6, IE5
xmlHttp=new ActiveXObject("Microsoft.xmlHttp");
}
xmlHttp.onreadystatechange=function()
{
if (xmlHttp.readyState==4 && xmlHttp.status==200)
{
//alert(str);
document.getElementById("textExists").innerHTML=xmlHttp.responseText;
}
}
xmlHttp.open("GET","http://localhost/Base_Data/default.aspx?q="+str,true);
xmlHttp.send();
}
</script>
</head>
<body>
<form action="" method="post">
<label>UserName
<input type="text" name="textUser" id="textUser" onchange="showUsernum(this.value)">
</label>
</form>
<br/>
<div >
<form name="form1" method="post" action="">
<label>
<div id="textExists">Exists?</div>
</label>
</form>
</div>
</body>
Here is my ASP code.
protected void Page_Load(object sender, EventArgs e)
{
Response.Expires = -1;
SqlConnection conn;
string connection = ConfigurationManager.ConnectionStrings ["BaseData"].ConnectionString;
conn = new SqlConnection(connection);
string sql = "SELECT USERNUM FROM useraccount WHERE USERNAME ='" + Request.QueryString["q"] + "'";
SqlCommand cmd = new SqlCommand(sql, conn);
conn.Open();
string contNm = Convert.ToString(cmd.ExecuteScalar());
Response.Write("textExists=" + contNm );
conn.Close();
}
Really appreaciate any response. Thank you.
The problem is that you're trying to assign whole page, including <html> tag and everything, into a single DOM element and IE doesn't really like that.
To have the server send only raw HTML without whole document you need to clear the Response. In addition you are not disposing properly of the database objects and you are exposed to SQL Injection attacks, so optimized code would be:
string connection = ConfigurationManager.ConnectionStrings ["BaseData"].ConnectionString;
using (SqlConnection conn = new SqlConnection(connection))
{
conn.Open();
string sql = "SELECT USERNUM FROM useraccount WHERE USERNAME=#user";
string contNm = "";
using (SqlCommand cmd = new SqlCommand(sql, conn))
{
cmd.Parameters.AddWithValue("#user", Request.QueryString["q"]);
contNm = Convert.ToString(cmd.ExecuteScalar());
}
Response.Clear();
Response.Write("textExists=" + contNm);
Response.End();
conn.Close();
}
Below is my html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1252">
<title>New Page 1</title>
<script type="text/javascript">
function Data_Check()
{
var xmlHttp;
try
{
xmlHttp=new XMLHttpRequest(); }
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Msxml2.XMLHTTP");
}
catch (e)
{
try
{
xmlHttp=new ActiveXObject("Microsoft.XMLHTTP");
}
catch (e)
{
alert("Your browser does not support AJAX!");
return false;
}
}
}
xmlHttp.onreadystatechange=function()
{
if(xmlHttp.readyState==4)
{
alert(xmlHttp.responseText);
}
}
var RES = document.getElementById("Remarks").innerHTML;
var params ="RES="+RES;
xmlHttp.open("POST","Data_Check.asp",true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
}
</script>
</head>
<body>
<textarea id="Remarks" rows="5" name="Remarks" cols="79" style="font-family: Arial; font-size: 11px">please, accept my submit form.</textarea>
<br>
<img id="Submit" onclick ="return Data_Check();" border="0" src="submit.png" width="145" height="28">
</body>
<img
</html>
Here i facing the problem is,
When i submit "Remarks" textarea innerhtml to my "Data_Check.asp"
<%
RES = Request.Form("RES")
%>
and this remarks save in my sql database.( database field is "Remarks_text" and datatype is "text")
In the data base textarea data is read ("please, accept my submit form.") textarea data with out space.
like this
please,acceptmysubmitform.
I need to save
please, accept my submit form.
hoping your support
Try url encoding:
var RES = encodeURIComponent(document.getElementById("Remarks").value);
Change
document.getElementById("Remarks").innerHTML;
to
document.getElementById("Remarks").value;
I suspect spaces are not supported in URLs or HTTP headers, hence old URLs had %20 instead of a space. Modern browsers and servers now do this behind the scenes.
I found replacing spaces with %20 using formValues = formValues.replace(/ /gi,"%20"); prior to sending solved the problem.
Yes this is fixed!
Example :
var dataString = "textcontent="+test.replace(/ /gi,"%20");