Call Us! Button

Request an Appointment Button

How to use navigator.sendBeacon with PHP 7
June 17, 2022

Recently I needed to send a request on the unload of a page (save where the user left), and regular POST requests via js aren’t a very good option, due to either hanging the browser on synchronous requests, or not having a guaranteed delivery on asynchronous ones, so I stumbled upon JavaScript navigator.sendBeacon, which:
the data is transmitted asynchronously to the web server when the User Agent has an opportunity to do so, without delaying the unload or affecting the performance of the next navigation. This solves all of the problems with submission of analytics data: the data is sent reliably, it’s sent asynchronously, and it doesn’t impact the loading of the next page“.

In addition, it has great compatibility, therefore it seemed like a very good option.

navigator.sendBeacon compatibility chart
navigator.sendBeacon compatibility chart

The issue came when I tried to intercept the request in PHP by regular means (read $_POST), in which the request didn’t show at all, so upon a lot of research, I came across the solution:

<?php
$request = json_decode(file_get_contents('php://input'), true);

So, I send the request as a JSON via navigator.sendBeacon, and intercept the raw request and decode the JSON to an PHP Array.

In conclusion, to send a request on the page Unload, via jQuery, here’s the deal:

navigator.sendBeacon("/logData.php", JSON.stringify({data:data.trim()}));

Quite simple, but took me a while. Feel free to ask any questions.

The post How to use navigator.sendBeacon with PHP 7 appeared first on Nelito.

  • All
  • Cat Care
  • Dog Care
  • General Care
  • Uncategorized

National Catio Day

March 15th is National Catio Day! This is one holiday we know our feline patients…
Read More

How Do You Know If Your Dog Is Allergic to Spring?

Spring is a time of rebirth and renewal. Your lawn will be green and lush,…
Read More

Is It Better to Adopt or Buy a Dog?

Some people have strong feelings about whether it’s better to adopt or buy a dog.…
Read More

Canine Flu

Did you know that your canine companion can get the flu? In fact, there’s an…
Read More

Blepping In Cats

Have you ever spotted your cat just sitting there with her tongue sticking out? This…
Read More
Dog harness on 2 dogs

Dog Collar or Harness? – The Pros and Cons

If you enjoy walks with Fido as much as he does, ensuring he wears the…
Read More

Choosing Safe Dog Toys

December is Safe Toys and Gifts Month. This is definitely a timely topic for us.…
Read More
White mutt dog with brown right cheek and ears

National Mutt Day – December 2nd 

If you’ve been wondering when to celebrate the best day of the year, we have…
Read More

Feline Hyperesthesia Syndrome

Feline hyperesthesia syndrome—which is also called rolling skin syndrome and twitchy cat disease—is a rather…
Read More
1 2 3 8