I am trying to load more data from a database with a jQuery .load, and it works perfectly, but after the first load, it ist'n bringing more data.
Also, for bringing the first content, which is brought on the first page load, i use a PHP foreach() loop, like this as a basic example:
<div class="grid-products">
<?php foreach($products as $product): ?>
<div class="grid-product">
<?php echo $product['name']; ?>
</div>
<?php endforeach; ?>
</div>
I am trying to load more data from my database on scroll, so the user don't have to click on a button. I am loading information from my database based on the method of this question, like this:
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
//do an ajax call
}
});
But as I don't know how to do the ajax call mentioned on the answer above I found, I decided to use a jquery .load passing also some POST method variables, which in this case would be productNewCount. First I set its value to 6, and when user reaches bottom of page, we sum plus six to its value, like this:
$(window).scroll(function() {
var productCount = 6;
if($(window).scrollTop() == $(document).height() - $(window).height()) {
productCount = productCount + 6;
$(".grid-products").load("load-products.php", {
productNewCount: productCount
});
}
});
This works great on first load, and so when this is executed, it loads on the <div class="grid-products"> the load-products.php file. Here, the variable $connection is calling my function to connect to the database, don't give too much importance to it.
This is load-products.php:
<?php
$connection = connect();
$product_new_count = $_POST['productNewCount'];
$sentence = $connection->prepare("
SELECT * FROM all_products ORDER BY date DESC LIMIT $product_new_count
");
$sentence->execute();
$products = $sentence;
?>
<?php foreach($products as $product): ?>
<div class="grid-product">
<?php echo $product['name']; ?>
</div>
<?php endforeach; ?>
In the sentence, we are calling to bring all the rows from the all_products table ordered through its date column, and limiting to bring only the rows product_new_count says, which its value is the productCount JS variable we brought on the main file, before its load.
I made sure there are still rows available to bring, so the reason why other rows arent being shown after first load isn't because there are no rows left. Also, terminal isnt showing any errors or warnings and there is also still available space to make scroll so the function can be called.
Can I bring more data through this .load method or should I use the AJAX call mentioned on the answer I found? If so how?
Every time you scroll productCount is set to 6, hence all your load request will be the same.
You can define productCount outside the event handler to increase the number of elements loaded each time.
var productCount = 6;
$(window).scroll(function() {
if($(window).scrollTop() == $(document).height() - $(window).height()) {
productCount = productCount + 6;
$(".grid-products").load("load-products.php", {
productNewCount: productCount
});
}
});
If you are trying to add to the existing content (not replace all of it) use $.post instead of load() and append the results.
load() replaces whatever is already existing inside the matching selector
$.post("load-products.php", {productNewCount: productCount}, function(html){
$(".grid-products").append(html)
})
Related
how is it possible to achieve this:
http://jennamolby.com/how-to-display-dynamic-content-on-a-page-using-url-parameters/
using php?
let's say that I have the following a url:
http://localhost:8888/index.php?page=pages-folder/works-folder/content-manager?article=my-article
to get there I have a link in pages-folder/works.php :
link
which should open content-manager.php in which inside a div I should load my-article.php
EDITED:
I have an index file in which a load into the div.container all the pages I need, so in this case my works.php file is loaded int the div.container using using:
<?php
$page = $_GET['page'];
if(!empty($page)){
$page .= '.php';
include($page);
}
else {
include('pages/home.php');
}
since I also needed to update the url without reloading the page I use this script:
function ChangeUrl(page, url) {
if (typeof (history.pushState) != "undefined") {
var obj = { Page: page, Url: url };
history.pushState(obj, obj.Page, obj.Url);
}
}
$('ul.menu li a').on('click', function(){
var page = $(this).attr('href');
var pageUrl = page.split("/");
pageUrl = pageUrl[1];
$('.container').load(page + '.php', function(){
//fadeout old content
//fadein new content
});
ChangeUrl('Page1', '?page=' + page);
return false;
})
once I have my works.php loaded into the div.container I have the above mentioned link which should lead me to: pages-folder/works-folder/content-manager.php
it is in this page where I'd like to load my-article.php inside the main div of content-manager.php
I thought that adding the ?article= variable would have worked using the same system as above:
$article = $_GET['article'];
if(!empty($article)){
$article .= '.php';
include($article);
}
else {
...
}
but it doesn't...
how can I achieve this?
Why you don't just add you article as a query param ?
http://localhost:8888/index.php?page=pages-folder/works-folder/content-manager&article=my-article
and make a link like this
link
This is just an exemple to understand what you want to do, don't use this kind of code in production, he is vulnerably to CSRF attack
EDIT: with echo it's better sorry
I haven't answered your question per se but this is the sort of code you are looking for:
<?php if (isset($_GET["page"]) && strtolower($_GET["page"]) == "1") { ?>
<p>You are on page one</p>
Back
<?php } elseif (isset($_GET["page"]) && strtolower($_GET["page"]) == "2") { ?>
<p>You are on page two</p>
Back
<?php } else { ?>
<p>You have not selected a page. Click one of the links:</p>
Page one
Page two
<?php } ?>
Explanation
How does $_GET work?
$_GET is a super global variable - meaning it can be accessed from anywhere.
It is a an associative array of variables passed to the current script via the URL parameters.
These are specified following a question mark (?) in the URL. To specify multiple parameters you must use the ampersand (&) character between each one.
$_GET must be specified at the end of the URL after everything else.
http://www.example.com/thisPage.php?page=a
http://www.example.com/thisPage.php?page=a&theme=light
The first URL will produce a $_GET with one element which can be accessed as: $_GET["page"] and would return a string of one character a.
The second will produce:
$_GET["page"]; // returns "a"
$_GET["theme"]; // returns "light"
Notice that for each parameter a new key-value pair is created.
I wrote a comprehensive explanation of superglobals on SO Documentation, but that has since been deprecated. RIP my hard work :P
Showing differing content
As you can see from my answer above. You can use simple if statements to check what the value is.
Firstly, ensure that $_GET isset and then check the value.
I have converted the value of the array to lowercase since "A" is not the same as "a".
The example you linked to really over-complicates things. There is honestly no need for all that regular expressions, and it also relies on JavaScript which is not necessarily a good idea.
With my example at the top, there is no difference between user experience as PHP is server sided thus all the content is worked out and then served to the user.
One step further
Using this you can go that extra step and have an event listener and combine it with AJAX.
Altering my initial example you can have the following.
I have used the jQuery library as it is a lot easier to implement.
<div id="test">
<?php if (isset($_GET["page"]) && strtolower($_GET["page"]) == "1") { ?>
<p>You are on page one</p>
Back
<?php } elseif (isset($_GET["page"]) && strtolower($_GET["page"]) == "2") { ?>
<p>You are on page two</p>
Back
<?php } else { ?>
<p>You have not selected a page. Click one of the links:</p>
Page one
Page two
<?php } ?>
</div>
function myAJAX() {
$("a").on("click", function(e) {
e.preventDefault();
// get the clicked page number
if (this.href.indexOf("&") > -1) {
var d = this.href.substring(this.href.indexOf("page=") + "page=".length, this.href.indexOf("&"))
} else {
var d = this.href.substr(this.href.indexOf("page=") + "page=".length)
}
$.ajax({
method: "GET",
url: "t.php",
data: "page=" + d,
success: function(data, textStatus, jqXHR) {
// change the content of the #test div
$("#test").html($($.parseHTML(data)).filter("#test")[0]);
myAJAX();
}
});
});
}
myAJAX();
Notice that the HTML is not being wrapped in <div id="test"> which is so that the JavaScript can find that element and change it in the function.
$("#test").html($($.parseHTML(data)).filter("#test")[0]); is the line that is fetching the HTML and changing it with the data from the page you tried to click on.
I also call the function inside itself so that it will reattach on the anchor links. If you remove this line then the page will redirect as normal.
The good thing about this implementation is that if your user does not have JavaScript then the page will act as normal and there will be a normal reload of the site.
No need for any extra work on your part.
Ok, I've looked around Stack and other places for the past 4 or 5 hours trying to find a solution to my problem.
I have an Iframe inside of a page which contains 5 lines of information, the information is fetched from a database. Said info will constantly change, therefor a need it to be refreshed every 1-5 seconds, can stretch to 10 seconds if needs be.
I have used the below code, which works, but crashed my browser(s) for some reason, I'm guessing reloading too fast?
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.0/jquery.min.js"></script>
<script type="text/javascript">
var auto_refresh = setInterval(
function ()
{
$('#info').load('mid.php');
}, 5000); // refresh every 5000 milliseconds
</script>
Below is the code from mid.php (There is PHP inside the page but this is the part that I need refreshing).
<div id="info"><font size="2">
<b>Crimes: </b><font color="white"><?php if ($fetch->lastcrime <= time()){ echo 'Ready'; }else{ echo "".maketime($fetch->lastcrime).""; } ?></font><br>
<b>GTA: </b><font color="white"><?php if ($fetch->lastgta <= time()){ echo 'Ready'; }else{ echo "".maketime($fetch->lastgta).""; } ?></font><br>
<b>Chase: </b><font color="white"><?php if ($fetch->last_chase < time()){ echo 'Ready'; }else{ echo "".maketime($fetch->last_chase).""; } ?></font><br>
<b>Extortion: </b><font color="white"><?php if ($fetch->last_ext < time()){ echo 'Ready'; }else{ echo "".maketime($fetch->last_ext).""; } ?></font><br>
<b>Rank:</b><?php echo "$fetch->rank"; ?></td></tr>
</div>
</table>
I know I can use HTML to refresh the Iframe but it looks unsightly when the whole top left corner of the screen refreshes every 3 seconds, any help is much appreciated.
Thanks
I'd expect you to use Ajax calls for this kind of thing. You'd tonally ice jQuery to update the contents of elements in place to avoid the refresh of your iframe. Iframes are limited in their capabilities and it typically doesn't make sense to use them just for updating web page contents.
The browser crash may be coming from the use of set internal. If the calls take longer than 5 seconds to complete, multiple calls might stack up. But for your case I feel like it's not the problem, as it should be able to update that orange pretty quick. Any way, a better approach is to set a timer for one execution of your update process every time it gets done running. That way, if the call does take too long, you don't just keep stacking up requests.
Use can use .load() callback, substitute setTimeout() for setInterval
$(document).ready(function() {
let timeout;
let duration = 5000;
let stop = false;
function update() {
$("#info").load("mid.php", function() {
if (timeout) {
clearTimeout(timeout)
}
if (stop === false) {
timeout = setTimeout(update, duration)
}
});
}
update();
});
Thanks.
I ended up using pretty much the same script, just splitting the PHP and HTML into separate files and calling the div from the HTML file.
This question already has answers here:
Load ajax when scroll reaches 80%
(2 answers)
Closed 8 years ago.
I have a container like this:
<div class="row row-sm padder-lg ">
<div class="col-xs-6 col-sm-4 col-md-3 col-lg-2">
...
</div></div>
The content is generated by this loop on a php page:
<?php
foreach ($top->feed->entry as $key => $value)
{
$value->title->label = str_ireplace( "- ".$value->artist->label, "", $value->title->label);
if($key >= $this->config->item("items_top"))
return false;
$image = $value->image[2]->label;
if($image == '')
$image = base_url()."assets/images/no-cover.png";
$image = str_ireplace("170x170", "200x200", $image);
?>
"items_top" is the number of array for max. images to display, how could I make a load more on scrolling?
So when user scroll at the bottom of the page are automatically loaded new contents
UPDATE
Ok I need to use Ajax but how to do? Is it correct to use this code in my php?
<script>
$(document).scroll(function(e){
// grab the scroll amount and the window height
var scrollAmount = $(window).scrollTop();
var documentHeight = $(document).height();
// calculate the percentage the user has scrolled down the page
var scrollPercent = (scrollAmount / documentHeight) * 100;
if(scrollPercent > 50) {
// run a function called doSomething
doSomething();
}
function doSomething() {
// do something when a user gets 50% of the way down my page
}
});
</script>
Short answer: You can't, at least not with PHP.
Since PHP is processed on the server side before the page is given to the client, there is no way to edit a page with PHP after it is received. That is the job of JavaScript or rather AJAX.
If you move your PHP script onto a separate page (php only preferably) that you include in your website, you can make an AJAX call to replace a part of the HTML code with the content returned by the script after the user scrolls.
This link might help you with that:
Loading DIV content via ajax as HTML
I have this small script, which, when clicked on, will show the content from a page where I do a PHP query. My problem is, that if the user click multiply times, it will just load the content from the PHP page multiply times as well...
This is my jQuery code:
$('.notifications-load').on('click',function() {
$('#notifications-holder').load("/?i=notifications");
});
And my HTML:
<i class="fa fa-bell notifications-load"><span class="notification">5</span></i>
<div id="notifications-holder"></div>
This is the PHP page (?i=notifications):
$n=$dbh->prepare("SELECT * FROM users_notifications WHERE userid=0 OR userid=:userid");
$n->bindParam(":userid",$userdata['id']);
$n->execute();
$data=$n->fetchAll();
foreach ($data as $value) {
echo $value['text'];
}
If a user clicks example 3 times on .notifications-load , then the content from /?i=notifications will load 3 times into the #notifications-holder - how can I prevent this?
Believe it or not, one character of difference will fix it:
$('.notifications-load').one('click',function() {
// Here -------------------^
$('#notifications-holder').load("/?i=notifications");
});
jQuery's one function hooks up a handler that it automatically unhooks the first time it's called.
If you have an aversion to using one (as some do, it's really easy to misread it as on), you have a couple of options:
You can create an alias for it:
$.fn.onOnce = $.fn.one;
You can unhook the handler explicitly:
$('.notifications-load').on('click.load',function() {
$('#notifications-holder').load("/?i=notifications");
$('.notifications-load').off('click.load');
});
Besides using $.one you can check to see if $('#notifications-holder') already has a value. Something like:
$('.notifications-load').on('click',function() {
var notification = $('#notifications-holder');
if (!notification.html().trim().length) {
notification.load("/?i=notifications");
}
});
I want to apply a plugin on a certain table that is being generated dynamically through a php script. This is the plugin : CLICK
Now from what i read in the comments i should You first need some form of server side component, say a PHP script, which generates the html table from the data in the database. Then pass the URL of this PHP script into a jQuery ajax call. In the "success" callback, set the innerHTML of some holding div to the response of the ajax call, then select this newly created DOM table element and put it into the plugin.
Hope that makes sense!
Here's what i got so far.
HTML
<div class="testin">
<script>
testin();
</script>
</div>
JS
function testin(){
var load = $.get('functions.php',{gameNo:"1",function:"testin"});
$(".testin").html('Refreshing');
load.error(function() {
console.log("Mlkia kaneis");
$(".testin").html('failed to load');
// do something here if request failed
});
load.success(function( res ) {
console.log( "Success" );
$(".testin").html(res);
});
load.done(function() {
console.log( "Completed" );
});
}
php
if($_GET['function']=="testin")
{
echo '<table class="template" style="display:none"><thead><tr><th>Game Name</th><th>Round</th><th>Player Name</th><th>Target Name</th><th>Shot Number Now</th><th>Shot Score So Far</th><th>Rank</th></tr></thead><tbody></tbody></table>';
$gamenumber = $_GET['gameNo'];
echo'<table border="1" class="actualTable"><tr><th>Game Name</th><th>Round</th><th>Player Name</th><th>Target Name</th><th>Shot Number Now</th><th>Shot Score So Far</th><th>Rank</th></tr>';
$sql = mysql_query("SELECT * FROM tbl_Round WHERE match_id='$gamenumber' ORDER BY round_name")
or die(mysql_error());
$i=1;
while($row = mysql_fetch_array($sql))
{
$tempSnumber = getcurrentshot($row['round_id'],$row['player_id']);
echo'<tr>';
echo'<td>'.$gamenumber.'</td>';
echo'<td>'.$row['round_name'].'</td>';
echo'<td>'.$row['player_id'].'</td>';
echo'<td>'.$row['target_name'].'</td>';
echo'<td>'.$tempSnumber.'</td>';
echo'<td>'.$row['round_score'].'</td>';
echo'<td>'.$i.'</td>';
echo'</tr>';
$i++;
}
echo'</table>';
}
The function fills the div just fine. I also create the template table in the php script.
Now my problem is how to invoke the plugin and what should i pass ass objects?
Invocation is like $(oldTableElement).rankingTableUpdate(newTableElement) but i'm confused due to the fact that it's being generated dynamically.
I'm new to JS so any help would be appreciated.
First off, I would put your javascript outside the div with class "testin".
Below you JS function you can add the jquery call like in the code below.
See this link for more info: http://api.jquery.com/on/
$(document).ready(function(){
$("table tr").on( "click", function() {
//your custom code goes here.
});
});
What this does is make sure then any element that matches the "table tr" will get an click handler, no matter when it gets created.