javascript include_once- javascript php calling same file duplicating content - php

I am using ajax to load a php script that shows content based on screen resolution. The script works great, but the url that ajax calls is also called later in the script-- it holds all of the processing information. So, the result is all content is loaded via jquery and then duplicated with php. Example:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'functions/maxresults.php',
type: 'GET',
data: {h: screen.height, w: screen.width}
}).done(function ( data ) {
alert("I am working!");
document.getElementById("container").innerHTML=data;
});
});
</script>
And further down
<?php
include_once("functions/maxresults.php");
?>
<?php
require_once("databasefunctions.php");
?>
<div id="container">
<div id="movieinfo">
<?php include("sidebar.php");?>
<?php
// get the function
include_once ('function.php');
if($_GET['page'])
$page = $_GET['page'];
else
$page = 0;
$maxresults = -1;
if(($_GET['w']) && ($_GET['h'])) {
$w = $_GET['w'];
$h = $_GET['h'];
}
if ($w == 1920) {
$maxresults = 24;
} else if ($w == 1600) {
$maxresults = 21;
} else if ($w == 1440){
$maxresults = 14;
} else if ($w == 1366) {
$maxresults = 21;
} else if ($w == 1024) {
$maxresults = 8;
} else
$maxresults = 6;
echo $maxresults;
$currentpage = $page;
$page = $page*$maxresults;
$numpages = QuickQuery("SELECT COUNT(id) FROM movies WHERE visible=1");
$numpages = mysql_result($numpages, 0);
$numpages = $numpages/$maxresults-1;
$result = GetMoviesByRangeID($page, $maxresults);//Show <maxresults> pages at a time
DisplayResults($result);
?>
</div>
</div>
I cannot remove the php include or the script won't work at all. Would creating an include_once in the jquery work and if so, how do I code it?

PHP is a preprocessor. So, it doesn't matter that you are including it 'later' in the file. Your include_once will be processed and output before the JavaScript is executed.
I looks like the problem is that your include_once script is also outputting the container div. So, when you remove that line it breaks the javascript. Try this instead:
Remove the container div from you maxresults.php file.
Replace the <?php include_once('functions/maxresults.php);> with an empty div with an id of container: <div id="container"></div>
Your JavaScript should work now:
<script type="text/javascript">
$(document).ready(function() {
$.ajax({
url: 'functions/maxresults.php',
type: 'GET',
data: {h: screen.height, w: screen.width}
}).done(function(resp) {
alert("I am working!");
$("#container").html(resp);
});
});
</script>
And further down
<div =id="container"></div>
maxresults.php
<?php
require_once("databasefunctions.php");
?>
<div id="movieinfo">
<?php include("sidebar.php");?>
<?php
// get the function
include_once ('function.php');
if($_GET['page'])
$page = $_GET['page'];
else
$page = 0;
$maxresults = -1;
if(($_GET['w']) && ($_GET['h'])) {
$w = $_GET['w'];
$h = $_GET['h'];
}
if ($w == 1920) {
$maxresults = 24;
} else if ($w == 1600) {
$maxresults = 21;
} else if ($w == 1440){
$maxresults = 14;
} else if ($w == 1366) {
$maxresults = 21;
} else if ($w == 1024) {
$maxresults = 8;
} else
$maxresults = 6;
echo $maxresults;
$currentpage = $page;
$page = $page*$maxresults;
$numpages = QuickQuery("SELECT COUNT(id) FROM movies WHERE visible=1");
$numpages = mysql_result($numpages, 0);
$numpages = $numpages/$maxresults-1;
$result = GetMoviesByRangeID($page, $maxresults);//Show <maxresults> pages at a time
DisplayResults($result);
?>
</div>

Related

AJAX pagination, update current page

I created a numeric pagination that loads the data via AJAX.
This is the code:
$(document).ready(function(){
load_data(1);
function load_data(page)
{
$.ajax({
url:"pagination2.php",
method:"POST",
data:{page:page},
success:function(data){
$('#load_data').html(data);
}
});
}
$(document).on('click', '.pagination_link', function(event)
{
event.preventDefault();
var page = $(this).attr("id");
load_data(page);
//Now push PAGE to URL
window.history.pushState({page}, `Selected: ${page}`, `${'page=' + page}`)
return event.preventDefault();
});
window.addEventListener('popstate', e => {
var page = $(this).attr("id");
load_data(e.state.page);
console.log('popstate error!');
});
});
The code works, but when I refresh the page the data are loaded again from the first page. test_ajax
Ex: If I click the button that loads the page 2 when I refresh the page the data are displayed from the page 1.
There is a way to remain on the same page even after the page refresh?
pagination2.php
<?php
$rowperpage = 10;
$page = 1;
if($_REQUEST['page'] > 1)
{
$p = (($_REQUEST['page'] - 1) * $rowperpage);
$page = $_REQUEST['page'];
}
else
{
$p = 0;
}
?>
<?php
$visible = $visible ?? true;
$products_count = count_all_products(['visible' => $visible]);
$sql = "SELECT * FROM products ";
$sql .= "WHERE visible = true ";
$sql .= "ORDER BY position ASC ";
$sql .= "LIMIT ".$p.", ".$rowperpage."";
$product_set = find_by_sql($sql);
$product_count = mysqli_num_rows($product_set);
if($product_count == 0) {
echo "<h1>No products</h1>";
}
while($run_product_set = mysqli_fetch_assoc($product_set)) { ?>
<div style="float: left; margin-left: 20px; margin-top: 10px; class="small">
<a href="<?php echo url_for('/show.php?id=' . h(u($run_product_set['id']))); ?>">
<img src="staff/images/<?php echo h($run_product_set['filename']); ?> " width="150">
</a>
<p><?php echo h($run_product_set['prod_name']); ?></p>
</div>
<?php }
mysqli_free_result($product_set);
?>
<section id="pagination">
<?php
$url = url_for('index_all.php');
if($_REQUEST['page'] > 1)
{
$page_nb = $_REQUEST['page'];
}
else
{
$page_nb = 1;
}
$check = $p + $rowperpage;
$prev_page = $page_nb - 1;
$limit = $products_count / $rowperpage;
//echo $limit;
//exit;
$limit = ceil($limit);
$current_page = $page_nb;
if($page_nb > 1) {
//echo "<a href='index_all.php?page=".$prev_page."'>Back</a>";
echo "<span class='pagination_link' style='cursor:pointer;' id='".$prev_page."'>Back</span>";
}
if ( $products_count > $check ) {
for ( $i = max( 1, $page_nb - 5 ); $i <= min( $page_nb + 5, $limit ); $i++ ) {
if ( $current_page == $i ) {
echo "<span class=\"selected\">{$i}</span>";
} else {
echo "<span class='pagination_link' style='cursor:pointer;' id='".$i."'>".$i."</span>";
}
}
}
if ($products_count > $check) {
$next_page = $page_nb + 1;
echo "<span class='pagination_link' style='cursor:pointer;' id='".$next_page."'>Next</span>";
}
When the document is ready you use load_data(1);
That's wrong because if someone refreshes at page 5 it starts anyway from page 1.
Check the current page everytime you refresh.
The code should be something like this:
var url_string = window.location.href;
var url_parts = url_string.split('/');
var piece = url_parts[url_parts.length -1]; //get last part of url (it should be page=n)
var page;
if(piece.substring(0, 5) === 'page=') {
page = parseInt(piece.substr(5));
} else { //if it's the first time you landed in the page you haven't page=n
page = 1;
}
load_data(page);

pagination with hash and parameters doesn't work

I have page with a URL like this:
http://***.com/profile/username#profile_favs
With my pagination it looks like this:
http://***.com/profile/username?s=0&p=1#profile_favs
The last example doesn't work.
Basically my pagination-function looks like this:
function Pagination($pages, $start, $display, $link_url="", $anchor="") {
echo '<div id="pagination">';
$current_page = ($start / $display) + 1;
$paginator_num = 5;
$pages_display = 10;
if ($current_page > $pages - $paginator_num) {
$paginator_num = $pages_display - ($pages - $current_page);
} elseif ($current_page < $paginator_num + 1) {
$paginator_num = $pages_display - $current_page;
} else {
$paginator_num = 5;
}
$min = max($current_page - $paginator_num, 1);
$max = min($current_page + $paginator_num, $pages);
for ($i = $min; $i <= $max; $i++) {
if ($i != $current_page) {
echo '<div class="pagination_link">';
echo '' . $i . '';
echo '</div>';
} else {
echo '<div id="pagination_active" class="pagination_link">';
echo $i . ' ';
echo '</div>';
}
}
echo '</div>';
}
And this is the part that calculates the pages (this part gets included right before my pagination-function):
<?php
$display = $display_num;
if (isset($_GET['p']) && is_numeric ($_GET['p'])) {
$pages = $_GET['p'];
} else {
$total_results = $qr_num;
if ($total_results > $display) {
$pages = ceil ($total_results / $display);
} else {
$pages = 1;
}
}
if (isset($_GET['s']) && is_numeric ($_GET['s'])) {
$start = $_GET['s'];
} else {
$start = 0;
}
?>
Now my question is: Is there any workaround possible to get that pagination working with a URL mentioned above:
http://***.com/profile/username?s=0&p=1#profile_favs
Actually I'd prefer a solution without GET-parameters.
You could use an AJAX call with the XMPHttpRequest Object to fetch it without the get parameters.
Another thing you could do (if you are using Apache) is to look at mod_rewrite for urls.
Hope that helps :)

append text from object to textarea not working

Here is the code:
<?php
$_SESSION['currentlocation'] = "combat.php";
if($_SESSION['ambush'] && $_SESSION['flee']) {
for($i = 0; $i < sizeOf($_SESSION['enemies']); $i++) {
$scaling = 20 - $_SESSION['enemies'][$i] -> luck;
if($_SESSION['enemies'][$i]-> rank >= 20 && $_SESSION['enemies'][$i]-> rank <
40) {
$prob = rand(1, 100);
if($prob <= 100) {
// if($prob <= 75 - $scaling * 3.8) {
if($_SESSION['comboAttack'] < 2) {
$_SESSION['comboAttack'] = 2;
}
$_SESSION['enemies'][$i]->comboAttack = 2;
$_SESSION['enemies'][$i]->attackMessage="Enemy #".strval($i)."pulls off
a 2-hit combo. \n";
}
}
else if($_SESSION['enemies'][$i]-> rank >= 40 && $_SESSION['enemies'][i]-> rank
< 60) {
$prob = rand(1, 100);
if($prob <= 50 - $scaling * 3.8) {
if($_SESSION['comboAttack'] < 3) {
$_SESSION['comboAttack'] = 3;
}
$_SESSION['enemies'][$i]->comboAttack = 3;
$_SESSION['enemies'][$i]->attackMessage="Enemy #".strval($i)."pulls off
a 3-hit combo. \n";
}
else if($prob <= 75 - $scaling * 3.8) {
if($_SESSION['comboAttack'] < 2) {
$_SESSION['comboAttack'] = 2;
}
$_SESSION['enemies'][$i]->comboAttack = 2;
}
}
if($_SESSION['enemies'][$i] != null) {
// $_SESSION['enemies'][$i]->attack($i);
// echo $_SESSION['enemies'][$i]->attackMessage;
}
?>
<script type="text/javascript">
$(document).ready(function() {
$('#combatinfo').append('<?php if($_SESSION['enemies'][$i] != null) echo
$_SESSION['enemies'][$i]->attackMessage; ?>');
});
</script>
<?php
}
?>
<button type="button">Defend</button> <button type="button">Flee</button>
<form action="index.php" method="post">
<input type="submit" name="submit" value="Submit" />
</form>
<?php
}
As the title states I'm trying to append the text in the text-field of an object(skinhead) to a textarea. The above code does not work. However when I replace some code with this:
<script type="text/javascript">
$(document).ready(function() {
$('#combatinfo').append('<?php if($_SESSION['enemies'][$i] != null) echo
"HELLO WORLD!" ?>');
});
</script>
This works.
The text in the object is not null, so how come it is not displaying?
Thank you for your time.
Replace
$_SESSION['enemies'][$i]->attackMessage="Enemy #".strval($i)."pulls off
a 2-hit combo. \n";
with
$_SESSION['enemies'][$i]->attackMessage="Enemy #".strval($i)."pulls off a 2-hit combo.
";
and so on...

Limiting pages in php pagination

I want to limit the number of pages displayed on my pagination php script below. This was a script made a few years back for me, and although I have read through similar problems on here, their coding is very different.
Any help with this would be really appreciated.
Here is my current script:
<?php
if ($max_pages>1) {
echo "<br>";
if ($page>0) {
echo 'Previous';
}
for ($x=0;$x<$max_pages;$x++) {
if ($page<>$x) {
echo ''.($x+1).'';
}
else {
echo '<span class="pagination">'.($x+1).'</span>';
}
}
if (($page+1<>$max_pages)) {
echo 'Next';
}
}?>
Your current script cycles $x between 0 and $max_pages.
What you can do is first replace them with $from_page and $to_page:
$from_page = 0;
$to_page = $max_pages;
...
for ($x=$from_page; $x < $to_page; $x++)
at which point the script will work just as before.
Now if you want to only display from $N pages before to $N pages after $page,
$N = 5; // display 5+5+1 = 11 pages
$from_page = $page - $N; if ($from_page < 0) $from_page = 0;
$to_page = $from_page + 2*$N+1; if ($to_page > $max_pages) $to_page = $max_pages;
$from_page = $to_page - 2*$N-1; if ($from_page < 0) $from_page = 0;
Not the most elegant way perhaps, but it will try to fit an 11-page area centered on the current page. You may want to also display a link to pages 0 and $max_pages-1.
MRE version
<?php
if ($max_pages>1)
{
$N = 5; // display 5+5+1 = 11 pages
$to_page = min($max_pages, max(0, $page - $N) + 2*$N+1);
$from_page = max($to_page - 2*$N-1, 0);
echo "<br>";
if ($page > 0)
{
echo 'Previous';
}
for ($x=$from_page; $x < $to_page; $x++) {
if ($page != $x) {
echo ''.($x+1).'';
}
else {
echo '<span class="pagination">'.($x+1).'</span>';
}
}
if (($page+1<>$max_pages)) {
echo 'Next';
}
}?>

PHP from external anchor to internal

I have modified my project into a one page website type.
Part of the code is this:
for ($i = 1; $i <= $total_pages; $i++)
{
echo ''.$i.'';
}
I need that code above to work with an internal link for example:
From here:
echo ''.$i.'';
TO
echo ''.$i.'';
Here is the full source code:
$per_page = 6;
$result = mysql_query("SELECT * FROM mytable ORDER BY date DESC");
$total_results = mysql_num_rows($result);
$total_pages = ceil($total_results / $per_page);
if (isset($_GET['page']) && is_numeric($_GET['page']))
{
$show_page = $_GET['page'];
if ($show_page > 0 && $show_page <= $total_pages)
{
$start = ($show_page -1) * $per_page;
$end = $start + $per_page;
}
else
{
// error - show first set of results
$start = 0;
$end = $per_page;
}
}
else
{
// if page isn't set, show first set of results
$start = 0;
$end = $per_page;
}
// display pagination
echo '<strong>View Page:</strong> ';
echo '<div data-role="controlgroup" data-type="horizontal">';
for ($i = 1; $i <= $total_pages; $i++)
{
echo ''.$i.'';
//echo ''.$i.'';
}
echo '</div>';
I need to change this:
echo ''.$i.'';
so it's internal.
Short answer: This can't be done in PHP alone. You will need send AJAX requests to a PHP script that grabs the data.
Basically, this will involve creating some javascript that listens for any changes to the hash (that's the part after the #);
(function(window) {
var hash = window.location.hash;
setTimeout(function() {
if(window.location.hash !== hash) {
hash = window.location.hash;
//Grab and update page with ajax...
}
setTimeout(arguments.callee, 50);
}, 50);
})(window);
For AJAX basics, check W3Schools. And please, please respect the back button.
Without reloading the page:
foo
If you modify the query string in the link, the page will reload and jump to the anchor:
foo
Or with JQuery:
<script type="text/javascript">
$(document).ready(function(){
window.location.hash = 'my-anchor';
});
</script>

Categories