Calling a JSP method from JavaScript code; passing in a JavaScript variable as an argument


I have a JSP that contains a method within a scriplet and a Javascript function, which is used as an event handler.
I would like to call the JSP method, from the JavaScript event handler, passing the JavaScript variable as an argument.


    public String foo(int value) {
        int a=5;
        return new (Integer(value = value + a)).toString();

<script language="javascript">
    function onNodeSelect(nodeId) {

The following does not work because the servlet complains that it can not resolve "nodeId".  This makes sense.  However, I've tried using escape characters to resolve and was still unsuccessful.  Can this be done?
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

You cannot call a JSP method from javascript without some sort of background submit/HTTP Post.  Often this integration is now called AJAX (Asynchronous Javascript And Xml)

The JSP runs server side and the javascript client side so you have to send the information to the server to run the JSP method then return the results to the javascript.

I can't give you many more details since I am not familiar with how to do AJAX in JSP
First of all when the above code gets compiled, all the server-side code gets compiled and executed first.
So, the code <%=foo(nodeId%> would get compiled first.  Since there are no variabled named 'nodeId' declared anywhere, it will complain.

If you want your client code to execute a piece of server code, use XMLHttp object.

    function onNodeSelect(nodeId) {
var xmlHttp = new ActiveXObject("MSXML2.DOMDocument.3.0");
var result = xmlHttp.send("http://server/command.jsp?command='executeFoo'");

The underlying concept behind AJAX is the same, I guess.

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
d_allensworth1Author Commented:
Yes, I already resolved this issue with AJAX.  Thanks for the solution though.
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
Web Development Software

From novice to tech pro — start learning today.