Reputation: 1228
I am sending post
data to a page that runs a MySql
statement then returns via a page redirect
header("location: {$_SERVER['HTTP-REFERER']}");
I am trying to use Ajax
to send the $(window).scrollTop()
value as a $_GET['scroll_pos']
variable like so:
<?php session_start(); ?>
$(document).ready(function(){
// SET SCROLL SESSION VARIABLE
$(window).scroll(function(){
var xmlhttp;
if( window.XMLHttpRequest ){
xmlhttp = new XMLHttpRequest();
} else {
xmlhttp = new ActiveXObject( 'Microsoft.XMLHTTP' );
}
xmlhttp.open('GET', 'script_files/set_scroll_session.php?scroll_pos=' +
$(window).scrollTop(), true);
xmlhttp.send();
});
// SCROLL TO $_SESSION['scroll_pos'];
$(window).scrollTop(<?php echo json_encode($_SESSION['scroll_pos']); ?>); // <-- THIS IS NOT FIRING
});
The set_scroll_session.php
page saves the $_GET['scroll_pos']
as a $_SESSION['scroll_pos']
variable like so
<?php
session_start();
// VARIABLES
$scroll_pos = $_GET['scroll_pos'];
$_SESSION['scroll_pos'] = $scroll_pos;
?>
which needs to be called as seen in the above $(document).ready()
function.
The window is not scrolling to amount specified in the $_SESSION['scroll_pos']
variable, how come?
Upvotes: 1
Views: 622
Reputation: 3763
First, you are already using jquery so I would highly recommend (however, it's not necessary) that you use jquerys built in AJAX method.
https://api.jquery.com/jQuery.ajax/
And the reason it's not working is because you can't echo
out a value to be used in javascript like that, you must use AJAX to fetch that value, then set the scroll position.
//WILL NOT WORK!!!!
$(window).scrollTop(<?php echo json_encode($_SESSION['scroll_pos']); ?>);
Or better yet, save the scroll position in a cookie or local storage to avoid an unnecessary call to the server...
Upvotes: 1