Reputation: 532
Is there a way of having a user select an item from an HTML SELECT dropdown and then store it in a $_SESSION variable before they navigate away from a page? I know the obvious way is to get the FORM to return to the same page and then check for the variable being set, but I'm trying to modify something that someone else has done without a major rewrite!
I.e. can a session variable be set whose value changes depending on the user's SELECT option without reloading the page?
All help much appreciated.
Upvotes: 0
Views: 2548
Reputation: 1
On your HTML file you have this jquery / javascript code:
$(document).ready( function() {
$("#my_select").change( function() {
// alert($(this).val());
url = "MyPage.php";
var myData = {};
myData['my_select'] = $(this).val();
jQuery.get( url, myData, function(data)
{
// console.log(data);
// the placeholder where you wanted to show it
$("#my_session_select_value").html(data);
});
});
});
and on your php file (which stores the session value) you have this code:
session_start();
$_SESSION['my_select'] = $_GET['my_select'];
// if you wanted a json encoded result
// echo json_encode($_SESSION);
// if you wanted a direct value
echo $_SESSION['my_select'];
Upvotes: 0
Reputation: 1542
You will need to make a AJAX request to the script from the HTML, you could use jQuery*
$(document).ready(function()
{
$("#dropdown").change(function()
{
var link = 'updateSession.php?value_to_update='.$(this).val();
$.ajax({
url: link,
type: "GET",
dataType: "html",
success: function(html)
{
$('#message').html(html);
}
});
});
});
*other JavaScript libraries are available
Upvotes: 1
Reputation: 55730
The only way you can modify the $_SESSION variable without reloading the page is to do an async request (i.e. AJAX).
Technically, you can't modify the session variable from the client side. This means that one way or another you need to make a request to the server - either by reloading the page, posting to a different page, or making an out of bound request using Ajax.
Upvotes: 1
Reputation: 72672
That is called AJAX.
http://nl.wikipedia.org/wiki/Asynchronous_JavaScript_and_XML
But there is no pure PHP way because PHP is serverside only.
So you will have to resort to javaScript.
Upvotes: 4