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
  • Snake Care
  • Uncategorized

Adopting A Stray Cat

Are you considering adopting a stray? Maybe a cute kitty has been hanging around your…
Read More

Benefits Of Acupuncture For Pets

Here at Compassionate Care Veterinary Hospital, we are happy to provide our adorable patients with…
Read More

Halloween Safety For Pets

Halloween is coming up fast! This can be a dangerous holiday for pets, so you’ll…
Read More

Soothing A Nervous Dog

October is Adopt A Dog Month! Going to a new place is a huge change…
Read More

Snakebite Awareness Day

September 19th is Snakebite Awareness Day. Here in Texas, we have 90 kinds of snakes,…
Read More

Adorable Happy Cat Quirks

September is Happy Cat Month! Kitties are always cute, but they’re particularly lovable when they’re…
Read More

Allergies In Dogs

Did you know that dogs can get allergies, just like people can? Fido can develop…
Read More

Itchy Pet Awareness Month

August is Itchy Pet Awareness Month! This was created to help spread information and awareness…
Read More

Protecting Your Dog From Porcupines

Texas is home to many different critters, including quite a few that you don’t want…
Read More
1 2 3 8