Javascript is recording if someone scrolls more than 400. If someone scrolls more than 400, I want to record this event in PHP somehow, here I will just alert it.
So, if someone scrolls more than 400, there will be an alert coming from the PHP-variable, and not JS-variable.
(Actually, I just want this function to be triggered once, and I want just to record the maximum scroll dept and INSERT that value into a database table, but a solution to my question above will be good enough).
Right now, my code is alerting "PHP: scroll> 400 just occured!" even though no scroll occured!
Can someone provide with a working Ajax solution?
This is my code in header.php:
<?php
echo '
<script type="text/javascript">
window.onscroll = function() {
var scrollLimit = 400;
if (window.scrollY >= scrollLimit) {
alert("Javascript: scroll> 400 just occured!")
}
};
</script>';
// $FromJStoPHP should trigger when window.scrollY >= scrollLimit
if (window.scrollY >= scrollLimit) {
$FromJStoPHP='PHP: scroll> 400 just occured!';
echo '<script type="text/javascript">alert("'.$FromJStoPHP.'");</script>';
}
?>
In your PHP script what is happening:
So in browser it triggers alert PHP: scroll immediately, and spam alerts Javascript: scroll every time, when scrollY > 400.
The only way to record browser scroll event on server is via sending network requests. So you should implement scroll detection logic in your js, which will be executed in browser. As one of possible solution, you can implement http endpoint on your server with PHP, which would handle scrolling event request. When scroll event is detected in browser it send http request to your server.
Here the example of javascript
Backend implementation depends on your project specifics.