-2
function checkId(val){
   alert("hello " + val);
   if(val == "yes"){
      <% req.getSession().setAttribute("buttonValue","yes"); %>
   } else {
      <% req.getSession().setAttribute("buttonValue","nil"); %>
   }
}

Value keeps changing to 'yes' & 'nil' as per button click which is fine when I check it as alert, but this function always set 'buttonValue' to 'nil'.

Please help, Thanks in advance.

Shiladitya
  • 12,003
  • 15
  • 25
  • 38
  • 4
    instead of `alert("hello " + val);` do `console.log(val);` and noe check the console and paste the output what you got here in your question – Alive to die - Anant Aug 24 '17 at 06:37
  • Use `===` in place of `==` and in everyplace use single quote instead of double quotes. Remove `alert`. and try checking for `if(val === 'nil')` once in condition. It might let you know what's wrong. – Om Sao Aug 24 '17 at 06:39
  • What's wrong is a basic misunderstanding of the difference between client- and server-side code. – Dave Newton Aug 25 '17 at 14:14

1 Answers1

0

The reason this is happening is because you're conflating JS (runs on the client) with scriptlets (runs on the server). This is basic web development stuff.

When this code runs on the server it first sets the value to "yes", but the server doesn't care at all about your JS, so continues on and sets it to "nil".

This is trivially demonstrable by swapping the values: suddenly the value will always be "yes".

If you want to change a session value through JS you need to make an XHR call to the server.

Dave Newton
  • 158,873
  • 26
  • 254
  • 302