I'm trying to use html onclick in java servlets like this;

ShoppingCart cart = new ShoppingCart();
out.println("  <h1><button type=\"button\" onclick=\"cart.addBook(b.getIsbn())\">add</button> </h1>");

addBook is a method in ShoppingCart class, and I'm calling it when the button is clicked, but it's not getting called. Please help.

Edited by peter_budo: Moving to Java Web and fixing code formatting

4 Years
Discussion Span
Last Post by Tu Dinh

the onclick event on a standard HTML button invokes javascript, not Java. So your code is looking for a javascript function called addBook on a javascript object called cart.

I believe you need to have the form POST to your servlet in order for the Java code to execute on the server. If you are using a shopping cart package, they will likely have implementation example code you could check to see how this should be called.


If you still don't understand @|-|x explanation. Just remember that Javascript is executed within Browser, Java code is executed from Server.

I believe in your case, you have to send a request from Browser to Server, which means using Javascript to send request to Server

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.