I'm trying to call a PHP script via AJAX but it seems like there is a problem I don't know what it is! I tried to use other solutions but I didn't understand them well. What I really want to do is call the PHP script via the AJAX code, then update the echo in the header with the data returned. Here's what I have done so far:
Header.php
<?php session_start(); ?>
<script src="https://code.jquery.com/jquery-3.4.1.slim.js" integrity="sha256-BTlTdQO9/fascB1drekrDVkaKd9PkwBymMlHOiG+qLI=" crossorigin="anonymous"></script>
<?php require_once('db/dbconnection.php'); ?>
<?php
$result = $mysqli->query("SELECT * FROM task
INNER JOIN user ON task.user_id = user.id
WHERE username='$username' AND status = 'achieved'") or die($mysqli->error);
$count = mysqli_num_rows($result);
?>
<div class="done" data-tooltip="Achieved">
<span><?php echo $count; ?></span>
</div>
Dashboard.php
<link rel="stylesheet" href="css/dashboard.css">
<script src="https://code.jquery.com/jquery-3.4.1.slim.js" integrity="sha256-BTlTdQO9/fascB1drekrDVkaKd9PkwBymMlHOiG+qLI=" crossorigin="anonymous"></script>
<?php require_once('db/dbconnection.php'); ?>
<?php require_once("header.php"); ?>
<?php $result = $mysqli->query("SELECT * FROM `task`") or die($mysqli->error); ?>
<?php
while ($row = mysqli_fetch_array($result)):
?>
<input type="checkbox" name="checkbox[]" value="<?php echo utf8_encode($row['id']); ?>">
<p id="task"><?php echo utf8_encode($row['task']); ?></p>
<?php endwhile; ?>
<!-- js files -->
<script src="js/main.js"></script>
dashboard.css
input[type=checkbox]:checked~p {
text-decoration: line-through;
}
main.js
$(document).ready(function() {
$("input[type='checkbox']").on('change', function() {
var id = $(this).val();
if (id) {
$.ajax({
type:'POST',
url:'db/ajaxdata.php',
data:'id='+id,
success:function(html){
$(".done").html(html);
}
});
} else {
//Error msg
}
});
});
ajaxdata.php
session_start();
require_once('dbconnection.php');
if ((isset($_POST['id'])) && (!empty($_POST['id']))){
//Example
$count = 2;
echo "$count";
} else {
header("location: /error.php");
}
Sorry if I didn't explain the problem properly!