1

I have a scenario where a form has to be filled in as easily as possible. The values to be filled in in the form, are asked from the user initially and stored in database.

Afterwards, when user clicks on a button, a javascript function is invoked that auto-fills all the fields in the form with values obtained by jsp/servlet.

I want to retrieve the values (that are to be filled in into the form) from database with the help of servlet/jsp...Now there should be some way for the javascript function to fill in this value (that was obtained by the servlet/jsp) into the form...

Is it possible to do such sharing of data/variables between jsp/servlets and javascript functions? The javascript functions will be part of the jsp (that retrieves the value that should be filled in in the form).

user974573
  • 65
  • 6

3 Answers3

1

The Javascript client in the browser has no direct access to the environment on the server (and shoudln't - imagine how it would be bad if all pages broke the day you decided to use a diferent server solution). You basically have two choices:

  • Include all the data you will ever need on the page you serve to the client (perhaps the form html is dinamically generated to suit your needs, etc etc)

  • Manually request extra information dinamically via XMLHttpRequest (aka AJAX). This is the only way if you can only determine what data you will need dinamically, after the page loads.

hugomg
  • 68,213
  • 24
  • 160
  • 246
1

If the request is sent synchronously (e.g. a form submit button), then you don't necessarily need JS for this job. Just let JSP/EL print them immediately as input values based on data which is prepopulated by a servlet. For example, assuming that ${user} is a typical Javabean which is prepared by the servlet:

<input type="text" name="name" value="${fn:escapeXml(user.name)}" />
<input type="text" name="city" value="${fn:escapeXml(user.city)}" />
<input type="text" name="country" value="${fn:escapeXml(user.country)}" />

(the fn:escapeXml() is just to prevent XSS attacks)

If the request is sent asynchronously (e.g. using ajax), then you just need to let the servlet return the data in a format which is easily parseable by JS, for example JSON.

{
    "username": "Bauke Scholtz",
    "city": "Willemstad",
    "country": "CuraƧao"
}

which you can then use as follows in the ajax response callback function (where user is the obtained JSON object):

document.getElementById("name").value = user.name;
document.getElementById("city").value = user.city;
document.getElementById("country").value = user.country;

jQuery makes things like this much easier. See also How to use Servlets and Ajax?

Community
  • 1
  • 1
BalusC
  • 1,082,665
  • 372
  • 3,610
  • 3,555
0

You could access your database dynamiclly using xmlhttprequest. For further information + relevant examples read : http://www.w3schools.com/ajax/ajax_aspphp.asp