PHP Session data lost on first reload with jquery load() - php

I'm loading content into a div with jquery's load() function and refresh that div every 15 seconds (it checks for a status).
For some reason after the first reload / refresh of the div, the session data is lost.
The exact code I'm using is very long, so a basic version of what I'm doing is this:
load.php
<?php
session_start();
$_SESSION['testvalue'] = "TESTVALUE";
?>
<div id="loaddiv"></div>
<script src="js/jquery.js"></script>
<script>
(function($)
{
$(document).ready(function()
{
$.ajaxSetup(
{
cache: false,
});
var $container = $("#loaddiv");
$container.load("load_test.php");
var refreshId = setInterval(function()
{
$container.load('load_test.php');
}, 10000);
});
})(jQuery);
</script>
load_test.php
<?php
session_start();
echo $_SESSION['testvalue'];
?>
Works fine when page loads initally and displays TESTVALUE, after the div refreshs there is no more output however.
Anyone experienced this before and knows what's going on ?
//EDIT
I'm one step further to solving this:
On the main page I'm selecting some things from my mysql db and putting this into the session, in the subpage (the one that jquery load() loads ) I am now just outputting the session values.
There's absolutely nothing on the subpage but this:
<?php
session_start();
echo $_SESSION['test_one'];
echo $_SESSION['test_two'];
?>
<?php echo session_id(); ?>
When jquery load() is triggered the second time, the values in
$_SESSION['test_one']; and $_SESSION['test_two']; change ... (It is running the mysql query again and putting something else into the session)
The values for the session get set on the mainpage, so why would refreshing the subpage run the mysql query on the main page again ?!

Related

loop through MySQL result every 1 seconds using Ajax

I have a class which gets a result from the database and the result is being looped through, and the database is being updated regularly but i dont want to keep refreshing the page because of some reasons.
//file class.php
class order {
function getOrders(){
//gets data from database
}
}
//file main.php
$ai = new order();
$orders = $ai->getOrders();
foreach($orders AS $order){
//data displayed in a table
}
I want the table to be automatically updated without page reload.
I know i have to use ajax but i have no idea what to implement that in oop
Use something like this.
$(function () {
setInterval(function () {
$("#liveTable").load("path/to/orderList");
}, 1000);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div id="liveTable"></div>
You need to use javascript and jQuery on your html page so as to reload a portion of the page.
you can add the following in your html page's head:
<script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
<script>
$(document).ready(function()
{
theIntervalHandle = setInterval(fetchNewOrders,3000);
});
function fetchNewOrders()
{
$('#ordersDiv').load('http://your.web.address/class.php');
}
</script>
and that
<div id="ordersDiv"></div>
inside your html file's body where you want the dynamic content to appear.
this assumes that the file that creates the output is called class.php and fetches data each 3 seconds as per second is quite often and can cause problems should your traffic increase beyond a few tens of users...

POST with Ajax not working - Why?

HTML
<div pid="14" class="buybutton">Buy</div>
Javascript
<script>
$(document).ready(function() {
$(".buybutton").click(function(){
console.log("Clicked Button");
var pid = $(this).attr("pid");
console.log(pid,"= Product ID");
$.post("/redirecttoproduct.php", {"pidofproduct": pid});
});
});
</script>
Console:
Clicked Button
14 = Product ID
redirecttoproduct.php
<?php
session_start();
$_SESSION['redirectproductpid'] = $_POST['pidofproduct'];
?>
Trying to echo SESSION, nothing shows up
<?php
$productpid = $_SESSION['redirectproductpid'];
echo $productpid;
?>
Nothing shows up - Any ideas?
Did you missed the session_start(); in this page? session_start() is necessary when you use $_SESSION.
<?php
session_start();
$productpid = $_SESSION['redirectproductpid'];
echo $productpid;
?>
I suggest do a callback function first to check if the post request is successfully submitted, one of the reason your $_SESSION variable doesn't return any value is because your js code doesn't post any values to it at all, in result no data is being assigned to your $_SESSION var, ie:
$.post("/redirecttoproduct.php", {"pidofproduct": pid})
.done(function() {alert( "success" );})
.fail(function() {alert( "error" );});
And it would be more convenient if you could supply an absolute path to your $.post request like your website's dir url ie: $.post("//yourwebsite.com/redirecttoproduct.php") with this relative path errors can be significantly avoided, and make sure your not submitting invalid values that would not pass your XSS filters (if there are any), hope this helps, cheers!

Best way to refresh multiple PHP values every x seconds?

I have an index.php file that I would like to run getdata.php every 5 seconds.
getdata.php returns multiple variables that need to be displayed in various places in index.php.
I've been trying to use the jQuery .load() function with no luck.
It's refreshing the 12 <div> elements in various places on the index.php, but it's not re-running the getdata.php file that should get the newest data.
But If I hit the browser refresh button, the data is refreshed.
getdata.php returns about 15 variables.
Here is some sample code:
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php'); // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow");
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Here's an example of GetData.php:
$query = "SELECT column1, COUNT(column2) AS variable FROM table GROUP BY column";
$result = mysql_query($query) or die(mysql_error());
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 '];
$variable = $row['variable '];
if($column1 == "Text1") { $variable1 = $variable; }
elseif($column1 == "Text2") { $variable2 = $variable; }
... continues to variable 15 ...
}
Then further down the page the HTML elements display the data:
<div id="Hidden_Data"></div>
<div id="Show_Data_001"><?php echo $variable1; ?></div>
<div id="Show_Data_002"><?php echo $variable2; ?></div>
<div id="Show_Data_003"><?php echo $variable3; ?></div>
...
I tried using the data parameter as suggested here:
https://stackoverflow.com/a/8480059/498596
But I couldn't fully understand how to load all the variables every 5 seconds and call them on the index page.
Today the GetData.php page just returns $variable1 = X; $variable2 = Y and so on.
UPDATE
For some reason the jQuery is not loading the GatData.php file and refreshing the variables.
I tried adding to "Hidden_Data" to the include('GetData.php') and then the variables are readable on the page.
If I remove this part, the page displays "variable not set" warning that suggesting that the jQuery is not loading the GetData.php script into the Hidden_Data <div>.
Try
<script>
var refreshId = setInterval(function()
{
$('#Hidden_Data').load('GetData.php', function() { // Shouldn´t this return $variables
$('#Show_Data_001').fadeOut("slow").fadeIn("slow");
$('#Show_Data_002').fadeOut("slow").fadeIn("slow");
$('#Show_Data_003').fadeOut("slow").fadeIn("slow");
$('#...').fadeOut("slow").fadeIn("slow"); });
}, 5000); // Data refreshed every 5 seconds
*/
</script>
Above is assuming, that your code returns snippet of HTML elements (Show_Data_XXX), but now that you've clarified your question above wont help you alone...
What you need to do is either in your php send back new value elements or send back your results as data and update existing elements.
Put your elements into a php Array and then send it back
data.php after sql call
$results = Array();
while($row = mysql_fetch_array($result)){
$column1 = $row['column1 ']; // change Text1 in db to Show_Data_001 in html or vice versa
$variable = $row['variable '];
$results[$column1] = $variable;
}
echo json_encode($results);
in your javascript something like this...
$.getJSON('GetData.php',function(data) {
$.each(data, function(key, val) {
$('#'+key).text(val);
});
});
I didn't put the fadeOut and fadeIn into the example, because it complicates it a bit. You could do fadeOut to all those elements before calling getJSON and the fadeIn as the results pouring in. Hope this helps
First of all, make sure you have correct respond from server, just like this:
//We won't use load() to load content for now
window.setInterval(function(){
$.ajax({
url : "path_to_your_php_script.php",
type : "GET",
beforeSend: function(){
//here you can display, smth like "Please wait" in some div
},
error : function(msg){
//You would know if an error occurs
alert(msg);
},
success : function(respondFromPHP){
//Are you getting distinct results every 5 sec?
alert(respondFromPHP);
return;
//if respondFromPHP contains data you want
//ONLY THEN, add some effects
}
});
}, 5000);
The only difference between this approach and yours, is that, you can handle errors and make sure you are getting data you want.
Can you show me the code of GetData.php?
Rather than using Jquery.load you can actually get the page with $.post or $.get and format your results from GetData.php to Json or xml you can easily map it to your javascript.
Using $.post it will allow you to have a callback after getting the value from GetData.php and you can check it if it's working right or not. If it gets a data from your GetData.php then you can populate it to your DIV elements.
You can check more information regarding POST and GET here:
http://api.jquery.com/jQuery.post/

AJAX pagination solution for PHP

Right now I use a pagination system that requires url like
http://mypage.com/index.php?page=1
http://mypage.com/index.php?page=2
http://mypage.com/index.php?page=3
http://mypage.com/index.php?page=4
etc...
So it uses $_GET method to find out what page the user is on.
I decided to switch most of my website to ajax and came over a problem. When I use Ajax to load new content on a page the url stays the same all the time e.g. http://mypage.com/index.php . Therefore pagination system I use is useless.
I was not able to find efficient AJAX pagination systems, (e.g some where lagy, most required user to scrol to the tiop each time he / she clicked on a next page, because they stayed at the bottom of the page when they clicked next page. etc...)
So I decided to ask you lot if anyone has an efficient pagination solution that works with ajax.
Example of what needs to be paginated:
$sql = mysql_query("SELECT * FROM myMembers WHERE username='$username' LIMIT 1") or die (mysql_error("There was an error in connection"));
//Gather profile information
while($row = mysql_fetch_assoc($sql)){
$username = $row["username"];
$id = $row["id"];
$data_display .= '<b>'.Name.'</b> has an id of <span style="color: f0f0f0;">'.$id.'</span>';
}
<!doctype>
<html>
<?php echo "$data_display"; ?> //and I need to paginate this entries
</html>
jQuery that loads new content from different pages into #content div
<script type="text/javascript">
function viewHome(){
$('#woodheader').load("inc/home_top.php", function () {
$(this).hide().fadeIn(700)
});
$('#content').html('<span class="loader">Loading.. <img class="loaderimg" src="images/ajax_loader.gif"/></span>').load("inc/home.php", function () {
$(this).hide().fadeIn(700)
});
}
function viewAbout(){
$('#woodheader').load("inc/about_top.php", function () {
$(this).hide().fadeIn(700)
});
$('#content').html('<span class="loader">Loading.. <img class="loaderimg" src="images/ajax_loader.gif"/></span>').load("inc/about.php", function () {
$(this).hide().fadeIn(700)
});
}
function viewProducts(){
$('#woodheader').load("inc/products_top.php", function () {
$(this).hide().fadeIn(700)
});
$('#content').html('<span class="loader">Loading.. <img class="loaderimg" src="images/ajax_loader.gif"/></span>').load("inc/products.php", function () {
$(this).hide().fadeIn(700)
});
}
</script>
Pagination is not as hard as you can think, you can use jQuery's load() function to load content into an element with the page's content.
So for example you have:
<div id="page-content"></div>
Page 1
Page 1
Page 3
<script>
$.ready(function(){
var currPage = <?=$pageNumber; ?>; // The page number loaded on page refresh
$('#link1,#link2,#link3').onclick(function(){
// Get the first number inside the id
var pageNum = parseInt($(this).attr('id'));
// Don't load the same page
if(currPage == pageNum) return;
// Show loading animation or whatever
// Load the page using ajax
$('#page-content').load('pages.php?page='+pageNum, function(){
// End loading animation
currPage = pageNum;
});
return false; // Important for not scrolling up
});
});
</script>
Regarding the url, you have three options to choose from when a user clicks a page link:
Just load the page with no changing of the url
Use the HTML5 history.pushState(see MDN resource) if supported and with option 3 as fallback for unsupported browsers
Use #page1, #page1 etc. as the href value of the links so that the user knows on what page they are on and parse the value of the url in php:
$uri = explode('#page', $_SERVER['REQUEST_URI']);
$pageNumber = intval($uri[1]);
I would create a index.php that doesn't load any $data_display initially.
Internally in javascript I would keep a variable named $page that would initially equals 1.
After load it would make a ajax call to names.php?page=$page and pass the results to a handler that presents it to the user.
Then on the links to "back" and "next" I would put a javascript function that first sets $page to the previous or next number, then calls names.php?page=$page and pass the results to the same handler.

Jquery with PHP problem

Let me post the code first.
function alertCallback<?=$position_info['id']?>()
{
var id = <?=$position_info['id']?>;
var itemname= '<?=$na?>';
<?PHP if($position_info['name'] == $wposition){ ?>
var reward = '<?= $itmname ?>';
$('#selected_item').html(''+itemname+reward);
<?PHP item_add($_SESSION['userid'],$itmid,1); } else { ?>
var noreward = 'You Found Nothing!';
$('#selected_item').html(''+itemname+noreward);
<?PHP } ?>
}
The above is working to an extent. The page is a image map where if you click on the right spot then you get an item. It is currently working where if you click on the right spot you get the item. Or get told you found nothing.
The problem I have is that the page reloads to set new positions
<script type="text/javascript">
//one seconds=1000 micro seconds
setInterval(function() {
$('#load').load('itemclick_ajax.php');
},60000);
</script>
but another item is won as long as the page is displayed. Any ideas on how to stop this occuring. If i keep the browser showing the page then im running up to thousands of items won.
Are you trying to stop the page reload?
Try adding "return false;" at the end of your Javascript function.

Categories