How to show value from database to jsp without refreshing the page using ajax
Solution 1
You have to make below changes :-
In Servlet :-
Set the response content type as:- response.setContentType("text/xml");
in top section of the servlet. By setting this we can send the response in XML format and while retrieving it on JSP we will get it based on tag name of the XML.
Do whatever operation you want in servlet... Save the value for ex-
String uname=";
uname="hello"; //some operation
//create one XML string
String sendThis="<?xml version='1.0'?>"
+"<Maintag>"
+"<Subtag>"
+"<unameVal>"+uname+"</unameVal>"
+"</Subtag>"
+"</Maintag>"
out.print(sendThis);
Now we'll go to JSP page where we've to display data.
function getXMLObject() //XML OBJECT
{
var xmlHttp = false;
try {
xmlHttp = new ActiveXObject("Msxml2.XMLHTTP") // For Old Microsoft Browsers
}
catch (e) {
try {
xmlHttp = new ActiveXObject("Microsoft.XMLHTTP") // For Microsoft IE 6.0+
}
catch (e2) {
xmlHttp = false // No Browser accepts the XMLHTTP Object then false
}
}
if (!xmlHttp && typeof XMLHttpRequest != 'undefined') {
xmlHttp = new XMLHttpRequest(); //For Mozilla, Opera Browsers
}
return xmlHttp; // Mandatory Statement returning the ajax object created
}
var xmlhttp = new getXMLObject(); //xmlhttp holds the ajax object
function ajaxFunction() {
if(xmlhttp) {
xmlhttp.open("GET","NameList",true); //NameList will be the servlet name
xmlhttp.onreadystatechange = handleServerResponse;
xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
xmlhttp.send(null);
}
}
function handleServerResponse() {
if (xmlhttp.readyState == 4) {
if(xmlhttp.status == 200) {
getVal();
}
else {
alert("Error during AJAX call. Please try again");
}
}
}
function getVal()
{
var xmlResp=xmlhttp.responseText;
try{
if(xmlResp.search("Maintag")>0 )
{
var x=xmlhttp.responseXML.documentElement.getElementsByTagName("Subtag");
var xx=x[0].getElementsByTagName("unameVal");
var recievedUname=xx[0].firstChild.nodeValue;
document.getElementById("message").innerText=recievedUname;//here
}
}catch(err2){
alert("Error in getting data"+err2);
}
}
And here you are done. :)
Solution 2
1.In servlet code
PrintWriter output = response.getWriter();
String result = "value";
writer.write(result);
writer.close()
2. Why you don't use jquery ?
You can replace your code on -
$.post('url', function(data) {
$('#message1').html(data);
});
Solution 3
Probably off the hook but might be useful, rather than putting up all the javascript for Ajax call use some javascript library preferably jQuery for making the Ajax call.
Any javascript library you use will help you make the code compact and concise and will also help you maintain cross browser compatibility.
If you planning to write all the XHTTP code yourself, you might end up spending a lot of time for fixing cross browser issues and your code will have a lots of hacks rather than the actual business logic.
Also, using library like jQuery will also achieve the same stuff with less number of lines of code.
Hope that helps.
Prashobh
I am working as a Associate UI consultant in Bangalore(India). My Blog: www.angulartutorial.net
Updated on July 03, 2020Comments
-
Prashobh almost 4 years
I am an Ajax fresher
Ajax
function ajaxFunction() { if(xmlhttp) { var txtname = document.getElementById("txtname"); xmlhttp.open("POST","Namelist",true); xmlhttp.onreadystatechange = handleServerResponse; xmlhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xmlhttp.send("txtname=" + txtname.value); } } function handleServerResponse() { if (xmlhttp.readyState == 4) { if(xmlhttp.status == 200) { document.getElementById("message").innerHTML=xmlhttp.responseText; } else { alert("Error during AJAX call. Please try again"); } } }
jsp
<form name="fname" action="Namellist" method="post"> Select Category : <select name="txtname" id="txtname"> <option value="Hindu">Hindu</option> <option value="Muslim">Muslim</option> <option value="Christian">Christian</option> </select> <input type="button" value="Show" id="sh" onclick="ajaxFunction();"> <div id="message">here i want to display name</div><div id="message1">here i want to display meaning</div> </form>
servlet
String ct=null; ct=request.getParameter("txtname"); Connection con=null; ResultSet rs=null; Statement st=null; try{ con=Dbconnection.getConnection(); PreparedStatement ps=con.prepareStatement("select name meaning from (select * from namelist order by dbms_random.value)where rownum<=20 and category='+ct+'" ); rs=ps.executeQuery(); out.println("name" + rs); **Here I have confusion,** } catch(Exception e) { System.out.println(e); }
How can i diaplay servlet value to jsp. Please help me? or please provide some good tutorial links.