So in my index.php file i have this:
<script src="jquery-1.12.3.js"></script>
<script>
$(window).scroll(function() {
var load = 0;
if($(window).scrollTop() + $(window).height() == $(document).height()) {
load++;
$.POST("scripts/myload.php",{load:load},function(data){
$.('photoclass').append(data);
})
}
});
</script>
and in my "myload.php" file i have this
$query = $handler->query("SELECT * FROM photo LIMIT ".$load.",5");
while($photo = $query->fetch()){
echo '<center><h1 class="ptitle">'.$photo['PhotoTitle'].'</h1></center>';
echo '<center><img src="UserPhotos/'.$photo['Photo'].'"></center>';
}
The problem is that it won't load in my index file the rest... Thanks in advance.
change your jquery code.
$.('photoclass').append(data); to
$('.photoclass').append(data); or $('#photoclass').append(data);
putting "." or "#" depends on class or id.
for example :
<div class="photoclass"> </div>then use $('.photoclass').append(data); otherwise $('#photoclass').append(data);
and in your php file make sure you are saving post value to variable.
like this $load=$_POST['load']
Related
I'm affronted to another jQuery problem. Well I'm beginning by my code to understand my issue here:
<script type="text/javascript">
jQuery(document).ready(function() {
var current = <?php echo ($_GET['page']!='') ? $_GET['page'] : 1; ?>;
var idp;
$(window).scroll(function(e){
if($(window).scrollTop() + $(window).height() >= $(document).height()) {
current=current+1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
if($(window).scrollTop() == 0) {
current=((current-1)<=0) ? 1 : current-1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
});
window.onpopstate = function(event) {
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
};
function loadMoreContent(position) {
$('#loader').fadeIn('slow', function() {
$.get("index.php"+position+" #annonceis", function(data){
var dato = $(data).find("#annonceis");
$("#annonceis").html(dato);
$('#loader').fadeOut('slow', function() {
$(window).scrollTop(60);
});
});
});
}
});
</script>
My problem is based on infinite scroll but instead of "append" I used html() function to replace content in a div called annonceis.
The idea is that when I'm scrolling to bottom of the page I get content of new page called index.php?page=1 2 3. And replace old content in de div annonceis with the new content that I get with jQuery, but when I scroll to the bottom I Get content of next next page ex when the current page is index.php?page=2 normally when I scroll to bottom I must get content of index.php?page=3 but here I get content of index.php?page=3 and instantly index.php?page=4 so the page display index.php?page=4.
The main idea is scrolling to bottom and get the content of the next page instead of pagination, but it must take care about history.pushState for SEO purpose and Google suggestions see http://scrollsample.appspot.com/items and that https://googlewebmastercentral.blogspot.com/2014/02/infinite-scroll-search-friendly.html.
Thank you very much in advance.
So, what you're after really is pagination combined with infinite scroll. What the provided example is doing is using .pushState() to track the users scroll using page Waypoints. Notice, once page X reaches the center point in the page, the .pushState() is triggered.
Secondly, if you look at the example's source code for any of the pages, you'll see it will only render the selected page, then using listeners on the .scroll it will append or prepend content as needed.
So, at it's core, this is really just simple pagination. The infinite scroll feel is simply added on top for user experience. Basic overview to do this would look something like this:
Model or Controller
Your PHP file or whatnot, that runs the actual queries - class based for ease of use. The class will contain one function to grab a set of posts based on a request page. JavaScript will handle everything else.
<?php
Class InfiniteScroller {
// Set some Public Vars
public $posts_per_page = 5;
public $page;
/**
* __construct function to grap our AJAX _POST data
*/
public function __construct() {
$this->page = ( isset($_POST['page']) ? $_POST['page'] : 1 );
}
/**
* Call this function with your AJAX, providing what page you want
*/
public function getPosts() {
// Calculate our offset
$offset = ($this->posts_per_page * $this->page) - $this->posts_per_page;
// Set up our Database call
$SQL = "SELECT * FROM my_post_table ORDER BY post_date ASC LIMIT " . $offset . ", " . $this->posts_per_page;
// Run Your query, format and return data
// echo $my_formatted_query_return;
}
}
?>
AJAX Call
The next thing you'll want to take care of is your frontend and JavaScript, so your AJAX call can sit in a function that simply calls the above method and takes a page parameter.
<script type="text/javascript">
function getPageResults( page = 1, arrange = 'next' ) {
$.ajax({
url: url;
type: "POST",
data: "?page=" + page,
success: function(html) {
/* print your info */
if( arrange == 'prev' ) {
$( '#myResults' ).prepend(html);
else if( arrange == 'next' ) {
$( '#myResults' ).append(html);
}
},
error: function(e) {
/* handle your error */
}
});
}
</script>
The HTML View
Your HTML would be fairly basic, just a place to hold your displayed results and some creative triggers.
<html>
<head>
</head>
<body>
<div class="loadPrev"></div>
<div id="myResults">
<!-- Your Results will show up here -->
</div>
<div class="loadNext"></div>
</body>
</html>
Loading the Page You Want
In basic summation, the last piece of your puzzle is loading the page requested based on the querystring in the URL. If no querystring is present, you want page 1. Otherwise, load the requested page.
<script type="text/javascript">
$( document ).ready(function() {
var page = <?php echo ( isset($_GET['page'] ? $_GET['page'] : 1) ?>;
getPageResults( page, 'next' );
});
</script>
After that you can set up some creative listeners for your previous and next triggers and call the getPageResults() with the needed page, and the next or prev attribute as needed.
This can really be done in a much more elegant sense - look at the JS from the example you provided: http://scrollsample.appspot.com/static/main.js
Cleaning it up
Once you have the basic architecture in place, then you can start altering the .pushState() as well as changing out the canonical, next, and prev <link rel> header items. Additionally at this point you can start to generate the next / prev links you need, etc. It should all fall into place once you have that basic foundation laid.
Hey Bro #LionelRitchietheManatee Finnaly I have resolved the problem this is the code that I used.
<script type="text/javascript">
jQuery(document).ready(function() {
var current = <?php echo ($_GET['page']!='') ? $_GET['page'] : 1; ?>;
var idp;
var loaded = true;
$(window).scroll(function(e){
if(($(window).scrollTop() + $(window).height() == $(document).height())&&(loaded)) {
loaded = !loaded;
current=current+1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
if($(window).scrollTop() == 0) {
loaded = !loaded;
current=((current-1)<=0) ? 1 : current-1;
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
e.preventDefault();
}
});
window.onpopstate = function(event) {
if(current<=1)
{
idp = '';
}
else
{
idp = '?page='+current;
}
loadMoreContent(idp);
history.pushState("state", "title: "+current, "index.php"+idp);
};
function loadMoreContent(position) {
$('#loader').fadeIn('slow', function() {
$.get("index.php"+position+" #annonceis", function(data){
var dato = $(data).find("#annonceis");
$("#annonceis").html(dato);
$('#loader').fadeOut('slow', function() {
loaded = !loaded;
$(window).scrollTop(60);
});
});
});
}
});
</script>
I had added a new var called "loaded" with initial value as TRUE, and it will be updated to FALSE state when content is loaded, and to the TRUE state when we begin scrolling.
I'ts very primitive as solution not very clean work as you did but it solved my problem.
Thank you anyway for your help, you are the BOSS.
How is possible to check if div is clicked and then return information?
function kat(){
echo "<div class='turinys'>";
$kategorijos = dbquery("SELECT * FROM kategorijos");
while($kat = dbarray($kategorijos)) {
echo"<div class='kategorija'><a href='".BASEDIR."kategorija/".seoname($kat['kategorija'])."/".$kat['id']."' class='kat'>".trimlink($kat['kategorija'],44)."</a></div>";
}
echo "</div>";
}
echo "<div class='mygtukas-js' onclick='kat();'>";
echo "</div>";
But actually it's wrong because my mygtukas-js has a drop down menu.
I need to generate a code which let me to press a button and then menu would be generated. Maybe someone knows?
EDIT: This div <div class='mygtukas-js'></div> (has to start and end before) <div class='turinys'> STARTS.
Some fresh ideas? :?
EDIT2:
<script src='http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js'>
</script>
<script>
$(document).ready(function(){
$('#mygtukas-js').click(function() {
$("#turinys").load('b.php');
});
});
</script>
and b.php
<?php
$kategorijos = dbquery("SELECT * FROM kategorijos");
while($kat = dbarray($kategorijos)) {
echo"<div class='kategorija'><a href='".BASEDIR."kategorija/".seoname($kat['kategorija'])."/".$kat['id']."' class='kat'>".trimlink($kat['kategorija'],44)."</a></div>";
}
?>
But no information generated :(
Create your PHP file which I guess would also include HTML.
Create a "click" JQuery function and make sure to send the POST to the specific PHP file / Controller which should handle the request. In case you want to just get the above file directly then point to it.
It should be like:
$(document).ready(function(){
$('#send').click(function() {
$("#menu").load('URL_TO_YOUR_PHP');
});
});
Thanks to AJAX the "#menu" should be displayed and will contain whatever the PHP file sends back.
HTH.
U can use jQuery to check if a div is clicked. Like this:
$('.turinys').click(function(e) {
$(this).html("Add any html to the div");
});
Use to different php file. Lets call A.php and B.php. A.php contain the menu code.
A.php
<?php
echo "<div class='turinys'>";
$kategorijos = dbquery("SELECT * FROM kategorijos");
while($kat = dbarray($kategorijos)) {
echo"<div class='kategorija'>
<a href='".BASEDIR."kategorija/".seoname($kat['kategorija'])."/".$kat['id']."' class='kat'>".trimlink($kat['kategorija'],44)."</a>
</div>";
}
echo "</div>";
?>
B.php
<script>
function kat(){
var xhr = new XMLHttpRequest();
xhr.open("GET", "A.php", false);
xhr.send(null);
// You can also check response status if you need.
var serverResponse = xhr.responseText;
document.getElementById('menu').innerHTML = serverResponse;
}
</script>
<?php
echo "<div class='mygtukas-js' onclick='kat();' id='menu'>";
echo "</div>";
?>
I'm attempting to take the ImageResolver plugin and adapt it to work with a php array.
Stripping the code to this returns the image without a form:
$(function(){
var url = $('#url').val();
ImageResolver.resolve(url, function(image){
if (image) {
$('#result').html('<img src="' + image + '" alt="">');
} else {
$('#result').html('<h2>No image found</h2>');
}
});
});
I want to adapt it to work within a php foreach loop. results would be replaced on the next class='result' div. IE: after the page has loaded the urls from the query, the function will parse the url and return image link if one is found. I'm guessing I need to use (each) or this(), but I can't figure it out.
can someone point me in the right direction?
<script src="ImageResolver/URI.min.js"></script>
<script src="ImageResolver/ImageResolver.js"></script>
<?
$javascriptarray = 'var urls = [';
$counter=0;
foreach (array('http://www.apple.com/','http://github.com/','http://www.test.com/') as $url)
{
if ($counter++ > 0) $javascriptarray .= ',';
$javascriptarray .= '"'.$url.'"';
}
$javascriptarray .= '];';
?>
<script>
<?=$javascriptarray?>
//The ImageResolver will try all the resolvers one after the other
//in the order of their registration
//Resolvers that guess the image URL
ImageResolver.register(new FileExtensionResolver());
ImageResolver.register(new ImgurPageResolver());
ImageResolver.register(new NineGagResolver());
ImageResolver.register(new InstagramResolver());
//Resolvers that need extra ajax requests
ImageResolver.register(new ImgurAlbumResolver());
ImageResolver.register(new OpengraphResolver());
ImageResolver.register(new WebpageResolver());
//Some jQuery code to make the demo work
//Use a crossdomain proxy (required by some plugins)
$.ajaxPrefilter('text', function(options) {
options.url = "http://furious-stream-4406.herokuapp.com?src=" + encodeURIComponent(options.url);
});
$(function(){
var length = urls.length,
url = null;
for (var i = 0; i < length; i++) {
url = urls[i];
ImageResolver.resolve(url, function(image){
if (image) {
$('#result').append('<img src="' + image + '" alt=""><br>');
} else {
$('#result').append('<h2>No image</h2>');
//$('#result').append('<h2>No image found for ' + url + '</h2>');
}
});
}
});
</script>
Watch out cause ImageResolver.resolve() works asynchrone you can get unexpected results. Call ImageResolver.resolve() again before the previous call has finished will change url in $('#result').append('<h2>No image found for ' + url + '</h2>'); to the url of your last call by example. To prevent this you need to initialize a new Resolver in the for-loop. see: Javascript prototypes and instance creation
var Result;
$(document).ready(function(){
location.href="index.php?Result=" +1;
$("a").click(function(){
Result=$(this).attr('id');
location.href="index.php?Result=" + Result;
})
});
<div id="tabs">
<ul>
<?php include "config.php";
$query = "select * from tabs";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$name = $row['name']; $tabid = $row['tabid'];
echo '<li><a id="' . $tabid . '" href="#' . $name . '"> ' . $name . '</a></li>';
} ?>
</ul>
</div>
Hie,
I have seven tabs,which are fetched from database using mysql query,Onclick on each tab am passing the tab value from javascript to php variable and by using that tabvalue am running the required querys to load the data into tabs,My issue is am unable to load the first tab content by default,on click the first tab content is loading properly,i want that first tab content to load by default here am using jquery ui tabs,when i followed the above code by calling first tab before onclick it is loading multiple times....and even focus is moving to first tab by default...suggest any solution......thanks....
The reason is, you are redirecting to index.php from the same file. So during the first execution of document ready function, it redirects you to the same file with a different query string parameter. But since the document ready function will execute again now, it keeps on reloading.
The simplest approach will be to handle this in PHP, when the "Result" parameter is not set, make it as 1.
In a javascript way, you can grab the query string value and check if "Result" parameter is set. If its not set then redirect the page to index.php?Result=1.
A javascript way of getting query string parameter is below.
function param(name)
{
var url = window.location.search.substring(1);
var query = url.split('?')[0];
var data = query.split('&');
for(var i in data)
{
if(data[i].split('=')[0] == name)
{
return data[i].split('=')[1];
}
}
}
You can call it by using
var page_num = param('Result');
if(page_num == null)
{
location.href = 'index.php?Result=1';
}
try this
var Result = 1;
$(document).ready(function(){
location.href="index.php?Result=" + Result;
$("a").click(function(){
Result=$(this).attr('id');
location.href="index.php?Result=" + Result;
})
})
This will trigger automatically first tab click.
<script type="text/javascript">
$('.parent > a').trigger('click');
</script>
var Result;
$(document).ready(function(){
$("a").click(function(){
Result=$(this).attr('id');
location.href="index.php?Result=" + Result;
})
}
And Body tag
<body onload="location.href='index.php?Result=1'">
i look this tutorial
http://tutorialzine.com/2009/09/simple-ajax-website-jquery/
but i don't understand how to make this work with php file with sql, echo ""; etc
If someone can explain, i try everything and nothing appears
Thanks :)
var default_content = "";
$(document).ready(function () {
checkURL();
$('ul li a').click(function (e) {
checkURL(this.hash);
});
//filling in the default content
default_content = $('#pagesContent').html();
setInterval("checkURL()", 250);
});
var lasturl = "";
function checkURL(hash) {
if (!hash) hash = window.location.hash;
if (hash != lasturl) {
lasturl = hash;
// FIX - if we've used the history buttons to return to the homepage,
// fill the pageContent with the default_content
if (hash == "")
$('#pagesContent').html(default_content);
else
loadPage(hash);
}
}
function loadPage(url) {
url = url.replace('#page', '');
$('#loading').css('visibility', 'visible');
$.ajax({
type: "POST",
url: "load_page.php",
data: 'page=' + url,
dataType: "html",
success: function (data) {
if (parseInt(data) != 0) {
$('#pagesContent').html(data);
$('#loading').css('visibility', 'hidden');
}
}
});
}
load_page.php
<?php
if(!$_POST['page']) die("0");
$page = (int)$_POST['page'];
if(file_exists('pages/page_'.$page.'.php'))
echo file_get_contents('pages/page_'.$page.'.php');
else echo 'There is no such page!';
?>
demo.html
< a href="#page1">Page1< /a>
< a href="#page2">Page2< /a>
< a href="#page3">Page3< /a>
< a href="#page4">Page4< /a>
<div id="pageContent">
//loaded ajax page
</div>
in this scenario , link > index.html#page1 will load file 'pages/page_1.php'
but in main index.html just can load html code , not php syntax .
Can I use php command in this case ?
So it looks like the problem here is that in the tutorials example, they simply use an HTML file. For this, file_get_contents() will work fine. However if you want your server to parse PHP code before serving it to the user, you should use the include() function.
From the documentation :
The include statement includes and evaluates the specified file.
The file_get_contents() function behaves silghtly differently :
file_get_contents — Reads entire file into a string
It simply reads the contents of the file, the PHP code is not evaluated/executed/interpreted...