simple Ajax and JSP

[nobr]Hello everybody,

i can't figure out why this Ajax call to my Servlet is unable to execute the Servlet's GET method... can you understand why?

I know Ajax readysteate returns me 1 and not 4

</STYLE>

<script language="javascript" type="text/javascript">

<!--

//Browser Support Code

function ajaxFunction(programma){

var ajaxRequest;// The variable that makes Ajax possible!

try{

// Opera 8.0+, Firefox, Safari

ajaxRequest =new XMLHttpRequest();

}catch (e){

// Internet Explorer Browsers

try{

ajaxRequest =new ActiveXObject("Msxml2.XMLHTTP");

}catch (e){

try{

ajaxRequest =new ActiveXObject("Microsoft.XMLHTTP");

}catch (e){

// Something went wrong

alert("Problemi di compatibilit?con il suo browser");

returnfalse;

}

}

}

var programma = document.getElementById('programma').value;

var queryString ="?programma=" + programma;

ajaxRequest.open("GET","engine.TicketHandler" + queryString,true);

ajaxRequest.send(null);

}

function stateChange()

{

if (ajaxRequest.readyState==4 || ajaxRequest.readyState=="complete"){

document.getElementById("relase").innerHTML=ajaxRequest.responseText;

}

}

//-->

</script>

<b><font size="3"face="Verdana" color="#FFAF36">

Segnalazione assistenza Fenice II</b>

</font>

<font size="1"face="Verdana" color="#666666">

<br><br>

<b>Gentile cliente</b>,<br>

da questa pagina ?possibile accedere alla banca dati aggiornata delle segnalazioni<br>

(anomalie/migliorie) ricevute. <br>

Qualora una Sua segnalazione non risultasse presente, nonostante abbia avuta conferma<br>

dell'avvenuto inserimento, La preghiamo di contattarci al pi?presto tramite i recapiti<br>

che potr?trovare a pi?di pagina, grazie.

<br><br>

<form name="ricerca" action="Query.jsp">

<table >

<tr><td>

<b>Codice</b></td>

<td><input type="text" name="codiceID" value="Tutti"></td></tr>

<tr><td>

<b>Programma</b></td>

<td><select name="programma" id="programma" onChange="ajaxFunction(this.value)">

<option>Tutti</option>

<%dati_bean = bean.Dati_Programma_Ticket();

Iterator Idati_bean2 = dati_bean.iterator();

while (Idati_bean2.hasNext()){

SQLBean myBean = (SQLBean)Idati_bean2.next();

String programma = myBean.getParametro();

%>

<option><%=programma%></option>

<%}

%>

</select></td></tr>

<tr><td><b>Relase</b></td>

<td><select name="relase" id="relase">

<option>Tutte</option>

</select></td></tr>

<tr><td>

[/nobr]

[5089 byte] By [Pentolinoa] at [2007-11-27 3:40:19]
# 1

Sorry old code,

there 's no onStateChange() function in the right one

<script language="javascript" type="text/javascript">

<!--

//Browser Support Code

function ajaxFunction(programma){

var ajaxRequest; // The variable that makes Ajax possible!

try{

// Opera 8.0+, Firefox, Safari

ajaxRequest = new XMLHttpRequest();

} catch (e){

// Internet Explorer Browsers

try{

ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try{

ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e){

// Something went wrong

alert("Problemi di compatibilit?con il suo browser");

return false;

}

}

}

if (ajaxRequest.readyState==4 || ajaxRequest.readyState=="complete"){

document.getElementById("relase").innerHTML=ajaxRequest.responseText;

}

var programma = document.getElementById('programma').value;

var queryString = "?programma=" + programma;

ajaxRequest.open("GET", "engine.TicketHandler" + queryString, true);

ajaxRequest.send(null);

window.document.write(queryString);

}

Pentolinoa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

<script language="javascript" type="text/javascript">

<!--

//Browser Support Code

function ajaxFunction(programma){

var ajaxRequest; // The variable that makes Ajax possible!

try{

// Opera 8.0+, Firefox, Safari

ajaxRequest = new XMLHttpRequest();

} catch (e){

// Internet Explorer Browsers

try{

ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try{

ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e){

// Something went wrong

alert("Problemi di compatibilit?con il suo browser");

return false;

}

}

}

var programma = document.getElementById('programma').value;

var queryString = "?programma=" + programma;

ajaxRequest.open("GET", "engine.TicketHandler" + queryString, true);

ajaxRequest.send(null);

}

function stateChange()

{

if (ajaxRequest.readyState==4 || ajaxRequest.readyState=="complete"){

document.getElementById("relase").innerHTML=ajaxRequest.responseText;

}

}

one silly mistake check the scope of ajaxRequest variable

<script language="javascript" type="text/javascript">

<!--

//Browser Support Code

var ajaxRequest = null;

function ajaxFunction(programma){

try{

// Opera 8.0+, Firefox, Safari

ajaxRequest = new XMLHttpRequest();

} catch (e){

// Internet Explorer Browsers

try{

ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try{

ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e){

// Something went wrong

alert("Problemi di compatibilit?con il suo browser");

return false;

}

}

}

var programma = document.getElementById('programma').value;

var queryString = "?programma=" + programma;

ajaxRequest.onreadystatechange=stateChange;

ajaxRequest.open("GET", "engine.TicketHandler" + queryString, true);

ajaxRequest.send(null);

}

function stateChange()

{

if (ajaxRequest.readyState==4 || ajaxRequest.readyState=="complete"){

alert(ajaxRequest.responseText);

document.getElementById("relase").innerHTML=ajaxRequest.responseText;

}

}

please let us know whether you are getting any text in alert box...

REGARDS,

RaHuL

RahulSharnaa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

first of all, thanks for your reply..

It wasn't a scope problem: I tried to move variable out of the function but nothing changes.

Also, the alert returns me no messagese but, as I said, the problem is that ajaxRequest.readystate returns me 1.

I also know that This JSP page is unable to reach TicketHandler servlet beacuse i've putted there on the first line, a System.out line with a string that is not printed in log as it normally have to be

Pentolinoa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4
UP
Pentolinoa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5
alright in that case you are not specifying a proper URL pattern why don't you post your ticker servlet mappings mentioned under web.xmldo you have any associated mapping of /engine.TicketHandler
RahulSharnaa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 6

Well,

the TIcketHandler servlet is already declared in web.xml and works correctly, because it have another method (Post) used my web application and that method works without problems.

engines is the directory under WEB-INF where TicketHandler.class is located;

When I tried to load TicketHandler without writing engines.TicketHandler Tomcat log teold me that my JSP page was unable to restore that page, so I decided to declare the URI entirely and, in this way, TOmcat wrties nothing into log (but, as you know, nothing works :D )

Pentolinoa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 7

>the TIcketHandler servlet is already declared in web.xml and works >correctly, because it have another method (Post) used my web >application and that method works without problems.

alright why don't you post that working case & do post Servlet mappings for you tickerhandler servlet metioned under web.xml & post the code snippet behind doGet(req,res) method there.

but i still feel it has something to do with your mappings url pattern you are using.Nothing with anyother listed problems.

>engines is the directory under WEB-INF where >TicketHandler.class is located;

check whether something below is mentioned in web.xml

<servlet>

<servlet-name>TickerHandler</servlet-name>

<servlet-class>engines.TickerHandler</servlet-class>

</servlet>

<servlet-mapping>

<servlet-name>TickerHandler</servlet-name>

<url-pattern>/engine.TickerHandler</url-pattern>

</servlet-mapping>

and make sure the TickerHandler.class is listed under engines package(which means TickerHandler.java has a line package engines; at declaration block ) & the .class file would be located at /WEB-INF/classes/engines/TicketHandler.class

Hope that helps :)

REGARDS,

RaHuL

RahulSharnaa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 8

sometime I hate Tomcat...

magically, and I underline magically Tomcat started to recognize my TicketHandler servlet.. without changing nothing!!!

but thanks for your advices!!!

Last question (and you will obtain your meritated points :D)

My JSP page is unable to receive the buffer string that servlet returns:

I know string is perfect, I know DB connection works because this string is returned as it as to be but nothing appears to be into ajaxRequest.respnseText

if (ajaxRequest.readyState==4 || ajaxRequest.readyState=="complete"){

document.getElementById("relase").innerHTML=ajaxRequest.responseText;

alert(ajaxRequest.responseText);

}

no alert appears!

THIS IS HOW I TRY TO OBTAIN DATA(consider that Servlet overwrite enterley this section from <select> to </select> excluding the divs)

<div id="relase">

<tr><td><b>Relase</b></td>

<td><select name='relase' id='relase'>

<option>Tutte</option>

</div>

no voices in the dropdown menu appears!

THIS IS HOW I SEND DATA FROM SERVLET TO JSP

res.getWriter().println(buffer);

Pentolinoa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 9
and another BAD news: IE doesn't calls Servlet at all how can I obtain results also from explore?this Ajax is making me crazy
Pentolinoa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 10

wat is that you are calling on readystatechange ? as per reference to your 1st and second post i don't see you handling XmlHttpRequest.onreadystatechange anywhere ?

<script language="javascript" type="text/javascript">

<!--

//Browser Support Code

var ajaxRequest = null;

function ajaxFunction(programma){

try{

// Opera 8.0+, Firefox, Safari

ajaxRequest = new XMLHttpRequest();

} catch (e){

// Internet Explorer Browsers

try{

ajaxRequest = new ActiveXObject("Msxml2.XMLHTTP");

} catch (e) {

try{

ajaxRequest = new ActiveXObject("Microsoft.XMLHTTP");

} catch (e){

// Something went wrong

alert("Problemi di compatibilit?con il suo browser");

return false;

}

}

}

var programma = document.getElementById('programma').value;

var queryString = "?programma=" + programma;

// you need to specificy of what has to happen if the present ready state of 1 or 2 changes to 3 or 4 stateChange is a javascript function which handles the state change.

ajaxRequest.onreadystatechange = stateChange;

ajaxRequest.open("GET", "engine.TicketHandler" + queryString, true);

ajaxRequest.send(null);

}

function stateChange()

{

if ((ajaxRequest.readyState==4 || ajaxRequest.readyState=="complete") && ajaxRequest.status == 200){

alert(ajaxRequest.responseText);

document.getElementById("relase").innerHTML=ajaxRequest.responseText;

}

}

RahulSharnaa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 11

I was out for a day so I cannot post here yesterday..

about onReadyStateChange, as you can see in the last code I posted, it's handled by StateChange and when answer becomes 4 or completed and html returns 200 as answer code, it would have to load StateChange

I tought the last code I post was right but, as I said, the "relase" select loads nothing: I know the servlet's function works because using System.out.printl I can read the right string on Tomcat log

any ideas?

also for IE that doesn't seems to "understand" this piece of code at all..

thank you!

Pentolinoa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 12

IT WORKS!

you were right, I was not handling nothing with onStateChange

Now I tested it also with IE and, putting an alert intho the StateChange function, I noticed thatit receives data too!!

last problem:

I need to overwrite in some way the select structure because:

1) in Firefox, with the first selection everything works right but, if I change the value another time, it creates an embedded select into the select

2)in IE (lovely IE...) I know JSP catch the right string from Ajax state change (with an alert put in the statechange function..) but nothing appears in the dependent menu.

i think, same problem, different way they answer

I'll give you the points becasue you helped me so much! thanks to you maybe a day I'll love Ajax

Pentolinoa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 13

I forgot:

string returned from servlet:

<select name='relase' id='relase'><option>Tutte</option><option>blablabla</option>....</select>

Structure in my JSP for relase, that appear by default when you load the page

<div id='relase'><select name='relase'>

<option>Tutte</option>

</select>

</div>

Pentolinoa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 14

[nobr]> I forgot:

>

>

> string returned from servlet:

>

> <select name='relase'

> id='relase'><option>Tutte</option><option>blablabla</o

> ption>....</select>

>

> Structure in my JSP for relase, that appear by

> default when you load the page

>

> <div id='relase'><select name='relase'>

> <option>Tutte</option>

> </select>

> </div>

I'm sorry to say this but as far as i think this is one the bad ways of doing implementing dependent dropdown problem.

Why don't you make use of XmlHttpRequest.responseXml or make use of JSON object which is the best solution to solve issues of this kind.

checkout the below example...& more importantly innerHTML is more of Browser specific thing ( IE ).

index.jsp:

==========

<%@page language="java" %>

<html>

<head>

<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">

<title>Automatic Drop-Down Updation</title>

<script language="javascript">

// Global Variable for XmlHttp Request Object

var xmlhttp

// Timer Variables

var c = 0

var t

/* A function which calls a servlet named AjaxServlet to get XmlData using XmlHttpObject */

function populateCombo(txt){

xmlhttp = null

// code for initializing XmlHttpRequest Object On Browsers like Mozilla, etc.

if (window.XMLHttpRequest){

xmlhttp = new XMLHttpRequest()

}

// code for initializing XmlHttpRequest Object On Browsers like IE

else if (window.ActiveXObject) {

xmlhttp = new ActiveXObject("Microsoft.XMLHTTP")

}

if (xmlhttp != null){

// Setting the Servlet url to get XmlData

url = "AjaxServlet?req="+txt;

// Course of Action That Should be Made if their is a change in XmlHttpRequest Object ReadyState NOTE : it is 4 when it has got request from CGI

xmlhttp.onreadystatechange = getResponseAction;

// Open the Request by passing Type of Request & CGI URL

xmlhttp.open("GET",url,true);

// Sending URL Encoded Data

xmlhttp.send(null);

}

else{

// Only Broswers like IE 5.0,Mozilla & all other browser which support XML data Supports AJAX Technology

// In the Below case it looks as if the browser is not compatiable

alert("Your browser does not support XMLHTTP.")

}

}

/* Used for verifing right ReadyState & Status of XmlHttpRequest Object returns true if it is verified */

function verifyReadyState(obj){

// As Said above if XmlHttp.ReadyState == 4 then the Page Has got Response from WebServer

if(obj.readyState == 4){

// Similarly if XmlHttp.status == 200 it means that we have got a Valid response from the WebServer

if(obj.status == 200){

return true

}

else{

alert("Problem retrieving XML data")

}

}

}

/* Action that has to take place after getting reponse */

function getResponseAction(){

// Verifying State & Status

if(verifyReadyState(xmlhttp) == true){

// Building a DOM parser from Response Object

var response = xmlhttp.responseXML.documentElement

// Deleting all the Present Elements in the Drop-Down Box

drRemove()

// Checking for the Root Node Tag

var x = response.getElementsByTagName("option")

var val

var tex

var optn

for(var i = 0;i < x.length; i++){

optn = document.createElement("OPTION")

var er

// Checking for the tag which holds the value of the Drop-Down combo element

val = x[i].getElementsByTagName("val")

{

try{

// Assigning the value to a Drop-Down Set Element

optn.value = val[0].firstChild.data

} catch(er){

}

}

// Checking for the tag which holds the Text of the Drop-Down combo element

tex = x[i].getElementsByTagName("text")

{

try{

// Assigning the Text to a Drop-Down Set Element

optn.text = tex[0].firstChild.data

} catch(er){

}

}

// Adding the Set Element to the Drop-Down

document.SampleForm.dependentCombo.options.add(optn)

}

}

}

/* Function removes all the elements in the Drop-Down */

function drRemove(){

document.SampleForm.SampleCombo.length = 0;

}

</script>

</head>

<body>

<pre> <h1>Refresh Drop-Down <div id='txt'> </div> </h1></pre>

<form name="SampleForm">

<b>Parent Combo</b>

<select name="parentCombo" onchange="populateCombo(this.value)">

<option value="1">Pending</option>

<option value="2">Review </option>

<option value="3">Reviewed</option>

</select>

<br/>

<br/>

<b>Dependent Combo</b>

<select name="dependentCombo">

<option value="-1">Pick One</option>

</select>

</form>

</body>

</html>

AjaxServlet.java:

=================

import java.io.*;

import javax.servlet.*;

import javax.servlet.http.*;

/*

* AjaxServlet.java

*

*/

/**

*

* @author RaHuL

* @version

*/

public class AjaxServlet extends HttpServlet {

/** Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.

* @param request servlet request

* @param response servlet response

*/

protected void processRequest(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Sets the content type made to xml specific

response.setContentType("text/xml");

// preventing caching

response.setHeader("Cache-Control","no-store");

response.setHeader("Cache-Control","no-cache");

response.setHeader("Pragma","no-cache");

response.setDateHeader ("Expires",0);

//Initializing PrintWriter

String req = request.getParameter("req");

// Creating an instance of XmlBean Which generates XmlData From Business Logic specified

XmlBean xml = new XmlBean(req);

// Method to Generate XMLDATA

String buffer = xml.getXmlData();

PrintWriter out = response.getWriter();

// If Close of DB connections are succefull then write the content to the printstream

if(xml.close() == true)

out.write(buffer);

out.flush()

out.close();

}

protected void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {

// Calls a Method called processRequest Which Processes the request which was made by the Browser Page

processRequest(request, response);

}

}

XmlBean.java:

===========

import java.sql.*;

import java.util.*;

import java.io.*;

/*

* XmlBean.java

*

*/

/**

*

* @author RaHuL

*/

public class XmlBean {

private Connection con = null;

private PreparedStatement pstmt = null;

private ResultSet rs = null;

private String req;

// Setting CLASSURL path to TYPE I Driver

private String CLASSURL = "sun.jdbc.odbc.JdbcOdbcDriver";

/* Specifing CONNECTION PATH to a DSN named TestDsn

* Please Make Sure you create a DSN Named TestDsn to your database which holds EMP table

*/

private String CONNECTIONURL = "jdbc:odbc:TestDsn";

boolean IS_ESTABLISHED = false;

/** Creates a new instance of XmlBean and also establishes DB Connections */

public XmlBean(String req) {

try{

this.req = req;

Class.forName(CLASSURL);

con = DriverManager.getConnection(CONNECTIONURL,"admin","");

IS_ESTABLISHED = true;

} catch(SQLException sqe){

sqe.printStackTrace();

} catch(Exception exp){

exp.printStackTrace();

}

}

/* Generates XmlData For the Business Logic Specified */

public String getXmlData(){

String XmlBuffer = "";

if(IS_ESTABLISHED == true){

try{

pstmt = con.prepareStatement("SELECT empid,name FROM EMP where req=' "+req+" ' " );

rs = pstmt.executeQuery();

if(rs != null){

XmlBuffer = XmlBuffer + "<?xml version=\"1.0\" encoding=\"ISO-8859-1\" ?>";

XmlBuffer = XmlBuffer + "<!-- Edited by Rahul Sharma -->";

// Root Node

XmlBuffer = XmlBuffer + "<dropdown>";

while(rs.next()){

String value = rs.getString(1);

String text = rs.getString(2);

// Sub-root Node

XmlBuffer = XmlBuffer + "<option>";

// node which holds value of drop-down combo

XmlBuffer = XmlBuffer + "<val>"+value+"</val>";

// node which holds text for drop-down combo

XmlBuffer = XmlBuffer + "<text>"+text+"</text>";

XmlBuffer = XmlBuffer + "</option>";

}

XmlBuffer = XmlBuffer + "</dropdown>";

}

}catch(SQLException sqe){

sqe.printStackTrace();

} catch(Exception exp){

exp.printStackTrace();

}

}

return(XmlBuffer);

}

/* Closes the DB Connection Conmpletely */

public boolean close(){

if(IS_ESTABLISHED == true){

try{

pstmt.close();

con.close();

return(true);

} catch(SQLException sqe){

sqe.printStackTrace();

} catch(Exception exp){

exp.printStackTrace();

}

}

return(false);

}

}

Hope that might help :)

REGARDS,

RaHuL[/nobr]

RahulSharnaa at 2007-7-12 8:43:45 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...