JSP response into a Javascript code

Suppose I have a form that I submit, and its action is set to a JSP page that returns a series of elements <option>, for example:

<option>2005</option>

<option>2006</option>

Is it possible to GET that JSP response, inside the JavaScript code?

Or should I better state, inside the JSP code, to return ONLY the numbers and then I get it on the JavaScript and use the .add() funtion to add the item to a <select> ?

How do I save that response inside the JavaScript?

For example, I am trying with this Javascript function that handles the changes on a drop-down list:

function clickedOnPType(lista)

{

document.form1.action ="searchAvailableYears.jsp?pType=" + txtPType;}

document.form1.submit();

}

...And I am getting, in return, a series of <option> with the correct data...

Thanking you in advance,

MMS

[1057 byte] By [tofuwithcoffeea] at [2007-11-27 7:55:24]
# 1
Simple, use AJAX. You can get the response text in javascript as a jap/xml format. 1) initiate xmlHttp object2) create action class and send the request thro' ajax3) create callback fn, which gets you the result of the actionif you need code, wait until
skp71a at 2007-7-12 19:36:46 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

well AJAX is not the only solution to achieve this....

their are many more practices which people follow to acheive this.

check out the below solutions.

1).Maintain the state of the Form In a Bean and refersh the page and then reload the page.

2).Use a Hidden iframe which loads a JSP after calling the Controller and then onload of the page write a javascrit which updates parent frame's dependent dropdown.

3).Use AJAX and call the controller get response in text(csv)/XML/JSON and parse then response update the nessary view fields accordingly.

checkout the below link where i've demostrated an example of how 3rd case works.

http://forum.java.sun.com/thread.jspa?threadID=5130482&tstart=0

Hope that might help :)

REGARDS,

RaHUl

RahulSharnaa at 2007-7-12 19:36:46 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3

Oh hello... in one of my 1000 searches I found that post days ago and I was already trying with your code, but I was getting several errors like "undefined is null or not an object" (in IE), "xmlhttp.responseXML has no properties" (in Firefox)....

And there is something wrong I am doing, but what?. I got tired of it and I began to search for other alternatives different from AJAX, but if I achieve it with AJAX, it will be good also to my co-workers here in this Summer internship because they will learn this "new" thing.

Ok, the code I modified from your example, RahulSharna, is below. I am not convinced that my modified version of handleHttpResponse() is correct. Perhaps there is a tiny error that makes the whole code unusable.

function handleOnChange(ddl)

{

var ddlIndex = ddl.selectedIndex;

var ddlText = ddl[ddlIndex].text;

var frmSelect = document.forms["form1"];

var frmSelectElem = frmSelect.elements;

if(ddl.name="pType")

{

txtYear = "";

txtDay = "";

txtTime = "";

unblock(document.form1.year);

block(document.form1.day);

block(document.form1.time1);

laProxLista = frmSelectElem["year"];

if (ddl.options[ddl.selectedIndex].text != "")

{

txtPType = ddl.options[ddl.selectedIndex].text;

}

}

else if(ddl.name="year")

{

txtDay="";

txtTime="";

unblock(document.form1.day);

block(document.form1.time1);

laProxLista = frmSelectElem["day"];

if (ddl.options[lista.selectedIndex].text != "")

{

txtYear = ddl.options[lista.selectedIndex].text;

}

}

else if(ddl.name="day")

{txtTime = "";

unblock(document.form1.time1);

laProxLista = frmSelectElem["time1"];

if (ddl.options[ddl.selectedIndex].text != "")

{

txtDay = ddl.options[ddl.selectedIndex].text;

}

}

else //time1

{

laProxLista = null;

if (ddl.options[ddl.selectedIndex].text != "")

{

txtTime1 = ddl.options[ddl.selectedIndex].text;

}

}

if ( txtPType != "")

{

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)

{

if(ddl.name = "pType")

{

// Setting the JSP/Servlet url to get XmlData

url = "searchAvailableYears.jsp?pType=" + txtPType;

}

else if(ddl.name = "year")

{

url = "searchAvailableDOY.jsp?pType=" + txtPType + "&year=" + txtYear;

}

else(ddl.name = "day")

{

url = "searchAvailableTimes.jsp?pType=" + txtPType + "&year=" + txtYear + "&day=" + txtDay;

}

xmlhttp.onreadystatechange = handleHttpResponse;

// 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.")

} //else

} //if chosen

} //function

//-

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{

return false;

//alert("Problem retrieving XML data")

}

}

}

//-

function handleHttpResponse()

{

if(verifyReadyState(xmlhttp) == true)

{

//--HERE!! - I GET "UNDEFINED" IN THE DIALOG BOX

//- BELOW THE CODE LINE.... ////--

var response = xmlhttp.responseXML.responseText;

alert(response);

//First we remove the actual items from the list

removeItems(laProxLista);

// Checking for the Root Node Tag

var _x = response.getElementsByTagName("option");

var txt;

var newOption;

// HERE!! -- THERE MUST BE A PROBLEM ALSO....-

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

{

newOption = document.createElement("OPTION");

txt = _x[i].text;

//newOption.text = txt[0].firstChild.data;

newOption.text = txt

laProxList.add(newOption);

}

} //if

else

{

alert(_x);

}

}//function

//

/* 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")

}

}

}

--

OMG... if I get to solve this I will definetely post the solution and all the code... I am sure there are other people out there with the same situation......

If any other person can help, it will be of great benefit to other people also.

-

Another thing...

I have tried to set the content type inside the JSP to

response.setContentType("text/html");

AND to

response.setContentType("text/xml");

but none of the above is getting me results......

Appreciating any help,

MMS

tofuwithcoffeea at 2007-7-12 19:36:46 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4

> Oh hello... in one of my 1000 searches I found that

> post days ago and I was already trying with your

> code, but I was getting several errors like

> "undefined is null or not an object" (in IE),

> "xmlhttp.responseXML has no properties" (in

> Firefox)....

Well one thing i wanted to discuss here is is wat properties does in general a XmlHttpRequest Object contains

checkout the below interface which gives a clear understanding of the Object member properties.

interface XMLHttpRequest {

attribute EventListeneronreadystatechange;

readonly attribute unsigned short readyState;

void open(in DOMString method, in DOMString url);

void open(in DOMString method, in DOMString url, in boolean async);

void open(in DOMString method, in DOMString url, in boolean async, in DOMString user);

void open(in DOMString method, in DOMString url, in boolean async, in DOMString user, in DOMString password);

void setRequestHeader(in DOMString header, in DOMString value);

void send();

void send(in DOMString data);

void send(in Document data);

void abort();

DOMString getAllResponseHeaders();

DOMString getResponseHeader(in DOMString header);

readonly attribute DOMString responseText;

readonly attribute DocumentresponseXML;

readonly attribute unsigned short status;

readonly attribute DOMString statusText;

};

therefore as you can see XmlHttpRequest.reponseXML returns a Document Object which has below set of properties.

http://www.w3schools.com/dom/dom_document.asp

http://www.javascriptkit.com/domref/documentproperties.shtml

and as said earlier one can send AJAX response in three ways

1).Plain text(with comma seperated values maybe): Which we can collect using XmlHttpRequest.responseText

2).XML: @ client side XmlHttpRequest.reponseXML create a DOM Object using which one can parse it get values

of attributes and values of different tags and then update the view accordingly.

3).JSON(Javascript Object Notation): It is a bit complicated thing to discuss at this moment

however it uses the first property(Plain text) and then

uses set of libraries to parse and update the view.

checkout below links to understand it

http://www.ibm.com/developerworks/library/j-ajax2/

http://oss.metaparadigm.com/jsonrpc/

> function handleOnChange(ddl)

>

> {

>

>var ddlIndex = ddl.selectedIndex;

> var ddlText = ddl[ddlIndex].text;

>var frmSelect = document.forms["form1"];

> var frmSelectElem = frmSelect.elements;

>

> if(ddl.name="pType")

>{

>txtYear = "";

> txtDay = "";

>txtTime = "";

>

> unblock(document.form1.year);

> block(document.form1.day);

> block(document.form1.time1);

>

>laProxLista = frmSelectElem["year"];

>

> if (ddl.options[ddl.selectedIndex].text !=

> "")

> {

>txtPType = ddl.options[ddl.selectedIndex].text;

> }

>

> else if(ddl.name="year")

> {

>txtDay="";

> txtTime="";

>

>unblock(document.form1.day);

> block(document.form1.time1);

>

>laProxLista = frmSelectElem["day"];

> f (ddl.options[lista.selectedIndex].text != "")

>{

> txtYear = ddl.options[lista.selectedIndex].text;

>}

>

>

>

>else if(ddl.name="day")

> {txtTime = "";

>unblock(document.form1.time1);

>

>laProxLista = frmSelectElem["time1"];

> (ddl.options[ddl.selectedIndex].text != "")

>{

> txtDay = ddl.options[ddl.selectedIndex].text;

>}

>

>

> else //time1

> {

>laProxLista = null;

> if (ddl.options[ddl.selectedIndex].text != "")

>{

> txtTime1 = ddl.options[ddl.selectedIndex].text;

>}

>

>

>if ( txtPType != "")

> {

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

>{

>

>if(ddl.name = "pType")

> {

> // Setting the JSP/Servlet url to get

> XmlData

> url = "searchAvailableYears.jsp?pType="

> + txtPType;

>}

>else if(ddl.name = "year")

>{

> url = "searchAvailableDOY.jsp?pType=" + txtPType

> PType + "&year=" + txtYear;

>}

>else(ddl.name = "day")

>{

> url = "searchAvailableTimes.jsp?pType=" +

> e=" + txtPType + "&year=" + txtYear + "&day=" +

> txtDay;

>}

>

> xmlhttp.onreadystatechange =

> handleHttpResponse;

>

> // 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.")

>} //else

>} //if chosen

>

> //function

>

> //-

Well as far as i can see i do not have any issues with it because your code looks

preety much involved with your business logic but one thing i would like to reconfim

here is the variable "xmlhttp" a global one.

if no declare xmlhttp variable as a global variable.

<script language="javascript">

var xmlhttp;

function handleOnChange(ddl){

}

function verifyReadyState(obj){

}

function handleHttpResponse() {

}

</script>

> function verifyReadyState(obj)

> if(obj.readyState == 4){

>

> if(obj.status == 200){

>

>if(obj.responseXML != null)

> return true;

>else

> return false;

> }

> else{

>return false;

>}

>} else return false;

> }

I believe,this is preety much it.

> function handleHttpResponse() [/b]

> {

>[code]if(verifyReadyState(xmlhttp) == true)

> {

>

> //--HERE!! - I GET "UNDEFINED" IN THE

> DIALOG BOX

> //- BELOW THE CODE LINE....

>////--

> var response = xmlhttp.responseXML.responseText;

>alert(response);

it is obvious that you would get Undefined here as responseText is not a property of Document Object or to be more specific to the Object what xmlhttp.responseXML returns.

you might have to use that as

alert(xmlhttp.responseText);

and coming back to parsing the XML reponse you have got from the server we need to use

var response = xmlhttp.responseXML.documentElement;

property for it...

and if you put as a alert message it has to give you an Output like"Object"

alert(response);

if that doesn't the browser version which you are using may not support XML properly.

var response = xmlhttp.responseXML.documentElement;

removeItems(laProxLista);

var x = response.getElementsByTagName("option")

var val

var tex

var newOption

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

newOption = document.createElement("OPTION")

var er

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

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

{

try{

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

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

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

} catch(er){

}

}

// Adding the Set Element to the Drop-Down

laProxList.add(newOption);

}

here i'm assuming that i'm sending a xml reponse of format something below.

<?xml version="1.0" encoding="ISO-8859-1" ?>

<drop-down>

<option>

<value>1</value>

<text>label1</text>

</option>

<option>

<value>2</value>

<text>label2</text>

</option>

<option>

<value>3</value>

<text>label3</text>

</option>

--

--

--

</drop-down>

and i'm trying to update both option's value and label which would be something like

<select >

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

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

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

<option value="4">label4</option>

</select>

else where if you are interested in getting a format like the one below

<select >

<option>label1</option>

<option>label2</option>

<option>label3</option>

<option>label4</option>

</select>

try the below snippet

var response = xmlhttp.responseXML.getElementsByTagName("text");

var length = response.length;

var newOption

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

newOption = this.document.createElement("OPTION");

newOption.text = response[i].childNodes[0].nodeValue;

// or newOption.text = response[i].firstChild.data

laProxList.add(newOption);

}

> Another thing...

>

> I have tried to set the content type inside the JSP

> to

> response.setContentType("text/html");

> AND to

> response.setContentType("text/xml");

>

> but none of the above is getting me results......

use of response.setContentType("text/xml"); is more appropriate here.. as you are outputting XML or a plain text here...

make sure you set the reponse headers in the below fashoin while outputting the results....

response.setContentType("text/xml");

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

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

response.setDateHeader("Expires", 1);

response.setDateHeader("max-age", 0);

and if you are serious about implementing AJAX i would advice you start learn basics of XmlHttpRequest Object and more about DOM parsing is being implemented using javascript.

http://www.w3.org/TR/XMLHttpRequest/#xmlhttprequest0

http://www.jibbering.com/2002/4/httprequest.html

http://java.sun.com/developer/technicalArticles/J2EE/AJAX/

http://developer.apple.com/internet/webcontent/xmlhttpreq.html

http://www.javascriptkit.com/domref/documentproperties.shtml

and then go about trying different means of achieving them using simpler and cool frameworks

like DWR,dojo,Prototype,GWT,Jmaki,Back Base 4 Struts,Back Base 4 JSF....etc and

others frameworks like Tomahawk,Ajax4Jsf,ADF Faces,ICE FACES and many others which work with JSF.

Please Refer

http://swik.net/Java+Ajax?popular

http://getahead.org/blog/joe/2006/09/27/most_popular_java_ajax_frameworks.html

Hope that might help :)

and finally an advice before implementing anything specfic API which may be related to any technologies (JAVA,javascript,VB,C++...) always refer to API documentation first which always gives you an Idea of implementing it.

Implementing bad examples posted by people(even me for that matter) directly doesn't make much sense as that would always lands you in trouble.

and especially when it is more specific to XmlHttpRequest always make habit of refering

specific Browser site to know more about why specific Object or its property it not working 4i

IE 6+: http://msdn2.microsoft.com/en-us/library/ms535874.aspx

MOZILLA: http://developer.mozilla.org/en/docs/XMLHttpRequest

Safari: http://developer.apple.com/internet/webcontent/xmlhttpreq.html

Opera 9+: http://www.opera.com/docs/specs/opera9/xhr/

Hope there are no hard issues on this...

REGARDS,

RaHuL

RahulSharnaa at 2007-7-12 19:36:46 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5

Thank you for your help! I solved the problem.

I did take example of your approach, and of other example. It is not working with FireFox, but I will find the solution.

It is giving me the following error in FireFox:

Error: uncaught exception:

[Exception... "Not enough arguments" nsresult: "0x80570001 (NS_ERROR_XPC_NOT_ENOUGH_ARGS)" location: "JS frame :: http://localhost/p1/left9.jsp :: removeItems :: line 53" data: no]

In IE the page loads perfectly, with the correct drop-down lists disabled because of a javascript function I invoke onLoad, but it does not work in FireFox... I will work with this now..

-

I will post my final solution, as a link to a .zip, perhaps on Thursday. :-)

tofuwithcoffeea at 2007-7-12 19:36:46 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 6

Okidoki...

In FireFox it worked with:

Add an item:

lista.appendChild(newOption);

....where lista is referring to a <select>...

In IE, however, it worked with a plain:

lista.add(newOption);

....I'm still working with the remove()...

tofuwithcoffeea at 2007-7-12 19:36:46 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 7
well remove is much simple as far as my knowledge goeslista.length=0that should empty all the elements in the drop down....
RahulSharnaa at 2007-7-12 19:36:46 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 8
thanks
tofuwithcoffeea at 2007-7-12 19:36:46 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 9
code posted here -- > http://msmeerkat.googlepages.com/ajaxJSPExample.zip....comments are not in English.....
tofuwithcoffeea at 2007-7-12 19:36:46 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...