So I’m working on a To Do App and I used Ajax to send data to PHP when a task is clicked to be marked as completed. PHP then sends an SQL query to MySQL and changes the value in the completed column from 1 to 0 or visa vera. Originally, I tried to send a PHP header to go back to that page but it didn’t work so after the request was sent I wrote some JavaScript code to refresh the page and the task is now marked as completed and I have a css style for that. I was wondering, I thought the purpose of Ajax was to not have to reload the whole page so idk if I’m using Ajax wrong and there is a better way to do this? The project works but I just want some feedback on my code I guess.
main.js:
for(i=0; i < div.length; i++){
div[i].addEventListener("click", function(e){
let xhr = new XMLHttpRequest();
xhr.open('POST', 'process_complete.php', true);
xhr.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
let task_num = e.target.getAttribute("id");
xhr.onreadystatechange = function(){
if(xhr.readyState === 4 && xhr.status === 200){
location.reload();
}
}
xhr.send(JSON.stringify(task_num));
});
}
process_complete.php:
if(isset($_SERVER['HTTP_X_REQUESTED_WITH'])){
$data = file_get_contents('php://input');
$id = json_decode($data);
$sql = mysqli_query($conn, "SELECT * FROM tasks WHERE Num = '$id'");
if($sql === false){
printf("error: %s\n", mysqli_error($conn));
}
while($row = mysqli_fetch_row($sql)){
if($row[3] === "1") {
$mysqli_update = mysqli_query($conn, "UPDATE tasks SET Completed = 0 WHERE Num = '$id';");
} else {
$mysqli_update = mysqli_query($conn, "UPDATE tasks SET Completed = 1 WHERE Num = '$id';");
}
}
}