how to get the value from a database without submitting a jsp page

I have a jsp which has a text box depending on the value entered I want to get the value from a database for other two fields with out submitting jsp page. I am using struts.Thanks For any assistance provided.
[223 byte] By [SubhaMania] at [2007-11-27 8:34:47]
# 1
you can use ajax to call a struts action , without actually submitting the form. Just google for ajax and use an example appropriate for your requirement
R@njita at 2007-7-12 20:31:07 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 2

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

var http_request = false;

function makePOSTRequest(url, parameters) {

http_request = false;

if (window.XMLHttpRequest) { // Mozilla, Safari,...

http_request = new XMLHttpRequest();

if (http_request.overrideMimeType) {

// set type accordingly to anticipated content type

//http_request.overrideMimeType('text/xml');

http_request.overrideMimeType('text/html');

}

} else if (window.ActiveXObject) { // IE

try {

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

} catch (e) {

try {

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

} catch (e) {}

}

}

if (!http_request) {

alert('Cannot create XMLHTTP instance');

return false;

}

http_request.onreadystatechange = showAmount;

http_request.open('POST', url, true);

http_request.setRequestHeader("Content-type", "application/x-www-form-urlencoded");

http_request.setRequestHeader("Content-length", parameters.length );

http_request.setRequestHeader("Connection", "close");

http_request.send(parameters);

}

function showAmount() {

if (http_request.readyState == 4) {

if (http_request.status == 200) {

alert(http_request.responseText);

result = http_request.responseText;

result_array=result.split(",");

document.getElementById('xxx').value = result_array[0];

document.getElementById('xxx').value = result_array[1];

document.getElementById('xxx').value = result_array[2];

} else {

alert('There was a problem with the request.');

}

}

}

function get() {

if(document.getElementById('xxx').value !="0" && document.getElementById('xx'x).value !="0"){

var poststr = "select=dispatchParameter&xxxx="+encodeURI( document.getElementById('xxx').value )+

"&yyyyy="+encodeURI( document.getElementById('xxx').value);

var proto = document.location.protocol;

var host = document.location.host;

makePOSTRequest( proto+"//"+host+"/xyz/actionxyz.do",poststr);

}

}

</script>

set the parameter as select in the struts-config for this action

add the parameter is application properties..

it will redirect to the correct action

in action perform the logic.

response can be written as

String str= < the values u want show >

response.getWriter().write(str);

and the action should return null.

PS :- This ajax code i got it from some site and modified for my requirement.You can find many more examples in net

HTH

R@njita at 2007-7-12 20:31:07 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 3
can you please tell me the site or explain me with an example.
SubhaMania at 2007-7-12 20:31:07 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 4
Try this. http://w3schools.com/ajax/default.asp
R@njita at 2007-7-12 20:31:07 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 5
can this be done using other than AJAX since my user might use old browser which doesn't support AJAX.
SubhaMania at 2007-7-12 20:31:07 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 6

Well looking at your problem using AJAX / XmlHttpRequest Object is just one of the solutions for acheiving it however there are few other ways of doing this too...

1).Maintain the State of the Form in the scope of the session (Bean).Call an action on onKeyup event of input textbox and then get the values from DB and update the Form Bean stored in the scope of session, then redirect the control the same page again and re-render the form by updated state of the Form bean.

2).Use a hidden Iframe and then call an Action and get XML reponse of it.Use this.document.getElementById("hiddenIframeId").contentDocument DOM Object parse the XML content and then get the values out of it and then update the view accordingly.

3).Use a Hidden Iframe and call an action and then in the hidden Iframe JSP on the ONLOAD event update parent.formname.componentName.value.

Hope that might help you :)

REGARDS,

RaHuL

RahulSharnaa at 2007-7-12 20:31:07 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 7
Rahulcan you explain in detail by providing me an example.thanks
SubhaMania at 2007-7-12 20:31:07 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...
# 8

Alright,here is an example for you for the first case.

Present.jsp:

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

<html:html>

<head>

<title><html:message key="page.title"/></title>

</head>

<body>

<html:form action="ChangeEvent.do">

<html:hidden property="method"/>

<!-- Submitting the Form onKeyUp of EmpId field and trying to save the

state of the Form in the scope of session -->

Emp Id:<html:text property="empId" size="5" onkeyup="if(true){this.form.elements[0].value='populateDetails';this.form.submit();}"/>

Emp Name:<html:text property="empName" size="10" />

Email Address:<html:text property="email" size="10" />

<html:submit>Submit</html:submit>

</html:form>

</body>

</html:html>

struts-config.xml:

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

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

<!DOCTYPE struts-config PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 1.1//EN" "http://jakarta.apache.org/struts/dtds/struts-config_1_1.dtd">

<struts-config>

<!-- Form bean which stores the properties of all the Form elements -->

<form-beans>

<form-bean name="employeeFormBean" type="org.apache.struts.action.DynaActionForm">

<form-property name="empId" type="java.lang.String"/>

<form-property name="empName" type="java.lang.String"/>

<form-property name="email" type="java.lang.String" />

</form-bean>

</form-bean>

<action-mappings>

<action path="/ChangeEvent" type="Test.GetChangeAction" name="employeeFormBean" scope="request" parameter="method">

<!-- On successful call of DB the Page has to be forwarded to the same page again by

uploading updated form bean values. -->

<forward name="success" path="/Present.jsp"></forward>

<forward name="failed" path="/error.jsp"></forward>

</action>

</action-mappings>

</struts-config>

GetChangeAction.java:

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

public class GetChangeAction extends DispatchAction{

-

-

-

public ActionForward populateDetails(ActionMapping mapping,ActionForm form, HttpServletRequest request, HttpServletResponse response) throws Exception {

DynaActionForm dForm = (DynaActionForm)form;

String empId = dForm.get("empId");

// calling Model / Db and then getting back Employee Details

EmployeeBean eb = ModelUtils.getDetails(empId);

// Updating form bean by updating values from the Model

dForm.set("empName".eb.getEmpName());

dForm.set("email".eb.getEmail());

return mapping.findForward("success");

}

-

-

-

}

well to me this should work regardless to any browser but we need to make sure we put in our logic properly.

RahulSharnaa at 2007-7-12 20:31:07 > top of Java-index,Enterprise & Remote Computing,Web Tier APIs...