jQuery slider to load content one at a time - php

I have a slider that load all of my content at once. Into a div. Like so:
external page.php
$get_users = mysql_query("SELECT * FROM user WHERE id!='$user_id'");
while ($rows = mysql_fetch_assoc($get_users)) {
$id = $rows['id'];
$firstname = $rows['firstname'];
$display_info .= '
<div class="f_outer" id="' . $id . '">
<div class="f_name likeu">' . $firstname . '</div>
</div>';
}
echo $display_info;
I call this page from my find.php page using bxslider
Here is my find.php page below.
<script type="text/javascript">
$(function() {
var slider = $("#slider1").bxSlider();
$("#slider-like").live('click', function() {
slider.goToNextSlide();
return false;
});
});
</script>
<div id="slider-like>Yes</div>
<div id="slider1">
<?PHP
include ("external.php");
?>
</div>
So what I get is all of my .f_outer div on the find.php page. I have hundreds of user and they will all be loaded at once. I would like to only load one slide at a time. So when I click #slider-like it load one of my dive from my external page.

If you include external.php, it loads all of the data from user. If you want to dynamically load, you need to use ajax instead of including the file on the server. You can keep track of what user you are up to with JS or the php session. I think the former is easier:
var nextUser = 0;
$(document).on('click', '#slider-like', function (e) {
var slider = $("#slider1").bxSlider();
$("#slider1").load("getuser.php?num=" + nextUser, function () {
slider.goToNextSlide();
nextUser++;
});
e.preventDefault();
});
Then, on getuser.php, you would have:
$num = isset($_GET['num']) ? $_GET['num'] : exit;
$query = "SELECT * FROM user WHERE id != '$user_id' LIMIT $num,1";
This queries the $numth user and limits it to one result.
NOTE: You should use PDO or mysqli instead of mysql_*. Both $user_id and $num need to be escaped.

Related

Ajax infinite scrolling not loading

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']

load contents without reloading the page

I am using the following code, for loading contents without loading the page !
index.html
<html>
<head>
<script type="text/javascript">
// <![CDATA[
document.observe('dom:loaded', function () {
var newsCat = document.getElementsByClassName('newsCat');
for(var i = 0; i < newsCat.length; i++) {
$(newsCat[i].id).onclick = function () {
getCatPage(this.id);
}
}
});
function getCatPage(id) {
var url = 'load-content.php';
var rand = Math.random(9999);
var pars = 'id=' + id + '&rand=' + rand;
var myAjax = new Ajax.Request(url, {
method: 'get',
parameters: pars,
onLoading: showLoad,
onComplete: showResponse
});
}
function showLoad() {
$('newsContent').style.display = 'none';
$('newsLoading').style.display = 'block';
}
function showResponse(originalRequest) {
var newData = originalRequest.responseText;
$('newsLoading').style.display = 'none';
$('newsContent').style.display = 'block';
$('newsContent').innerHTML = newData;
}
// ]]>
</script>
</head>
<body>
<div class="newsCat" id="newsCat1">Politics</div>
<div class="newsCat" id="newsCat2">Sports</div>
<div class="newsCat" id="newsCat3">Lifestyle</div>
<div id="newsLoading">Loading
<img src="loading_indicator.gif" title="Loading..." alt="Loading..." border="0" />
</div>
<div id="newsContent"></div>
</div>
</body>
</html>
this page is for including the desired page in the index.php !
content-load.php
<?php
function stringForJavascript($in_string) {
$str = preg_replace("# [\r\n] #", " \\n\\\n", $in_string);
$str = preg_replace('#"#', '\\"', $str);
return $str;
$user = $_SESSION['userName'];
}
switch($_GET['id']) {
case 'newsCat1':
$content = include("politics.php");
break;
case 'newsCat2':
$content = include("sports.php");
break;
case 'newsCat3':
$content = include("lifestyle.php");
break;
default:
$content = 'There was an error.';
}
print stringForJavascript($content);
usleep(600000);
?>
PROBLEM FACING
it works fine, but when i am refreshing the page or submitting a form, the code refreshes, i mean the page which was include before refreshing, doesnot exists......
and i am really sorry about my ENGLISH, i know its horrible ! :)
pls help me php masters, i need ur help...
There are two ways to slove that problem.
You could do that on the client site with an hashtag what is curriently loaded and rebuild the page with that data or:
use the pushState API to manipulate the shown url in the address bar. Then you need to return the right data from the server after a reload.
This is behaviour by design. The Reload button will really reload the page - this includes resetting the page state.
In a freshly loaded page, you do not display a category - this is triggered only by user interaction after the page has finished loading.
A common workaraound is to store the chosen category in a cookie, auto-trigger the category load after the page has initialized.

Keeping variables from PHP while loop

I have been looking all over for a way to do this.
I use a PHP while loop to get some variables from a database:
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
?>
<script type="text/javascript">
<!--
function go_there()
{
var id= "<?php echo $id ?>"
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
//-->
</SCRIPT>
<td><form><INPUT TYPE="button" value="Go!" onClick="go_there()"></form></td></tr>
<? } //end while
?>
Sometimes i get 10 results, and i make 10 Go! bottoms. But when i come to the delete page, the $is variable is off cause the same as the last result, no matter witch of the bottoms i press..
Any ideas on how to get around that, so i get the confirm box, and still keep the right id to be deleted?
You're creating a global function called "go_there" for each entry, so only the last one will remain. Instead of that, create just one function, and fetch the "id" value from an attribute on the button.
function go_there(button)
{
var id= button.getAttribute("data-id");
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
}
Then:
<INPUT TYPE="button" value="Go!" onClick="go_there(this)" data-id="<?php echo $id ?>">
It seems to me like you're creating your javascript function in your loop as well so it only fires one of them (you're creating multiple functions with the same name. How is it supposed to know which one to use). You should create 1 javascript function and pass the id into it as a a parameter
<script type="text/javascript">
function go_there(id)
{
var where_to= confirm("Are you sure you want to delete?");
if (where_to== true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
</SCRIPT>
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
echo '<td><form><INPUT TYPE="button" value="Go!" onClick="go_there(<?php echo $id; ?>)"></form></td></tr>'
} //end while
?>
Overall this is a poor way to do this. You should avoid wrtiting handlers inline unless you have a specific case where it is the only way. Much better if you attach a handler to the elements in questions (working fiddle - for firefox anyhow...):
<!-- output our inputs with the id value in an attribute data-id-value -->
<?php while ($row = mysql_fetch_array($query)): $id = $row["ID"]; ?>
<td><form><INPUT class="go-button" TYPE="button" value="Go!" data-id-value="<?php echo $id ?>"></form></td></tr>
<?php endwhile; ?>
<script type="text/javascript">
var goButtons = document.querySelectorAll('input.go-button'), // select all out buttons
// define our handler function
goThere = function (event) {
// get the id the we encoded from php from our data attr
var id = event.target.getAttribute('data-id-value');
if(confirm('Are you sure you want to delete?')) {
// if confirm is true then redirect to the delete url
window.location = "index.php?p=delete&id=" + id;
}
};
// loop over the buttons and attach the handler
for (var i = 0; i < goButtons.length; i++) {
goButtons[i].addEventListener('click', goThere);
}
</script>
The issue here is that that isnt necessarily cross browser. Thats typically one of the reasons people use libraries like jQuery or similar so that they don't have to normalize dom querying and listener attachment.
Here is a corrected script.
<?php while ($row = mysql_fetch_array($query)) {
$id = $row["ID"];
?>
<SCRIPT language="JavaScript">
<!--
function go_there()
{
var id= "<?php echo $id ?>"
var where_to= confirm("Are you sure you want to delete?");
if (where_to == true)
{
window.location="index.php?p=delete&id=" + id;
}
else
{
}
}
-->
</SCRIPT>
<td><form><INPUT TYPE="button" value="Go!" onClick="go_there()"></form></td></tr>
Your button will not work because you have added the comment markers <!-- and --> to the function. If you want help with that then please comment.
Also, can you clarify you're issue in the comments? We can help you better then.

javascript variable value to php variable and loading tab content by default

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'">

Codeigniter scrollpagination

I am using jquery plugin scrollpagination in codeigniter i am facing problem that my loop does not terminate and alos not giving accurate result.
this is my html code
<div id="main">
<div id='friend_display'>
<?php if($list->num_rows() > 0 ){
foreach($list->result() as $show)
{ ?>
<div class="image-box" style="margin-left:30px" id='image-holder' >
<div class="photo-cover">
<img width="160px" height="117px" src="<?=base_url()?>uploads/user_images/friends/<?php echo $show->user_image;?>" alt="" />
</div>
<p class="photo-name"><b><?php echo $show->user_name;?></b></p>
</div>
<?php } } else { echo '<div align="center" style="color:#FF0000; font-size:17px; font-weight:bold">You have no Friends yet</div>';}?>
<div class="cl"> </div>
</div></div>
this is script
<script type="text/javascript">
var page_num = 1;
$(function(){
$('#friend_display').scrollPagination({
'contentPage': '<?=base_url()?>friends/load_more', // the url you are fetching the results
'contentData': {page_num:$('.image-box').size()}, // these are the variables you can pass to the request, for example: children().size() to know which page you are
'scrollTarget': $(window), // who gonna scroll? in this example, the full window
'heightOffset': 10, // it gonna request when scroll is 10 pixels before the page ends
'beforeLoad': function(){ // before load function, you can display a preloader div
$('#loading1').fadeIn();
},
'afterLoad': function(elementsLoaded){ // after loading content, you can use this function to animate your new elements
$('#loading1').fadeOut();
var i = 0;
$(elementsLoaded).fadeInWithDelay();
page_num:$('.image-box').size();
}
});
// code for fade in element by element
$.fn.fadeInWithDelay = function(){
var delay = 0;
return this.each(function(){
$(this).delay(delay).animate({opacity:1}, 200);
delay += 100;
});
};
});
</script>
and this is my php function
function load_more()
{
$offset = $this->input->post('page_num');
$list = $this->friends_model->show_friends($offset);
if($list->num_rows()>0)
{
foreach($list->result() as $show)
{?>
<div class="image-box" style="margin-left:30px" id='image-holder'>
<div class="photo-cover">
<img width="160px" height="117px" src="<?=base_url()?>uploads/user_images/friends/<?php echo $show->user_image;?>" alt="" />
</div>
<p class="photo-name"><b><?php echo $show->user_name;?></b></p>
</div>
<?php } ?>
<div class="cl"> </div>
<?php
}
else
{
//echo(333);
}
}
in db i jst shoing main query
$this->db->limit(12,$offset);
can someone tell me what i am missing?
Open this Link to wathch complete code.Scroll Pagination
I belive that the way you are fetching offset isn't correct. (Thought I'm not sure because I don't know what is in your POST['page_num'])
$offset = $this->input->post('page_num');
It looks like you fetch the page number, but the offset in limit function should be how much row has to be skipped. So if you are showing 12 results per "tick" offset should be 12*page_number
$this->db->limit(12,$offset*12);
If you leave offset to page number, you will get wrong results:
limit(12,[0,1,2,...]) // items 1-12, 2-13, 3-14 etc...
limit(12,[0,12,24....] //items 1-12, 13-24, 25-32 etc...
Here i solve this problem in my own way you can try this.In your script remove this line
'contentData': {page_num:$('.image-box').size()},
and add this line
'childClass' : '.image-box',
After open scrollpagination.js file then replace this line data: opts.contentData, with this data: {page_num : $(obj).children(opts.childClass).size()},. Again replace 'contentData' : {}, this line with 'childClass' : '.datalist',.
In your function display_friends() please replace exit; function with this line echo '<input type="hidden" id="nodata" value="1" />'; . After that write your script look like this :
$(function(){
$('#nomoreresult').hide();
$('#loading1').hide();
$('#friend_display').scrollPagination({
'contentPage': 'Your_Url', // the url you are fetching the results
// these are the variables you can pass to the request, for example: children().size() to know which page you are
'childClass' : '.image-box',
'scrollTarget': $(window), // who gonna scroll? in this example, the full window
'heightOffset': 10, // it gonna request when scroll is 10 pixels before the page ends
'beforeLoad': function(){ // before load function, you can display a preloader div
$('#loading1').show().fadeIn();
},
'afterLoad': function(elementsLoaded){
// after loading content, you can use this function to animate your new elements
$('#loading1').hide().fadeOut();
$(elementsLoaded).fadeInWithDelay();
if($('#nodata').val() == '1'){
$('#friend_display').stopScrollPagination();
$('#loading1').hide();
$('#nomoreresult').show().fadeIn();
}
}
});
// code for fade in element by element
$.fn.fadeInWithDelay = function(){
var delay = 0;
return this.each(function(){
$(this).delay(delay).animate({opacity:1}, 200);
delay += 1000;
});
};
Did you try jQuery.noConflict()?
<script type="text/javascript">
var page_num = 1;
jQuery.noConflict();
$(function(){...
Edit2:
It seems your offset works wrong. According to http://pastebin.com/MC1KZm8y
Find:
$offset = $this->input->post('page_num');
$list = $this->friends_model->find($offset);
Replace:
$page_line = 6; //for example
$page_num = $this->input->post('page_num');
$offset = ($page_num -1) * $page_line;
$list = $this->friends_model->find($offset);
Add this missing code inside the afterLoad:function(){.. code also this should stop looping your pagination make sure to add exactly same id that you entered for the scrollpagination id <div id='friend_display'>
if ($('#friend_display').children().size() > 100){ //set the condition to where to stop
// if more than 100 results already loaded, then stop pagination (only for testing)
$('#nomoreresults').fadeIn(); //if you want to show message like "No more result!" use this
$('#friend_display').stopScrollPagination();// this is the most important function call
}
inside .scrollPagination({.. change 'contentPage': '<?php echo base_url();?>controller/action' inside this action(){ $this->load->view('that_you_want_to_display'); it means your display_friends() method only should contain the view file that want to load and parse and the data that you want to display and inside that view echo your data using the foreach

Categories