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

Esse post foi escrito pelo ChatGPT. Descubra como ele funciona!

O ChatGPT é uma ferramenta de conversação desenvolvida pela OpenAI que permite aos usuários conversar…
Read More

How to use navigator.sendBeacon with PHP 7

Recently I needed to send a request on the unload of a page (save where…
Read More

How to add hover to images in Duda.co

Duda does not provide a widget to do this natively, but it can be achieved…
Read More

How to host email on Duda.co

Duda does not provide email hosting services, so you can’t host email on Duda directly.…
Read More

Our Lazy Feline Friends

Fluffy’s favorite holiday is just around the corner: National Lazy Day is August 10th! Granted,…
Read More

Keeping Kitty Hydrated

Summer is in full swing now. Staying hydrated is extremely important at this time of…
Read More

Keeping Fluffy Fit

Cats are very active when they are young. It’s always adorable seeing a frisky kitten…
Read More

Pool Safety for Dogs

Does your dog like swimming? Our canine companions are rather divided on this topic. Just…
Read More

Reasons to Hug Your Cat

Is your feline pal a cuddlebug? If so, you may want to make a note…
Read More
1 2 3 4