2

I'm trying to make a cart for a shopping site and i use javascript to retrieve data from the servlet and somehow, the javascript isn't being called at all, i tried putting an alert() into the function to check but it's not being called. Can anyone help me? I'd appreciate any help provided, thanks in advance

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
    <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="Style.css">
</head>
<body onload="load();">
    <div id="nav">
        <button class="navbtn" onclick="location.href='Home.jsp'">Home</button>
        <button class="navbtn" onclick="location.href='Show'">Products</button>
        <button class="navbtn">About Us</button>
        <button class="navbtn" style="float:right;" onclick="location.href='Login.jsp'">Log in</button>
        <button class="navbtn" style="float:right;" onclick="location.href='Register.jsp'">Register</button>
        <button class="navbtn" onclick="location.href='Cart.jsp'">Cart</button>
        <form style="float:right;" method="Post" action="SearchController">
            <input name="search" id="search" type="text" placeholder="Search..">
            <input type="submit" style="display:none">
        </form>
    </div>
    <table id="tbl" style="border: 1px solid black;width:100%;border-collapse:collapse;">
        <tr>
            <th style="border: 1px solid black;">Name</th>
            <th style="border: 1px solid black;">Price</th>
            <th style="border: 1px solid black;">Quantity</th>
            <th style="border: 1px solid black;">Amount</th>
        </tr>
        <tr id="row">
            <td id="name" style="border: 1px solid black;"><c:out value="${arr.get(0).name}"/></td>
            <td id="price" style="border: 1px solid black;"><c:out value="${arr.get(0).price}"/></td>
            <td id="quantity" style="border: 1px solid black;"><c:out value="${arr.get(0).quantity}"/></td>
            <td id="amount" style="border: 1px solid black;"><c:out value="${Math.ceil(arr.get(0).price*arr.get(0).quantity) }"/></td>
        </tr>
    </table>
    <button style="width:100px;height:30px;background-color:orange;border:none">Submit</button>
    <script type="application/javascript">
    function createRow(int i) {
          var row = document.createElement('tr');
          var col = document.createElement('td');
          var col2 = document.createElement('td');
          var col3 = document.createElement('td');
          var col4 = document.createElement('td');
          row.appendChild(col);
          row.appendChild(col2);
          row.appendChild(col3);
          row.appendChild(col4);
          col.innerHTML = ${arr.get(i).name};
          col2.innerHTML = ${arr.get(i).price};
          col3.innerHTML = ${arr.get(i).quantity};
          col4.innerHTML = ${arr.get(i).price}*${arr.get(i).quantity};
          var table = document.getElementById("tbl");
          table.appendChild(row);
        }
        function load(){    
            alert("Test");
            for(int i=0;i<{arr.size()};i++){
                createRow(i);
            }
        }
        
    </script>
    
</body>
</html>
Edit: Already got answer from comment section
ObscurusLux
  • 370
  • 3
  • 14
  • 1
    You have a bunch of syntax errors, starting here: `col.innerHTML = ${arr.get(i).name};` You don't need that dollar wrap unless you're inserting values into a template literal. Replace those lines with `col.innerHTML = arr.get(i).name;` and similar.(and always check the browser console for errors first) –  Jan 20 '21 at 12:08
  • 1
    Javascript does not have any static datatypes. Change `function createRow(int i)` to `function createRow(i)` & `for(i=0;i<{arr.size()};i++)` to `for(let i=0;i – A Rogue Otaku Jan 20 '21 at 12:10
  • @ChrisG it's not a syntax error, i'm trying to retrieve data from the servlet – ObscurusLux Jan 20 '21 at 12:33
  • where is `servlet` code ? how you are retrieving that values ? there is no code for that. – Swati Jan 20 '21 at 13:25
  • https://www.codepile.net/pile/1x28Z6Gg I can't paste it on here because it contains too much character, sorry – ObscurusLux Jan 20 '21 at 14:21
  • 1
    Yes, it's absolutely a syntax error. If you want to prevent that, I guess you need to use the same syntax like further up: `col.innerHTML = ` however you're still mixing client-side and server-side code. You cannot use a client-side `i` to dynamically grab `arr.get(i)` from the server. You need to a) make the entire `arr` available to your client-side JavaScript code then b) use that to create your rows. –  Jan 20 '21 at 14:47
  • 1
    However, none of that seems to be necessary at all in the first place; you should use a server-side loop to directly build that table on the server, not pass that on to client-side JavaScript. To be clear: the code you have inside ` –  Jan 20 '21 at 14:48
  • @ChrisG Thanks, i owe you my life – ObscurusLux Jan 20 '21 at 14:54

2 Answers2

1

In this case, the JavaScript Code ist defined after the use. In the body tag, you refer to the load() method which is declared afterwards. Moving the load() method up into the head could also help to solve the problem.

EricHier
  • 446
  • 3
  • 10
  • 1. body onload code can absolutely refer to functions declared further down. 2. this answer does not even attempt to address the actual problem here: mixing client-side and server-side code as if they run simultaneously, as opposed to before and after an HTTP request. –  Jan 20 '21 at 14:51
0

I think You should you JS syntax instead Java(or else).

function load(){    
        alert("Test");
        // try to comment this and previous function and you will get your alert.
        // for(let i = 0; i < array.length; i++){
            // createRow(i);
        //}
    }

For Example in JS your loop looks like this:

function load(){    
   alert("Test");
     
   for(let i = 0; i < array.length; i++){
       createRow(i);
   }
}

enter image description here

I hope It'll help you! Be happy and Have a clean code :)

  • I don't think that EL works like that though – ObscurusLux Jan 20 '21 at 12:37
  • Ok, but what chrome dev tools console says? (F12) Do you see any errors? – Aleksey Zikrackiy Jan 20 '21 at 12:39
  • You don't have use static types like `int` etc, In Js you have to use let/const :) – Aleksey Zikrackiy Jan 20 '21 at 12:42
  • i removed the thing but it's still not working – ObscurusLux Jan 20 '21 at 12:46
  • I'm sure, you can see some errors in you chrome console. – Aleksey Zikrackiy Jan 20 '21 at 12:49
  • the errors are even weirder, it said unexpected token ';' at line 50 and Failed to load resource: the server responded with a status of 404 () :8080/favicon.ico:1. After adding something to the cart, the unexpected token error turned to unexpected number while the data the site received is string and the failed to load resource error was gone – ObscurusLux Jan 20 '21 at 12:53
  • Ok, but what are you see in the `elements` tab on chrome dev tool? Do you see you JS in correct syntax?) – Aleksey Zikrackiy Jan 20 '21 at 12:56
  • Could you please send script part from elements tab?) – Aleksey Zikrackiy Jan 20 '21 at 13:13
  • function createRow(i) { var row = document.createElement("tr"); var col = document.createElement("td"); var col2 = document.createElement("td"); var col3 = document.createElement("td"); var col4 = document.createElement("td"); row.appendChild(col); row.appendChild(col2); row.appendChild(col3); row.appendChild(col4); col.innerHTML = iPhone 11 Pro Max 512GB; col2.innerHTML = 17.99; col3.innerHTML = 2.0; col4.innerHTML = 17.99*2.0; var table = document.getElementById("tbl"); table.appendChild(row); } function load(){ alert("Test"); for(int i=0;i<20;i++){ createRow(i); } } – ObscurusLux Jan 20 '21 at 14:18
  • 1. don't use `int` in 'for', use `let` instead. 2. Change `col.innerHTML = iPhone 11 Pro Max 512GB;` => `col.innerHTML = "iPhone 11 Pro Max 512GB";` – Aleksey Zikrackiy Jan 20 '21 at 14:55
  • not creating any difference, besides, i already got the answer from the comment section – ObscurusLux Jan 20 '21 at 14:57
  • Oh, It's cool! Sorry, I didn't see answer in comments) – Aleksey Zikrackiy Jan 20 '21 at 15:00
  • Nah, it's fine, i used to be like you, at least 5 times so it's ok – ObscurusLux Jan 20 '21 at 15:04