Win a copy of Android Programming: The Big Nerd Ranch Guide this week in the Android forum!
  • Post Reply Bookmark Topic Watch Topic
  • New Topic

Calling a servlet from a javascript function  RSS feed

Harry Wordsworth
Posts: 27
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello, hopefully this is the right sub forum for this question.

How do I call a servlet from a javascript function?

Heres the background on my problem.
Using only javascript I have created a "Quiz" type website. Very simple, 10 multiple choice questions, all displaying on the same page at once. 

For an example, for question1, someone selects, on the main html page,  one of the 4 choices offered and hits a button. If the answer is right or wrong that info is displayed right there. I have it so that when the user hits the button a call is made to a function in an external javascript file. This function in the external file has the logic to add to the total score if the answer is right, and also to display a message if the answer was right or wrong.

For each of the 10 questions on the main html page there is a corresponding function in the external javascript file. The function that corresponds to the very last question, calls one last function which prints the total score.
Hopefully I described that clearly, if not please let me know. Anyhow this is how things work now.

What I want to do is this, when the user finishes the last question, give them the option to submit their name/score to a DB. This way I can keep a listing of scores, sort of like a "high score" list.
The way I want to do this....I to somehow have the javascript call a servlet but I am not sure how. I did some searching online and found this code but want advice on if this is really the way to go?

You can call a servlet from client side javascript using code like this :

In this snipped of code the loadservlet_onclick() javascript function is calling a servlet named myServlet that is in a package com.myproj, it pass 2 parameters to servlet.

The idea is that location.href takes a URL, so it can be a static html page, jsp or servlet.

Also I looked at just making the DB calls directly from javascript but from researching this online it seems to be very much frowned upon making any DB calls from javascript.
I am sure there may be alternate ways to doing this with other technologies but I am hoping to find a way using java/jsp/servets which I know and javascript which I know a little bit.

Bear Bibeault
Author and ninkuma
Posts: 65979
IntelliJ IDE Java jQuery Mac Mac OS X
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Using document.location is the equivalent of clicking a link. If you don't want the page to change you'll need to use Ajax.
It is sorta covered in the JavaRanch Style Guide.
  • Post Reply Bookmark Topic Watch Topic
  • New Topic
Boost this thread!