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

Feline Hyperesthesia Syndrome

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

Early Signs Of Hip Dysplasia

Did you know that hip dysplasia is the most common orthopedic issue we see in…
Read More

Cognitive Decline in Senior Cats

Did you know that, just like people, cats can experience a decline in cognitive abilities…
Read More

Poodle Day

Today, October 1st, is Poodle Day! These iconic dogs have very unique appearances, and make…
Read More

Unusual Cat Eating Habits

Cats are mysterious creatures. We all know that, but did you know that their eating…
Read More

Celebrating Scooby Doo

Ruh Roh! September 13th is Scooby Doo Day! The beloved cartoon dog has become a…
Read More

5 Things To Do For Holistic Pet Day

Holistic Pet Day is August 30th! There is a growing awareness of the benefits of…
Read More

Cat Care Tips for the Summer Heat

The summer is heating up, and so are our pets. But how do cats keep…
Read More

Caring For A Super Senior Pet

Is your pet entering—or already into—their golden years? Pets age the way many people do…slowly…
Read More
1 2 3 7