lets say i have a code pretty similar like this
<form>
<input type="checkbox" name="account1" value="1">
<input type="checkbox" name="account2" value="2">
<input type="checkbox" name="account3" value="3">
<input type="checkbox" name="account4" value="4">
<button type="submit">Delete</button>
</form>
Now i want to store the value of the checkbox in a php session once the user checked the boxes without clicking the submit/delete button. I plan to use jquery/ajax for this but i still cant quite wrap my head around it since im very new to ajax or jquery.
To add more detail, the process is like this.. the user can select any account he wants he checked. lets say he checked an account on page 1. he then went to another page(pagination) and then went back to page 1, the checked boxes would still be checked.
CodePudding user response:
You can use onchange
event listener for this.
Live example here.
index.php
<form>
<input type="checkbox" name="account1" value="1">
<input type="checkbox" name="account2" value="2">
<input type="checkbox" name="account3" value="3">
<input type="checkbox" name="account4" value="4">
<button type="submit">Delete</button>
</form>
<br/><strong>You can see the checkbox values in session below...</strong>
<div id="newDiv">
</div>
<script>
$('*[type="checkbox"]').on("change", function(){
var check = 0;
if(this.checked == true) check = 1;
var value = this.value;
$.post("session.php", { box : value, check : check }, function(data, status){
if(status == "success"){
$('#newDiv').load("values.php");
}
})
})
</script>
session.php
<?
session_start();
if(isset($_POST['box'])){
//Separate session variable for each checkbox.
$checkbox = "checkBox".$_POST['box'];
$_SESSION[$checkbox] = $_POST['check'];
}
?>
values.php
<?
session_start();
print_r($_SESSION);
?>
For any queries comment down.