HTML5 Notification With PHP HTML5 Notification With PHP php php

HTML5 Notification With PHP


Your problem is the lack of AJAX to connect Javascript and PHP. The way your PHP script works is by manually running the script, so only the device hitting that script will see the notification. There is nothing that actually sends that info to your other device right now.

To better explain the problem, your desktop may have allowed access to the notifications, but it doesn't automatically pull in those notifications. The code you have provided will need to use AJAX to hit the script URL, instead of using it as a cron job.

First off, you need to start a repeating request to the PHP script to see if there has been any updated notification. If there is a new notification, then you need to create a new notification object using the returned response.

Second, you need to alter the PHP script to output a JSON string rather instead of the notification script.

JSON output example:

{  {    title: 'new blog!',    options: {      body: 'come read my new blog!',      icon: 'same icon as before or maybe a new one!'    }  },  {    title: 'another blog item!',    options: {      body: 'come read my second blog!',      icon: 'hooray for icons!'    }  }}

Your notifyUsers() should take title and option as arguments instead of hardcoding them:

function notifyUser(title, options) { ... }

Using jQuery, get the PHP response and create the notification:

function checkNotifications(){  $.get( "/path/to/script.php", function( data ) {    // data is the returned response, let's parse the JSON string    json = JSON.parse(data);    // check if any items were returned    if(!$.isEmptyObject(json)){      // send each item to the notify function      for(var i in json){        notifyUser(json[i].title, json[i].options);      }    }  });  setTimeout(checkNotifications, 60000); // call once per minute}

Now, you just need to kickstart the AJAX polling, so add this to your webpage:

$(document).ready(checkNotifications);

That's pretty much it! You were just missing the part when your desktop needed to pull in the notifications. Heads up though, this isn't tested and you may need to tweek something.