0

I want to send code title and price as an argument to the book object but gives illegal start expression error.

 function addrecord() {
    code = document.getElementById('code').value;
            title = document.getElementById('title').value;
            price = parseFloat(document.getElementById('price').value);

    <%   Book book = new Book(%> code <% ,%> title <% , %> price <% );
   bookdb.addRecord(book);   
             %>
            document.getElementById("code").value = "";
            document.getElementById("title").value = "";
            document.getElementById("price").value = "";
    }
Salil Chauhan
  • 13
  • 1
  • 1
  • 2

2 Answers2

3

You are misunderstanding where java and javascript run. You use <% and %> as if that sends values to the server, which it does not. those tags are used only inside the jsp to start snippets of java code. This only works while you are generating the page. Once your html is at your browser, these tags will not do anything.

Highlighting important keywords, this is not intended as sarcarsm

When you request a jsp page with your browser, the browser opens a network connection to the server. Think of these 2 (browser, server) as living in 2 completely different places.

The server then runs the java code. When it executes, it generates an html page. This html page is sent back across the network connection to the client (your browser)

Your browser will receive this fully formed html page and use it to create it's view. On this page you can run javascript but the javascript will only run on the client (browser)

To get any variable back to the server again, you will need to either: get or post a form (using a submit inside a form tage, or use JavaScript post request like a form submit) , do an ajax call (http://www.javascriptkit.com/dhtmltutors/ajaxgetpost.shtml) or have the user click a link (a href="...your page").

The easiest way is to do:

<form method="POST" action="your/page/url">
    <input type="hidden" name="someName" value="someValue" />
    <input type="submit" />
</form>

read some of the links and make sure you keep in mind, your browser and the server are separated, so running javascript in your browser will not reach the server.

Community
  • 1
  • 1
Joeblade
  • 1,582
  • 13
  • 19
1

See here: Assign JavaScript variable to Java Variable in JSP

As that states, it's really not possible as the JSP executes on the server, and the javascript executes later in the browser.

Community
  • 1
  • 1
ash
  • 4,078
  • 1
  • 17
  • 29