John Davidson

Use html input to send http request to change PHP SESSION variable

0 comments
Message:


I have an html table which I want to have a night mode and a day mode. I've built a very basic example of what I'm trying to do below. The boxes in this table will have different colors depending on whether their class is set to "condition_night" or "condition_day". The page will refresh quite often so I'm trying to use the php SESSION object to keep the mode of the page across refreshes. See snippet


<?php

session_start();




if(isset($_SESSION['MODE']) && $_SESSION['MODE'] === 'night'){
$mode = 'night';
} else {
$mode = 'day';
};

?>
<style>
.condition_night {
background-color: grey;
color: black;
}
.condition_day {
background-color: blue;
color: white;
}

</style>
<table>
<thead>
<tr>
<th class="condition_<?=$mode;?>">Person</th>
<th class="condition_<?=$mode;?>">Score</th>
</tr>
</thead>
<tbody>
<tr>
<td>James</td>
<td>100%</td>
</tr>
</tbody>

</table>


<input type="button" name="night_mode" class="btn btn-secondary" value="Night Mode" onclick="change_session_day.php;" data-dismiss="modal" style="width: 170px;margin-top: 5px;margin-bottom: 5px;"/>

<input type="button" name="day_mode" class="btn btn-secondary" value="Day Mode" onclick="change_session_day.php;" data-dismiss="modal" style="width: 170px;margin-top: 5px;margin-bottom: 5px;"/>

I am fully aware that the buttons at the bottom of the page won't work I've put them there as an example of what I'm trying to achieve. Is there a way to make the buttons call a separate php script on another page which will change the SESSION['MODE'} variable, then refresh the page so that the new colors are apparent?


The script on the php page would go along the lines of See Snippet


<?php

session_start();
$_SESSION['MODE']="day";

//Refresh page here
?>


My Answer:
To achieve this functionality, you can modify the buttons to make an AJAX request to the PHP script that changes the SESSION variable and then refreshes the page. Here's an example of how you can do this:

1. Modify the buttons in your HTML to call a JavaScript function that makes an AJAX request:

html







2. Create a PHP script named `change_session_mode.php` that changes the SESSION variable based on the mode passed in the AJAX request:

php
session_start();

if(isset($_POST['mode'])) {
$_SESSION['MODE'] = $_POST['mode'];
echo 'Mode changed successfully';
} else {
echo 'Mode not specified';
}
?>


With this setup, when you click the Night Mode or Day Mode button, it will make an AJAX request to the `change_session_mode.php` script, which will change the SESSION variable and then refresh the page to reflect the new mode.

Rate this post

3 of 5 based on 1537 votes

Comments




© 2024 Hayatsk.info - Personal Blogs Platform. All Rights Reserved.
Create blog  |  Privacy Policy  |  Terms & Conditions  |  Contact Us