Jump to content

How do you write a simple Listener script?


simona6

Recommended Posts

Something I have never done, but want to learn the best practice for doing so, is a listener script.

Example: one of our websites is in bespoke PHP and has two links that shows if there are any noticeboard 'notifications' or any new 'messages'.

Ideally I'd like to show 1, 2, 3... etc as a count of how many are remaining for Messages.  So if a new one comes in while they are on a page, that number literally changes while they are on the page.

I assume this is with Ajax, and not straight forward.  I don't know any DOM code or Javascript.  But would appreciate some help please.

Simon

Link to comment
Share on other sites

You have a link that the user pushes to see the number of new messages; so it most probably is done through AJAX. A listener on that link would change anything. What I think your looking for is PUSH notifications which are way above your pay grade.

 

You could simulate push notifications with a time loop in JS to send the request every once in a while.

Link to comment
Share on other sites

Your topic is a bit misleading.  You don't need a "listener" script.    A web server is already a listener, that listens for connections.  It is also possible to utilize websockets, but then you need a websocket server, which comes with a lot of baggage and system administration setup which also complicates your environment.  For a couple of message counters, I wouldn't recommend going down that road.

You simply need a PHP script that takes some GET or POST parameters and returns the required numbers.   My "pro tip" is to return the data in a json structure, as this makes it easy to work with in your client javascript.

On the "client javascript" side, you should probably use fetch.  It's also possible to use jquery.ajax if you already are using jquery in your project, but the modern way of doing ajax calls is to use fetch, as it works with Promises.  I'm not going to regurgitate the examples but to quote from the link I provided:

Quote

The simplest use of fetch() takes one argument — the path to the resource you want to fetch — and returns a promise containing the response (a Response object).

Start with writing the script and returning the json data, based on the provided parameters.  You can utilize session variables to establish user identity just as you might in any other PHP script, or pass parameters from the client side.  Test that it returns the correct json structure (and make sure that your php script sets the http header content type to be JSON.

Once the script works for one request, you simply need your client to do some sort of "polling".  This SO question has an implementation you can look at for writing a polling routine where you can call your fetch function.  You want to carefully consider the typical number of concurrent users you might have, as well as the periodicity within which you want to call your routine.  Keep in mind that you will generate those requests so long as a user sits on the page which has these counts.  Given the overhead, you might want to combine the requests into one php script that returns both counts at the same time.    Look at the answer from allenyilee:

let cancelCallback = () => {};

var sleep = (period) => {
  return new Promise((resolve) => {
    cancelCallback = () => {
      console.log("Canceling...");
      // send cancel message...
      return resolve('Canceled');
    }
    setTimeout(() => {
      resolve("tick");
    }, period)
  })
}

var poll = (promiseFn, period, timeout) => promiseFn().then(() => {
  let asleep = async(period) => {
    let respond = await sleep(period);
    // if you need to do something as soon as sleep finished
    console.log("sleep just finished, do something...");
    return respond;
  }


  // just check if cancelCallback is empty function, 
  // if yes, set a time out to run cancelCallback()
  if (cancelCallback.toString() === "() => {}") {
    console.log("set timout to run cancelCallback()")
    setTimeout(() => {
      cancelCallback()
    }, timeout);
  }

  asleep(period).then((respond) => {
    // check if sleep canceled, if not, continue to poll
    if (respond !== 'Canceled') {
      poll(promiseFn, period);
    } else {
      console.log(respond);
    }
  })

  // do something1...
  console.log("do something1...");

})


poll(() => new Promise((resolve) => {
  console.log('Hello World!');
  resolve(); //you need resolve to jump into .then()
}), 3000, 10000);

// do something2...
console.log("do something2....")

You can run this script on the SO page and debug it, so that you are clear you understand how the pieces work.  It is a bit more complicated than need be, due to the implementation of a cancellation capability, which you might not need, however, you might want to have a feature that stops the polling requests after some reasonable period of time.  Using these routines or ones that are similar in combination with your fetch function AND whatever javascript routines you need to update the relevant count(s) links should be everything you need.  The nice thing about this example is that the console.log statements show you where your routines should be that make the fetch(ajax) request(s) you will want.

Link to comment
Share on other sites

6 hours ago, simona6 said:

Goodness me.

Well firstly apologies for the terminology I used.  I thought it was a "listener".

It does look to be extremely complicated.

Try building it out.  There's next to no complexity on the PHP/server side.  There is some complexity on the client-side if you are not experienced with javascript, and in particular ES6 javascript syntax.  With that said, any modern UI is going to have a good amount of javascript in it, so it's the price of having a functional modern web user interface.  JSON is something you need to be comfortable with as it's by far the most popular format for REST api data formatting.

As I said in my response, take it step by step:

  1. Write the php script
  2. Test it out using a browser or a tool like Postman.
  3. Validate your json response
  4. Make a client page with a button that calls your PHP script via Ajax and updates a link
  5. Add the Polling

At each step along the way, you will have learned something valuable, and figured out how to test and debug without having to put everything together perfectly on your first try.

If you are out of your depth in regards to javascript, you are not alone, but you have something you can study up on.  FreeCodeCamp is an amazing organization that provides totally free top notch educational content.  Here's a complete course on Javascript for beginners!

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.