Need Cookbook JavaScript to Servlet Example

Posted on 2006-11-14
Medium Priority
Last Modified: 2011-04-14
I need a simple example on how pass and retrieve information from a servlet using java script.   There's a couple of related examples on EE, but I just don't get the whole picture.

Perhaps a simple cookbook example would make more sense.

Servlet takes values a and b and returns a + b

function callAddServlet(a, b){
    // pseudo code ,  How do I pass A and B to servlet and return c?
    c = a + b;
    return c;

What does the servlet look like that take 'a' and 'b' and returns 'a + b'?

How do i call the servlet from the JavaScript function.
Question by:tmonteit
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 4
  • 3
LVL 41

Assisted Solution

HonorGod earned 400 total points
ID: 17939527
 One way would be to use Ajax:

  The pseudo code for this would be:

  - create a request object
  - connect to servlet, sending values
  - wait for response

  The servlet would simply take the specified parameters, operate on them, and respond with the result.

  // Ajax routines for calling a servlet
  var xmlHttp;

  // Name: createXMLHttpRequest()
  // Role: Create the XML Request Object used by the Ajax routines
  function createXMLHttpRequest() {
    if ( window.ActiveXObject ) {
      xmlHttp = new ActiveXObject( "Microsoft.XMLHTTP" );
    } else if ( window.XMLHttpRequest ) {
      xmlHttp = new XMLHttpRequest();
  // Name: getInfo()
  // Role: Issue the request to the Addition servlet
  function getInfo( a, b ) {
    var queryString = '/servlet/Addition?A=' + a + '&B=' + b;
    xmlHttp.onreadystatechange = handleStateChange;
    xmlHttp.open( 'GET', queryString, true );
    xmlHttp.send( null );

  // Name: handleStateChange()
  // Role: Callback routine invoked when XML Request state changes
  function handleStateChange() {
    var field = document.getElementById( 'state' );
    field.value += xmlHttp.readyState + ' ';
    if ( xmlHttp.readyState == 4 ) {
        field.value += '  RC = ' + xmlHttp.status;
      if ( xmlHttp.status == 200 ) {

  // Name: parseResults()
  // Role: Routine used to process results of Addition
  function parseResults() {
    document.getElementById( "result" ).value = xmlHttp.responseText;
LVL 18

Accepted Solution

Morcalavin earned 1600 total points
ID: 17939699
Alternative using the javascript prototype ajax object(http://prototype.conio.net/)

<script src="prototype-1.4.0.js"></script>
function getInfo(a, b) {
var myAjax = new Ajax.Request(
                  'yourservleturl?a=' + a + '&b=' + b,  
                        method: 'get',
                        onComplete: function(response) {$F("result") = response.responseText;}

The servlet would simply take the a and b values from the querystring, add them and return the value(pseudo code below):
write querystiring(a) + querystring(b);

Author Comment

ID: 17940112
Morcalvin, I think i get it...  does getInfo need a return value?

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

LVL 18

Expert Comment

ID: 17940176
No.  the onComplete parameter will run an anonymous function that will populate an element value with the response from the servlet.  You could also populate a span or a div element with an id of "result" by doing the following:
$("result").innerHTML = response.responseText;

Author Comment

ID: 17941012
For the other half of the question, What would the servlet look like that returns for example:  2 + 3 = 5?

Stating the obvious...  Does the code that calls 'getInfo' then become:

var mySum = getInfo(a, b);

LVL 18

Expert Comment

ID: 17941110
No.  The server side code depends on the type of language you are using.  PHP, perl, ruby, python, asp, asp.net, etc.  It's entirely up to you.  All it needs to do is add up the two values and print the data out to the data to the browser.
getInfo has no return value.  response.responseText would be the value returned from your server side code(in your case the sum of a and b).  So if you wanted to use that value in some other function, you would need to pass the value to that function like so
...ajax code...
onComplete: function(response) {myFunction(response.responseText)}
...more ajax code..

function myFunction(mySum) {
         alert('The server added up a and b and the sum is + ' mySum);

Author Comment

ID: 17941836
Sorry, I'm getting confused over this 'missiing return value'.  Say its a simple Java Servlet

I pretty much have this code working.. passing in the a and b from the ajax.    Return of sum back to Javascript still baffles me.

public ActionForward executeAdd(ActionMapping mapping,
                  ActionForm form,
                  HttpServletRequest request,
                  HttpServletResponse response)
      AddForm addForm = (AddForm) form;
      Integer a = addForm.getA();
      Integer b = addForm.getB();

      Integer c = a + b;
   // Now what?


Author Comment

ID: 17941854
At the point I call getInfo, where do I get the return value?

var c = getInfo(a, b)   ??


Featured Post

Optimize your web performance

What's in the eBook?
- Full list of reasons for poor performance
- Ultimate measures to speed things up
- Primary web monitoring types
- KPIs you should be monitoring in order to increase your ROI

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will give core knowledge of JavaScript and will head in to your first JavaScript program. I am Durvesh Naik and I am here to deal with this series of JavaScript. I will teach you JavaScript in part wise , as its quite boring to read big…
This article demonstrates how to create a simple responsive confirmation dialog with Ok and Cancel buttons using HTML, CSS, jQuery and Promises
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

800 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question