0

I want to update the value of a session attribute when a button is clicked on a page without using a form and redirecting to another page.

I've looked at JSTL and scriptlets but because these occur on the server end, they already happen before the button is clicked.

I have looked into AJAX but I am not entirely sure how the whole process works.

Any suggestions on how to accomplish this?

Something that can be incorporated into:

function myFunction()
{
    //setAttribute("session_variable_name", "newvalue")
}
<button onclick="myFunction()">Change Variable</button>
spenibus
  • 4,339
  • 11
  • 26
  • 35
N Hoss
  • 1
  • 2

2 Answers2

1

Ajax is the way to go:

Jquery ajax:

var request = $.ajax({
  url: "/changesession.jsp", 
  type: "POST",
  data: ["newSessionValue"=>'newSessionValue'],
});

request.done(function( msg ) {
  alert('suceess changed');
});


request.fail(function(msg)) {
   alert('failed ajax')
});

And in your changesession.jsp

HttpSession session = request.getSession();
String newValue= ${param.newSessionValue};
setAttribute("session_variable_name", "newvalue");

Hope this helps.

Nishanth Matha
  • 5,993
  • 2
  • 19
  • 28
  • Thanks a lot! One question though wouldn't the following be in the servlet rather that the jsp: `HttpSession session = request.getSession(); String newValue= ${param.newSessionValue}; setAttribute("session_variable_name", "newvalue");` – N Hoss Oct 05 '15 at 03:04
  • it can be in either sevlet or jsp.. depends on what you want to acheieve after it. If you put that in a servelet then make sure to chage the URL to point to that particular servlet. – Nishanth Matha Oct 05 '15 at 03:18
-1

PHP side code // the_php_file_that_change_your_session.php

<?php 
    if( isset($_POST["sessionVarName"]) && isset($_POST["sessionVarValue"]) ) 
    {
        $_SESSION[$_POST["sessionVarName"]] = $_POST["sessionVarValue"] ;
    }
    exit();
?>

Javascript side code

function myFunction()
{
    $.post("the_php_file_that_change_your_session.php",{sessionVarName:sessionVarName_Value,sessionVarValue:sessionVarValue},function()
    {
        // do what you want after the Session variable is changed
    });
}
Diptox
  • 1,809
  • 10
  • 19