This week's giveaway is in the Spring forum.
We're giving away four copies of REST with Spring (video course) and have Eugen Paraschiv on-line!
See this thread for details.
The moose likes Servlets and the fly likes Calling servlet from a Javascript Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login

Win a copy of REST with Spring (video course) this week in the Spring forum!
JavaRanch » Java Forums » Java » Servlets
Bookmark "Calling servlet from a Javascript" Watch "Calling servlet from a Javascript" New topic

Calling servlet from a Javascript

P Agarwal

Joined: Jun 03, 2004
Posts: 2
Can anyone help me in calling a servlet from a javascript? I am new to this. Please help. Thanks in Advance.
Ranch Hand

Joined: Nov 22, 2008
Posts: 18944
You can use following in script
P Agarwal

Joined: Jun 03, 2004
Posts: 2

Thanks for your reply. But actually I want to call the servlet which would return me one XML, that is to be parsed. So if I submit the form, how will I get the XML? I don't have any idea as how to retrieve XML from servlet called through Javascript.
If you can give me any clue...
Paul Sturrock

Joined: Apr 14, 2004
Posts: 10336

JavaScript (which runs clientside in this context) cannot directly call a servlet - since it is serverside code. What it can do (as Gajanan C explains) is make an HTTP request to the server. What will come back is probably another HTML page. If you then want to run clientside JavaScript with variables dynamically set in the servlet you will have to render them into the HTML page. For example:
<script language="JavaScript">
alert("I'm doing something with XML: " + <%=xmlStringFromJSP%> ) ;
[ June 03, 2004: Message edited by: Paul Sturrock ]

JavaRanch FAQ HowToAskQuestionsOnJavaRanch
wood burning stoves
subject: Calling servlet from a Javascript
It's not a secret anymore!