This week's book giveaway is in the Servlets forum.
We're giving away four copies of Murach's Java Servlets and JSP and have Joel Murach on-line!
See this thread for details.
The moose likes HTML, CSS and JavaScript and the fly likes Displaying a Greeting message using Ajax Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Murach's Java Servlets and JSP this week in the Servlets forum!
JavaRanch » Java Forums » Engineering » HTML, CSS and JavaScript
Bookmark "Displaying a Greeting message using Ajax" Watch "Displaying a Greeting message using Ajax" New topic
Author

Displaying a Greeting message using Ajax

Jahnavi Kondapaneni
Ranch Hand

Joined: Jan 25, 2008
Posts: 56
Hi all,
I am implementing Ajax on a simple jsp page.Code snippet of the jsp is as shown below:
<form name="myForm">
Enter name: <input type="text" name="username" onblur="ajaxFunction()"/>
<span id="message"></span>
Enter location:<input type="text" name="location" onblur="ajaxFunction1()"/>
<span id="locationdetails"></span>
</form>
I have also included the JS functions for creating theXMLHTTRequest object. The code snippets of "ajaxFunction()" and "ajaxFunction1()" are as follows:
function ajaxFunction()
{
var params = "username="+document.myForm.username.value;
alert("username:"+params);
xmlHttp.open("POST","AjaxServlet",true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
xmlHttp.onreadystate = function()
{
if(xmlHttp.readyState == 4)
{

alert("Into ready state");

if(xmlHttp.status == 200)
{
alert("xmlHttp.responseText");
document.getElementById("message").innerHTML = xmlHttp.responseText;
}
}
}
}


ajaxFunction1()
function ajaxFunction1()
{
var params = "location="+document.myForm.location.value;
alert("location:"+params);
xmlHttp.open("POST","AjaxServlet",true);
xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xmlHttp.setRequestHeader("Content-length", params.length);
xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
xmlHttp.onreadystate = function()
{
alert("Into ready state");
if(xmlHttp.readyState == 4)
{
if(xmlHttp.status == 200)
{
alert("xmlHttp.responseText");
document.getElementById("locationdetails").innerHTML = xmlHttp.responseText;
}
}
}
}

In the servlet's doPost method I have included a method which returns the greeting message and location details.Code snippet is as follows:
public void doPost(HttpServletRequest request,
HttpServletResponse response) throws IOException {

String username = null;
String location = null;
response.setContentType("text/html");
username = request.getParameter("username");
location = request.getParameter("location");
System.out.println("USERNAME:"+username);
System.out.println("LOCATION:"+location);
displaymessage(response,username);
displaylocationdetails(response,location);

}

private void displaymessage(HttpServletResponse response ,
String username)throws IOException
{
String message = null;
PrintWriter out = response.getWriter();
if(username!=null)
{
System.out.println("Into display message if");
message = "Welcome..."+username;

}
else
{
System.out.println("Into display message else");
message = "Please enter the username";
}

out.println(message);
out.close();
}

private void displaylocationdetails(HttpServletResponse response,
String location)throws IOException{

PrintWriter out = response.getWriter();
String locationdetails = null;
if(location!=null)
{
System.out.println("Into location display message if");
if(location.equalsIgnoreCase("TCO"))
{
locationdetails = "Techno Campus";
}
else if(location.equalsIgnoreCase("GMR"))
{
locationdetails = "GMR office";
}
else if(location.equalsIgnoreCase("SRI"))
{
locationdetails ="Siruseri";
}
else
{
locationdetails = "New location";
}
}
else
{
System.out.println("Into location display message else");
locationdetails = "Please enter the location details";
}

out.println(locationdetails);
out.close();
}

If you go through the code you will get to know that when the name is entered a wecome message shud be displayed or "Please enter username" message when its left blank.
But when I run this application it does not display any message if we leave the field blank or enter any data same thing holds good for locationdetails also.
Looking forward for your reply.

Regards
Janu

Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

Your Ajax code is not right..


Just looked at this Simple introduction with example, This will help to make your code simple.


[LEARNING bLOG] | [Freelance Web Designer] | [and "Rohan" is part of my surname]
Jahnavi Kondapaneni
Ranch Hand

Joined: Jan 25, 2008
Posts: 56
Hi Sagar,

I have created an XMLHttpRequest object using the code below but I forgot to mention it in my post.
var xmlHttp;
function createRequest()
{
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;
}
}
}
alert("Out of create request:");
}
window.onload = createRequest();
Hope its clear....
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

Ok, Good, If you are getting valid XMLHttp object, no Problem and please use Code Tags to quote your source.

And have you noticed the comment I put at your ajax code. Just separate out the call back handler function named "fucntion()"..



Try this changes..
Jahnavi Kondapaneni
Ranch Hand

Joined: Jan 25, 2008
Posts: 56
Hi Sagar,

I have done the changes as you mentioned.But still it dosent work....
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

Jahnavi Kondapaneni wrote:But still it dosent work....


It indicate noting.

Lets make it simple by using AJAX action for single "name" input field , so remove all other AJAX script.

then I expect the following flow in your JS source, something like this..



try this.

Jahnavi Kondapaneni
Ranch Hand

Joined: Jan 25, 2008
Posts: 56
Yes your are right Sagar.
I am considering only username field now.
I did the necessary changes but still it is not working
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

Jahnavi Kondapaneni wrote: ....but still it is not working


Again same answer, Would you please see this link which I posted in my previous reply,

http://faq.javaranch.com/java/ItDoesntWorkIsUseless

and please elaborate "What exactly happening?"
Jahnavi Kondapaneni
Ranch Hand

Joined: Jan 25, 2008
Posts: 56
Sagar,

I traced the flow of the data by giving some alerts and Sysouts.
What I could find was in the doPost method I have performed a null check for username
i.e
if(username!=null )
{......
}
when the username is null it shud not get into the if loop but it is going into the if loop.
So this means the null check fails.
And even if I enter any username the greeting message does not get displayed.
I hope now it might get an idea....
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

Now it means you can call servlet.

Now makes some changes in AJAX call,



After making this modification, Re run it. and post what you get here, Also while posting, copy paste you latest code you working on .. (Surrounded by code tags)

Jahnavi Kondapaneni
Ranch Hand

Joined: Jan 25, 2008
Posts: 56
Hi Sagar,
I have commented the code as you mentioned.
I added a few alert statements within the call back functon i.e.
xmlHttp.onreadystate = functionGreet;
I realised that it was not going into the function "functionGreet()".So I made a small change i.e,
I added a pair of paranthesis for the function as shown below.
xmlHttp.onreadystate = functionGreet();
After I made this change the callback function was called.
Now it displays only one greeting message in all cases ie"Please enter the username" even if the username has been entered.


Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1

Jahnavi Kondapaneni wrote:

I realised that it was not going into the function "functionGreet()".So I made a small change i.e,
I added a pair of paranthesis for the function as shown below.
xmlHttp.onreadystate = functionGreet();
After I made this change the callback function was called.

Sorry, I haven't looked your code properly ! (May be because of not using CODE tags)
Actually, there is no XMLHttpRequest properties called "onreadystate", but have "onreadystatechange" properties, which sets the method to be called on every state change. This is usually your event handler for the asynchronous callback. So make this correction.


Jahnavi Kondapaneni wrote:
Now it displays only one greeting message in all cases ie"Please enter the username" even if the username has been entered.

The way you passed "params" are correct, but still I suggest some AJAX code modification as



And also post the updated code , you working on.
Jahnavi Kondapaneni
Ranch Hand

Joined: Jan 25, 2008
Posts: 56
Hi Sagar,

I am sending you the code.
I have made the changes as told by you.
Still I get the same message "Please enter the username" in all cases.


function ajaxFunction()
{
var params = "username="+document.myForm.username.value;
alert("username:"+params);
xmlHttp.open("POST","AjaxServlet",true);
//xmlHttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
//xmlHttp.setRequestHeader("Content-length", params.length);
//xmlHttp.setRequestHeader("Connection", "close");
xmlHttp.send(params);
xmlHttp.onreadystatechange = functionGreet();

}

function functionGreet()
{
alert("Into greet function");
if(xmlHttp.readyState == 4)
{

alert("Into ready state");

if(xmlHttp.status == 200)
{
//alert("xmlHttp.responseText");
document.getElementById("greetingMessage").innerHTML = xmlHttp.responseText;
}
}
}
Jahnavi Kondapaneni
Ranch Hand

Joined: Jan 25, 2008
Posts: 56
Hi Sagar,

Its finally working.
I have kept the JS code the same.
I have made change in the servlet.
if(uname.length()!=0)
{
System.out.println(uname.length());
System.out.println("Into uname!=null");
msg = "Welcome..."+uname;
}
else
{
System.out.println("Into else");
msg = "Please enter username";
}
Instead of checking if(uname!=null) I have replaced it by if(uname.length()!=0).
Sagar Rohankar
Ranch Hand

Joined: Feb 19, 2008
Posts: 2902
    
    1


Good
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Displaying a Greeting message using Ajax
 
Similar Threads
Simple AJAX query what I'm missing?
Problem getting servlets working
Notify Users before session expires
Java Dynamic Servlet
responseXml is null