labu77 labu77 - 3 months ago 22
Ajax Question

Update divs without reload page - jquery / ajax setInterval

A website with a notification system and private messages system use setInterval to update the relevant 2 divs without page reload.

Therefore I use:

<script>
$(document).ready(function () {
setInterval(function() {
$.get("notifi_reload.php?n=1", function (result) {
$('.notifications').html(result);
});
}, 10000);

setInterval(function() {
$.get("notifi_reload.php?n=2", function (result) {
$('.private_messages').html(result);
});
}, 10000);
});
</script>


The notifi_reload.php gives out only a number. Code:

$notifi = $_GET["n"];

// 1 = notification
if ($notifi == 1)
{

echo $user->data['user_notification_count'];

} else{

// 2 = PM
echo $user->data['user_new_privmsg'];

}


Problem:

I have every 10000 seconds 2 $.get requests. Is it anyways possible to have only 1 $.get requests? Maybe I can structure the notifi_reload.php to have both present?

Thank you

Answer

in JS

$(document).ready(function () {
    setInterval(function() {
        $.ajax({
            dataType: "json",
            url: "notifi_reload.php",
            success: function(result){
                $('.notifications').html(result.notif);
                $('.private_messages').html(result.private_msg);
            }
        });
    }, 10000);
});

and in PHP

$data = array();

$data['notif'] = $user->data['user_notification_count'];
$data['private_msg'] = $user->data['private_msg'];

echo json_encode($data);