简体   繁体   中英

Jquery + Ajax is not working properly, why?

This code will show a counter when there's rows with the status = unread , and it will UPDATE the row to status = read when the user click on the a icon <i class="fas fa-bell"></i> .

The problem is: This is not working propelly, when i click on the <i class="fas fa-bell"></i> it get a delay of 3-9 seconds to update the counter to 0, it update my table instantly, only the counter that get some delay, but sometimes i need to reload the page and click on the icon to update my table, why? What's wrong?

html: <span class="text-white divCountNT" id="datacount"></span>

script:

<script>
  $(document).ready(function(){

    $("#datacount").load("select.php");

    setInterval(function(){
    $("#datacount").load('select.php')
    }, 10000);

  });

  $(document).on('click', '.fa-bell', function (){

    $.ajax({
       type: "POST",
       url: "update.php"
    });

  });
</script>

select.php:

<?php
require_once 'db.php';

if(!isset($_SESSION))session_start();

if(isset($_SESSION['user_id'])) {
  $user_id = $_SESSION['user_id'];
}

$status = 'unread';
$sql = $conn->prepare("SELECT * FROM noti WHERE status = :status AND user_id = :user_id");
$sql->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();

if($countNT >= 1){
echo $countNT;
}

?>

update.php:

<?php
require_once 'db.php';

if(!isset($_SESSION))session_start();

if(isset($_SESSION['user_id'])) {
  $user_id = $_SESSION['user_id'];
}

$status = 'read';
$sql = $conn->prepare("UPDATE noti SET status = :status WHERE user_id = :user_id");
$sql->bindParam(':user_id', $user_id, PDO::PARAM_INT);
$sql->bindParam(':status', $status, PDO::PARAM_STR);
$sql->execute();
$countNT = $sql->rowCount();

echo $countNT;

?>

You dont have a callback function for your ajax call so your table only updates itself with load function. Your ajax call should be something like that :

$.ajax({
   type: "POST",
   url: "update.php"
}).done(function() {
   window.location.reload(true);
});

You can Try with this code It's Working Fine

$.ajax({
   type: "POST",
   url: "update.php"
   success: function(result){
        $(body).find("#loadData").html(result);
       // $(body).find("#loadData").append(result); //you can also use for append data insted of replace
   }
   error: function(xhr){
        alert("An error occured: " + xhr.status + " " + xhr.statusText);
   }
});

check this for use of more methods of AJAX https://www.w3schools.com/jquery/ajax_ajax.asp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM