Session variable not updating after AJAX call - php

I'm a tad stumped here. I have 2 php pages. One displays the template essentially, and on click, an AJAX call calls an external page and displays all the necessary information. My problem is my session variable isn't updating. I'm using some pagination and the numbers aren't updating. Some code on my template page:
Redndering pagination
session_start();
$pagination .= $_SESSION['position'] == "" ? '' : 'Items '.$_SESSION['position'].'-'.$_SESSION['item_per_page'].' of '.$get_total_rows ;
if($pages > 1)
{
$pagination .= '<ul class="paginate nav nav-pills">';
for($i = 1; $i<=$pages; $i++)
{
$pagination .= '<li>'.$i.'</li>';
}
$pagination .= '</ul>';
}
<?php echo $pagination; ?>
<div id="results">
<!-- Results from query will go in here -->
</div>
j$(".paginate_click").click(function (e) {
j$("#results").prepend('<div class="loading-indication"><img src="/assets/loader.gif" /></div>');
var clicked_id = j$(this).attr("id").split("-"); //ID of clicked element, split() to get page number.
var page_num = parseInt(clicked_id[0]); //clicked_id[0] holds the page number we need
j$('.paginate_click').removeClass('active'); //remove any active class
//post page number and load returned data into result element
//notice (page_num-1), subtract 1 to get actual starting point
j$("#results").load("development_fetch.php", {'page': (page_num-1)}, function(){
});
j$(this).addClass('active'); //add active class to currently clicked element
return false; //prevent going to herf link
});
in development_fetch.php:
session_start();
$page_number = filter_var($_POST["page"], FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
$position = ($page_number * $item_per_page);
$_SESSION['position'] = $position;
$_SESSION['item_per_page'] = $item_per_page;
//Grab code to display inside template blah.
If you click on page 1 in the pagination, it should result in:
Items 0 - 100 of 1000
If I click page 2, it should be:
Items 100 - 200 of 1000
but instead it just stays at:
Items 0 - 100 of 1000
0 is the $_SESSION['position']
100 is the $_SESSION['item_per_page']
I don't understand why it isn't updating. Please help stackers!

i already solved mine. the issue i'm having is that, when i'm doing the ajax, the session variable is not updating in realtime. what i did, is that, i just turned the ajax asynchronous to false, since when you are doing the asynchronous, the value being cache is not the updated value since it is in asynchronous mode. if you are using jquery, just do this:
$.ajax({
type: 'POST',
url: 'url',
data: 'the datas',
success: function() {},
async: false
});

Put session_start(); at the begining of the page loaded with AJAX.

i think i found it, in your development_fetch.php
$position = ($page_number * $item_per_page);
okay, $page_number has a value, but what about $item_per_page ? i guess its zero, and the result of multiplication of course is zero. Then you set those zeroes on the $_SESSION
solution:
set your $item_per_page
session_start();
$item_per_page = 20;
// ...rest of code

i also got this issue, but mine was acting weird. it seems that the session was not fast enough to catch with the ajax.. is this problem already resolved?

Related

Pass PHP variables without using href in Bootstrap tabs

I'm trying to send PHP variables using the <a> tag and the data attribute on the same PHP page using the Bootstrap tabs:
HTML (Bootstrap tab option):
<a style='padding:20px;' href='#tab_e' data-page='$page' class='passrss' data-rssid='$rssid' data-toggle='tab'>Test</a>
PHP (stored in #tab_e tab):
$rsspassedid = GET $rssid from the a tag (data-rssid)
I'd like to get the value stored in data-rssid on click and pass it to a variable further down in the same PHP file so that when the tab is opened using #tab_e, the mySQL statement will run based on the value provided in $rssid and display the results of the query. I'm not sure if any jQuery/AJAX would be required for this but is it possible to get data stored in the data attribute of the <a> tag in PHP?
UPDATE
I've tried storing the variables in the pagination links but still no luck, here's the XHR object I created:
<script>
$(document).ready(function () {
$('.passrss').click(function () {
$('span.pass-tabe').load('tabe.php?rssid=' + $(this).data('rssid') + '&page=' + $(this).data('page'));
});
});
</script>
Tabe passes the variables stored in the a tag to a seperate php file (tabe.php) which then loads into the browser using <span class="pass-tabe"></span>, as for pagination - the links are stored in the tabe.php file but they refer back to the main php file hence pagination fails to work e.g.
originalphpfile.php?page=$page&rssid=$rssidpassed&pageurl=$x#tab_e
NOTE: $rssidpassed is stored in tabe.php which it gets from the XHR object e.g.
$_GET['rssid']
UPDATE 2
I've added the code for pagination below where I'm having the issue at the moment which is stored in tabe.php:
$perpage = 10;
$pageurl = (isset($_GET['pageurl'])) ? (int)$_GET['pageurl'] : 1;
$start = ($pageurl - 1) * $perpage;
$pagequery = mysql_query("SELECT COUNT('topic_id') FROM topic WHERE cat_id='$page' AND topic.users_id = '$rssid'");
$pagination = ceil(mysql_result($pagequery, 0) / $perpage);
//query goes here
//pagination numbers
if($pagination >= 1){
echo "<div style='text-align:center;'><ul class='pagination'>";
for($x=1; $x<=$pagination; $x++){
echo ($x == $pageurl) ? "<li class='active'><a href='originalphpfile.php?page=$page&pageurl=$x#tab_e'>$x</a></li>":"<li><a href='originalphpfile.php?page=$page&pageurl=$x#tab_e'>$x</a></li>";
}
echo "</ul></div>";
}
When I click on pagination links, it doesn't load the second, third, etc set of results as it returns to the originalphpfile.php
Is there any work around for this?
I'm going to go ahead and turn this into an answer because our comment blocks are getting long.
In your PHP template, to turn PHP into something useful you're going to need to do something like this:
// file1.php
// notice <?= ?> is quick echo, the same as <? echo $rssid; ?>
<a style='padding:20px;' href='#tab_e' data-rssid='<?= $rssid ?>' data-toggle='tab'>Test</a>
In your javascript, the reason you're getting $rssid is because you're not echoing the value, I think, according to the post.
// file2.php
$page = array_key_exists($_GET,'page') && is_numeric( $_GET['page'] ) ? $_GET['page'] : 1
// do query i.e select * from x offset $page * $per_page limit $per_page
// do stuff with your pagination in a loop defining an index $number
<a class="pagination" onclick="getPage(<?= $number ?>)"><?= $number; ?></a>
Then in jquery:
// Call this when they click the tab
var id;
function setId(id){
id = id;
getPage(1);
}
// call this when they click the pagination
function getPage(number){
$('span.pass-tabe').load('tabe.php?rssid=' + $id + '&page=' +number )
}
Please massage the example code, it seems as if you're doing something complex and it's hard to necessarily grasp your exact use case precisely.
Issue resolved, I echoed out the AJAX into the tabe php file and changed the pagination HTML links:
tabe.php pagination link:
<a href='#tab_e' class='passrssurl' data-rssid='$rsspassedid' data-url='$x' data-page='$page' data-toggle='tab'>
tabe.php echo AJAX:
echo "<script>
$(document).ready(function () {
$('.passrssurl').click(function () {
$('span.pass-tabe').load('tabe.php?rssid=' + $(this).data('rssid') + '&page=' + $(this).data('page') + '&pageurl=' + $(this).data('url'));
});
});
</script>";

Hot to get all the images to display without reloading the page in PHP?

After User Clicks Sumbit Button Data passes through one half of the path to images and then the code below links it to the second half. I want to know how I can display all this without Page Reload? I know it might be done with AJAX but I have no idea on how to do so. So please can someone help?
<?php
$albumnamepath = $_POST['field'];
echo $albumnamepath;
$display = "SELECT * FROM paths WHERE user_id = '$session_user_id' AND album_name = '$albumnamepath'";
$result = mysql_query($display);
echo "<table>";
$i = 0;
while ( $row = mysql_fetch_array($result) ) {
if ($i % 4 == 0) { //3 == 0.
echo '<tr>';
}
echo "<td>".'
<ul class="img-list">
<li><div class="picbox"><img src="'.$albumnamepath.$row['thumbnail'].'"><span class="text-content"><span>'.$row['caption'].'</span></span>'."</li>
</ul>
</td>";
//echo '<a href="'.$albumnamepath.$row['location'].'" class="swipebox" title="'.$row['caption'].'"><img src="'.$albumnamepath.$row['thumbnail'].'">';
if ($i % 4 == 3) { //3 == 2.
echo '</tr>';
}
$i++;
}
//Here is a check in case there is not a multiple of 3 images in a row.
if ($i % 4 != 0) { //4 != 0.
echo '</tr>';
}
echo "</table>";
?>
Thank you.
I don't think Ajax would help you very much, since you'll be using ajax to get, essentially, the entire page. Ajax is usually used if you want to change a part of the page, and the data either has to come from the server real-time (i.e. after the page is loaded), or is expensive to calculate or deliver in full (e.g. a very long, or infinite list, and if most users only use a small amount). Otherwise, it's more efficient to send all the data in one go, and then manipulate it in the browser.
I would suggest the following approach: divide the table rows into groups of table rows; e.g. 5 rows (chosen arbitrarily). Change the block of code where you echo '' to:
if ($i % 4 == 0) { //3 == 0.
$block=ceil($i/(4*5));
echo '<tr class="block_$block">';
}
This means each block of 5 rows (by 4 across) will be a different class - "block_1", "block_2" and so forth.
Then, you can hide and display blocks using Javascript. To hide a block, use the following javascript code:
var trToHide = document.getElementsByClassName("block_1");
for(var i = 0; i < trToHide.length; i++) {
trToHide[i].style.display="none";
}
To unhide a block:
var trToHide = document.getElementsByClassName("block_3");
for(var i = 0; i < trToHide.length; i++) {
trToHide[i].style.display="block";
}
Obviously, you will want to use variables to keep track of which block is displayed; then you can have a "Next" and "Back" button, which hides the current block, adds/subtracts one, then displays the (new) current block. You will also want to have all blocks except the first one hidden at the start. Left as an exercise to the reader.
Answer:
You have to use ajax request.
You use form to set filters? Then you can use .ajaxSumbit (but you need jQuery Form Plugin for it).
Also, you can add form submit handler, where you will prevent form default submit action and send ajax request instead of it. Look this example:
File getImages.php:
// in this file you will do same actions as you do now to output table with images
Note, that getImages.php must contain only table with results or message, that there are no results.
File with form, where you set filters:
// some html with forms etc
<form id='myForm'>
// some inputs etc
</form>
<div id='results'></div>
And javascript:
$("#myForm").submit(function(e) { // use e parameter for preventDefault();
$.ajax({
type: "POST",
url: "path/to/getImages.php",
data: $("#myForm").serialize(), // serializes the form's elements.
success: function(data)
{
$("#results").html(data);
}
});
return false; // <-- deny sumitting from and reloading page
//e.preventDefault(); // <-- this do same as `return false;` <-- deny sumitting from and reloading page
});
Explanation:
Browser load page with form, where you can set filters. User sets filters and pressing button submit. Browser will send ajax request to file getImages.php with some parameters (filters, user set filter before sending the form). This script generates some output with table, with img tags etc and return it. Browser receives this output and puts it to element with id #results:
<div id='results'></div>
^
------------------^
Data, generated by script getImages.php will be inserted here.
So, filtered images will be received and shown without page reload :)
Is it what you need?
Hope this will help you.

Updating PHP session variable using jQuery Ajax

I know this question has been answered multiple times but I haven't been able to find one specifically to solve my problem.
I'm making a website where a user can sell their eBay items, using the eBay API (which is a bit of a pain!). My problem is at the results' pagination: I need a way of updating a $_SESSION page number variable so that the page reloads and displays a different page of results. I'm doing this with AJAX, and it's my first time using it.
The process is the following:
1)User clicks on one of the pagination links on the bottom of the page (like what's at the bottom of your Google results), which I made into a form with a hidden field storing the next page number that updates accordingly when the user clicks.
2)Use AJAX to update said $_SESSION variable on an external page (without refreshing!)
3)Reload the page and display the appropriate page of results.
The problem seems to be between steps #2 and 3. The bits of code I use:
Set $_SESSION variable
<?php
session_start();
if(!isset($_SESSION['pageNumber']))
{
$_SESSION['pageNumber'] = "1";
echo("Session value NOT set, pageNumber = " . $_SESSION['pageNumber']);
}
else
{
echo("Session value SET, pageNumber = " . $_SESSION['pageNumber']);
}
?>
Pagination
<form action="">
<div id="pagination" style="text-align:center; <?php if($totalPages == 1) echo('display:none;');?>">
<?php
global $totalPages;
if(intval($_SESSION['pageNumber']) != 1)
{
print("Previous Page");
}
for($i = 1; $i <= $totalPages; $i++)
{
print("$i");
print(" ");
}
if(intval($_SESSION['pageNumber']) != $totalPages)
{
print("Next Page");
}
?>
</div>
<input type="hidden" name="nextPageNumber" id="nextPageNumber" value="<?php echo($_SESSION['pageNumber']);?>">
</form>
Update Hidden Field and $_SESSION Value
function updatePageNumber(newNumber)
{
//Update hidden field
if(newNumber == -1)
{
var num = document.getElementById('nextPageNumber').value;
num--;
document.getElementById('nextPageNumber').value = num;
}
else if(newNumber == 0)
{
var num = document.getElementById('nextPageNumber').value;
num++;
document.getElementById('nextPageNumber').value = num;
}
else
{
document.getElementById('nextPageNumber').value = newNumber;
}
//Update $_SESSION value with AJAX
var dataString = 'nextPageNumber='+ document.getElementById('nextPageNumber').value;
$.ajax(
{
url: "scripts/updatePageNumber.php",
type: "POST",
data: dataString,
dataType: "text",
success: function(text)
{
alert("Done! Response: " + text);
}
});
And the PHP file
<?php
if (isset($_POST['nextPageNumber']))
{
session_start();
die("Made it this far!");
$nextPageNumber = $_POST['nextPageNumber'];
$_SESSION['pageNumber'] = $nextPageNumber;
echo $nextPageNumber;
}
?>
Note: I don't get to the PHP file's die() method, nor the alert with the AJAX's success (by the way, is that how to properly get the response text?)
I'd greatly appreciate any help at all, I've been stuck at this for quite a long time now!
Your ajax call doesnt have nextPageNumber in its data, so it isn't seen by your PHP script (not in $_POST array) your test for it fails.
(As a general comment, your question involves too many working parts that makes it not a good fit for a site like this, devoted to helping others with similar problems. Next time please isolate the very part of the code that is causing the problem. This is likely why you have no other answers yet - people are sick of getting downvoted when trying to help solve something so comprehensive.)

Javascript pagination (next project / previous project) with jQuery?

I recently came upon a site that has done exactly what I want as far as pagination goes. I have the same basic setup as the site I just found.
I would like to have prev and next links to navigate through my portfolio. Each project would be in a separate file (1.php, 2.php, 3.php, etc.) For example, if I am on the 1.php page and I click "next project" it will take me to 2.php.
The site I am referencing to accomplishes this with javascript. I don't think it's jQuery:
function nextPg(step) {
var str = window.location.href;
if(pNum = str.match(/(\d+)\.php/i)){
pNum = pNum[1] * 1 + step+'';
if ((pNum<1) || (pNum > 20)) { pNum = 1; }
pNum = "".substr(0, 4-pNum.length)+pNum;
window.location = str.replace(/\d+\.php/i, pNum+'.php');
}
}
And then the HTML:
Next Project
I can't really decipher the code above, but I assume the script detects what page you are on and the injects a number into the next page link that is one higher than the current page.
I suppose I could copy this code but it seems like it's not the best solution. Is there a way to do this with php(for people with javascript turned off)? And if not, can this script be converted for use with jQuery?
Also, if it can be done with php, can it be done without dirty URLs?
For example, http://www.example.com/index.php?next=31
I would like to retain link-ability.
I have searched on stackoverflow on this topic. There are many questions about pagination within a page, but none about navigating to another page that I could find.
From your question you know how many pages there are going to be. From this I mean that the content for the pages themselves are hardcoded, and not dynamically loaded from a database.
If this is the approach you're going to take you can take the same course in your javascript: set an array up with the filenames that you will be requesting, and then attach event handlers to your prev/next buttons to cycle through the array. You will also need to keep track of the 'current' page, and check that incrementing/decrementing the current page will not take you out of the bounds of your page array.
My solution below does the loading of the next page via AJAX, and does not change the actual location of the browser. This seems like a better approach to me, but your situation may be different. If so, you can just replace the related AJAX calls with window.location = pages[curPage] statements.
jQuery: (untested)
$(function() {
var pages = [
'1.php',
'2.php',
'3.php'
];
var curPage = 0;
$('.next').bind('click', function() {
curPage++;
if(curPage > pages.length)
curPage = 0;
$.ajax({
url: pages[curPage],
success: function(html) {
$('#pageContentContainer').html(html);
}
});
});
$('.prev').bind('click', function() {
curPage--;
if(curPage < 0)
curPage = (pages.length -1);
$.ajax({
url: pages[curPage],
success: function(html) {
$('#pageContentContainer').html(html);
}
});
});
});
HTML:
<div id = "pageContentContainer">
This is the default content to display upon page load.
</div>
<a class = "prev">Previous</a>
<a class = "next">Next</a>
To migrate this solution to one that does not have the pages themselves hardcoded but instead loaded from an external database, you could simply write a PHP script that outputs a JSON encoded array of the pages, and then call that script via AJAX and parse the JSON to replace the pages array above.
var pages = [];
$.ajax({
url: '/ajax/pages.php',
success: function(json) {
pages = JSON.parse(json);
}
});
You can do this without ever effecting the structure of the URL.
Create a function too control the page flow, with an ajax call
function changePage(page){
$.ajax({
type: 'POST',
url: 'myPaginationFile.php',
data: 'page='+page,
success: function(data){
//work with the returned data.
}
});
}
This function MUST be created as a Global function.
Now we call the function on page load so we always land at the first page initially.
changePage('1');
Then we need to create a Pagination File to handle our requests, and output what we need.
<?php
//include whatever you need here. We'll use MySQL for this example
$page = $_REQUEST['page'];
if($page){
$q = $("SELECT * FROM my_table");
$cur_page = $page; // what page are we on
$per_page = 15; //how many results do we want to show per page?
$results = mysql_query($q) or die("MySQL Error:" .mysql_error()); //query
$num_rows = mysql_num_rows($result); // how many rows are returned
$prev_page = $page-1 // previous page is this page, minus 1 page.
$next_page = $page+1 //next page is this page, plus 1 page.
$page_start = (($per_page * $page)-$per_page); //where does our page index start
if($num_rows<=$per_page){
$num_pages = 1;
//we checked to see if the rows we received were less than 15.
//if true, then we only have 1 page.
}else if(($num_rows % $per_page)==0){
$num_pages = ($num_rows/$per_page);
}else{
$num_pages = ($num_rows/$per_page)+1;
$num_pages = (int)$num_pages;
}
$q. = "order by myColumn ASC LIMIT $page_start, $per_page";
//add our pagination, order by our column, sort it by ascending
$result = mysql_query($q) or die ("MySQL Error: ".mysql_error());
while($row = mysql_fetch_array($result){
echo $row[0].','.$row[1].','.$row[2];
if($prev_page){
echo ' Previous ';
for(i=1;$i<=$num_pages;$i++){
if($1 != $page){
echo "<a href=\"JavaScript:changePage('".$i."');\";> ".$i."</a>";
}else{
echo '<a class="current_page"><b>'.$i.'</a>';
}
}
if($page != $num_pages){
echo "<a class='next_link' href='#' id='next-".$next_page."'> Next </a>';
}
}
}
}
I choose to explicitly define the next and previous functions; so here we go with jQuery!
$(".prev_link").live('click', function(e){
e.preventDefault();//not modifying URL's here.
var page = $(this).attr("id");
var page = page.replace(/prev-/g, '');
changePage(page);
});
$(".next_link").live('click', function(e){
e.preventDefault(); // not modifying URL's here
var page = $(this).attr("id");
var page = page.replace(/next-/g, '');
changePage(page);
});
Then finally, we go back to our changePage function that we built initially and we set a target for our data to go to, preferably a DIV already existing within the DOM.
...
success: function(data){
$("#paginationDiv").html(data);
}
I hope this gives you at least some insight into how I'd perform pagination with ajax and php without modifying the URL bar.
Good luck!

PHP, SQL, and JQuery paging error

I'm following this tutorial here: http://brenelz.com/blog/implementing-paging-using-php-and-jquery/
Here is what I have: http://eataustineat.com/testingfolder/
I've encountered a strange problem when the page initially loads. All that shows is the Next and previous link when the first set of results and the next link should be present. Once you click next or previous, then the the results show. But after that, the next and previous links no longer work. The numbered links will work, however.
I've included the jquery below because i believe it to be the source of the problem:
function pager(dir) {
var page = parseInt($("#offset").val());
var max = parseInt($("#maxpage").val());
var no = isNaN(parseInt(dir));
if (!no) {
page = parseInt(dir);
}
if (dir == "next") page = page + 1;
else if (dir == "first") page = 0;
else page = page - 1;
if (page == 0) {
$("#prev").remove();
} else $("#prev").add();
if (page == max - 1) {
$("#next").remove();
} else $("#next").add();
$.post("page.php", {
val: page
}, function (result) {
$("#table-div").html(result);
});
}
Thanks for reading.
The problem is the var page = parseInt($("#offset").val()); line in your pager function. There is no element with an id attribute of offset. The result of parseInt is NaN and when you try to add a number to it, it doesn't add since NaN isn't a number.
You most likely forgot to add the element that contains the offset in your form somewhere. It looks like that's covered in Step 9 of your tutorial.
Is there createTable($link,$sql_offset,$limit); in your php code, Step 8

Categories