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.

Recommended Answers

All 2 Replies

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

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.