Oxenarf
Oxenarf

Reputation: 278

How to pass an argument from javascript to a Servlet through JSP

I'd like to do something like that

function(){
    <% ExampleClass sample = new ExampleClass(); %>
    var ID = 4;
    var something = <%= sample.getSomethingById(ID) %>
}

How can I pass this ID to the jsp expression?

Thanks for any suggestion, and sorry id the question is not so well formulated.

Upvotes: 2

Views: 4357

Answers (4)

MaVRoSCy
MaVRoSCy

Reputation: 17839

you can also use more advanced methods and tools, like Ajax and JQuery:

function submitToJsp(){
    $.ajax({
        type: 'POST',
        url: 'mypage.jsp',
        data: {
            id: '123',
            comment:$('#comment').val()
        },
        beforeSend:function(){
            // this is where we append usually a loading image
        },
        success:function(data){
            // successful request; do something with the data
            $('#output').html(data);

        },
        error:function(){
            // failed request; give feedback to user
        }
    });

}

In short, by calling the function submitToJsp(); we send an asynchronous (ajax) request to the mypage.jsp jsp with 2 parameters.

Upvotes: 1

JDGuide
JDGuide

Reputation: 6525

You should use hidden field :-

<input type="hidden" name="hdtest" id="idtest" value="<%=sample.getSomethingById(ID) %>" />

Now inside javascript try to access the value.

Try this code in java script :

var something = document.getElementById('idtest').value;

Hope it will help you.

Upvotes: 1

NilsH
NilsH

Reputation: 13821

Your javascript code is not executed until after the JSP page has been rendered. So any java variables you want to access in your script needs to be pre-rendered as a javscript variable. After the page has been rendered, you can't execute java code in your javascript. You can't "share" variables between java code and javascript like that. Your example is probably simplified, but in this case, you could just do

var something = <%= sample.getSomethingById(4) %>

Upvotes: 1

PSR
PSR

Reputation: 40318

use hidden variable and then put the id into that variable.You can not pass using the code above.

<input type="hidden" name="test" value="your id" />

Then you can access like request parameter.

Upvotes: 1

Related Questions