0

My notification sender is working perfectly. I can see the notification when I refreshed the page, without the AJAX.

I want to implement AJAX to refresh the content automatically when there is new notification is incoming for the user.


Example for what I am trying to achieve:

user A sent a friend request to user B, so user B gets a notification, but the notification is only showing after the page is refreshed. I want to refresh the notification automatically, whenever the database is updated/inserted a new value.


$(document).ready(function(){
$.ajax({
    type: 'POST',
    url:  '../main/count-fnd.php',
    success: function(data){
        $('#output').html(data);
    }
 });
});

The problems that I have had with AJAX reload:

  • The Ajax refresh won't stop refreshing

  • If I put a button next to the <div id='output'></div> (not inside of the div tag) tag, the button won't stop refreshing with the div element itself.

Code for fetching the notification:

$query = "SELECT * FROM notrequests WHERE userTo = '$userName'  AND counter != '0'";

$result = $conn->query($query);

if ($result->num_rows > 0) {
 while($row = $result->fetch_assoc()) {
   $totalRequestNot = $row["counter"];
 }
}
Chris_00
  • 406
  • 6
  • 17
  • can you post the html sample for this issue? – Nikola Kirincic Mar 31 '19 at 09:21
  • for real-time notifications, SignalR, socket programming to get the notification. second, if you really want to use Ajax, then you should periodically ping the API, get the latest result and show them but this will increase the unnecessary load on your server. follow this SO question https://stackoverflow.com/questions/35473356/is-there-any-javascript-tcp-soket-library-for-php-like-signalr-with-net – Khizar Iqbal Mar 31 '19 at 09:30
  • @Chris_00, sample from php doesn't output anything, it just shows how is fetching the counter value for given user. You must provide full sample in php with output for `data` used in ajax response. Also, sample in html where you append your response from ajax request. – Nikola Kirincic Mar 31 '19 at 09:43
  • you are looking for websockets or ajax polling. – Shoyeb Sheikh Mar 31 '19 at 14:00
  • @ShoyebSheikh which one would be better for this task? – Chris_00 Mar 31 '19 at 20:07
  • 1
    @Chris_00 you will get an idea from https://stackoverflow.com/questions/10028770/in-what-situations-would-ajax-long-short-polling-be-preferred-over-html5-websock – Shoyeb Sheikh Apr 01 '19 at 02:12

0 Answers0