Tom
Tom

Reputation: 771

pass value to servlet from jsp by hyperlink

I saw answers relating to this question and tried to solve still I am getting null in Servlet, where I am doing mistake?? Perhaps I am missing something in Javascript or in jsp??

home.jsp

 <head>
 <script type="text/javascript" src="layout/styles/jquery-latest.min.js"></script>

 <script type="text/javascript">

      function callMe(){
$.ajax({
  type: "POST",
  url: "/NewServlet",
  data: { methodToInvoke: "sayHello" , data: "4" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});
}  
        </script>

I want to pass the value 4 to servlet(doPost in NewServlet.java) from home.jsp

<a href="NewServlet?count=4" onclick="callMe()" id="4" >HTML Images</a>

NewServlet.java

 String t= request.getParameter("count");
           out.println(t);// should display 4, but getting null here

Upvotes: 0

Views: 1071

Answers (2)

ccheneson
ccheneson

Reputation: 49410

Put the count=4 in the url of your ajax request

function callMe(count){
$.ajax({
  type: "POST",
  url: "/NewServlet?count=" + count,
  data: { methodToInvoke: "sayHello" , data: "4" }
}).done(function( msg ) {
  alert( "Data Saved: " + msg );
});
}  

and in your jsp:

<a  onclick="callMe(4)" id="4" >HTML Images</a>

Edit: To send the count back to the webbrowser, do:

PrintWriter out = response.getWriter();
out.println(t);

where response is a HttpServletResponse .

See here to get started

Upvotes: 1

Mohamed Elbeialy
Mohamed Elbeialy

Reputation: 31

Your parameter name is "count" not "param1" .. So, It should be:

String t = request.getParameter("count");

Upvotes: 0

Related Questions