Reputation: 5472
I intend to call a function in JavaScript which then calls a Servlet after an <input type="image">
is clicked.
JSP:
<head>
<script type="text/javascript">
function callServlet() {
document.location.href="test-servlet.jsp";
}
</script>
</head>
<body>
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
...
<input type="image" name="submit"
src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_buynow_pp_142x27.png"
onclick="callServlet()" alt="PayPal - The safer, easier way to pay online!">
</form>
</body>
Servlet (test-servlet.jsp
):
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<h1>TestServlet called successfully!</h1>");
}
Context Root:
http://localhost:8080/mysite/test-servlet.jsp
However, nothing happens when I click the image button. I am new to JavaScript.
Upvotes: 1
Views: 16672
Reputation: 1
Try this code
<a href="#" onclick="callServlet()"><img
src="https://www.paypalobjects.com/webstatic/en_US/btn/btn_buynow_pp_142x27.png"
alt="PayPal - The safer, easier way to pay online!"></a>
EDIT:
Finally we discovered that a servlet should be mapped without extension and doGet
method is used to get the request from javascript.
Upvotes: 1
Reputation: 8187
I Could see multiple errors in your jsp .
First of all ,
<form action="https://www.sandbox.paypal.com/cgi-bin/webscr" method="post">
And also use the img
tag with button
as Roman says
the url in the action
is called , when your form is being submitted
so try replacing it with ,
<form action="./test-servlet" method="post">
and using your JavaScript now,
You cant use window.location.href
to make a POST
request . check pass post data with window.location.href
<script type="text/javascript">
function callServlet() {
document.forms[0].submit;
}
</script>
Upvotes: 1