I am trying to create a form where a client can check off their tasks that automatically saves (AJAX). When the client checks the form, the value of the task's ID is sent to the PHP page. However, if the client unchecks it, even with the exact same code, the value disappears and I don't understand why. Here is my code:
index.php
<form method="post" action="this.form.submit();" name="form1">
<div class="client-list">
<div class="checkbox-list">
<?php if(empty($clientTask['status'])): ?>
<input type="checkbox" id="task0" name="task0" onclick="function1();" value="1">
<?php else: ?>
<input type="checkbox" id="task0" name="task0" onclick="function1();" value="1" checked>
<?php endif; ?>
<label for="task0">Task 0 Name</label>
<?php if(empty($clientTask['status'])): ?>
<input type="checkbox" id="task1" name="task1" onclick="function1();" value="2">
<?php else: ?>
<input type="checkbox" id="task1" name="task1" onclick="function1();" value="2" checked>
<?php endif; ?>
<label for="task1">Task 1 Name</label>
<?php if(empty($clientTask['status'])): ?>
<input type="checkbox" id="task2" name="task2" onclick="function1();" value="3">
<?php else: ?>
<input type="checkbox" id="task2" name="task2" onclick="function1();" value="3" checked>
<?php endif; ?>
<label for="task2">Task 2 Name</label>
</div>
</div>
</form>
script.js
<script>
function function1() {
var data = $("[name='form1']").serialize()
$.ajax({
url: "client-tasks.php",
type: "POST",
async: true,
cache: false,
data: data,
success: function(data){
alert(data)
}
});
}
</script>
I tried 3 different ways to see what works and what doesn't in client-tasks.php
:
$_POST['task0']
works both ways when theid
is hard-coded.$_POST['task1']
only works in theif
statement, but the value disappears in theelse
statement. It doesn't matter if thestatus
is set to1
or0
.- The whole code with
$_POST['task2']
will work even though the$task2
is an empty string.
From what I found, the else
statement never works unless it is hard-coded. So, I need to find a way to get it working.
<?php
include("../../path.php");
include(ROOT_PATH . "/app/database/config.php");
if (isset($_POST['task0'])) {
$sql1="UPDATE client_tasks SET status = 1 WHERE id = 1";
} else {
$sql1="UPDATE client_tasks SET status = 0 WHERE id = 1";
}
$result=$conn->query($sql1);
if (isset($_POST['task1'])) {
$sql2="UPDATE client_tasks SET status = 1 WHERE id = " . $_POST['task1'] . "";
} else {
$sql2="UPDATE client_tasks SET status = 0 WHERE id = " . $_POST['task1'] . "";
}
$result=$conn->query($sql2);
$task2 = $_POST['task2'];
if (isset(task2)) {
$sql3="UPDATE client_tasks SET status = 1 WHERE id = " . $task2 . "";
} else {
$sql3="UPDATE client_tasks SET status = 0 WHERE id = '$task2'";
}
$result=$conn->query($sql3);
When it works When it doesn't work (empty string helps execute code)
I would really appreciate any help or advice, thank you!
Aucun commentaire:
Enregistrer un commentaire