Endless Scroll with Jquery, PHP, and Ajax - php

So I'm trying to impliment an endless scroll pulling from a table in my mysql database and I have it so that when the bottom of the page is reached it will call for a new number of reviews to be pulled to the newsfeed but for some reason when it gets to the bottom but just shows the loading gif and nothing new loads. Any help where I am messing up would be awesome. Thanks guys
Here is my jquery/ajax:
<script>
//Script to continue the home newsfeed after 10 posts
$(window).scroll(function() {
if($(window).scrollTop() === $(document).height() - $(window).height()) {
$('div#load_more_posts').show();
$.ajax( {
url: "load_more_posts.php?lastPost=" + $(".display_newsfeed:last").attr("id"),
success: function(html) {
if(html) {
$("#outputDiv").append(html);
$('div#load_more_posts').hide();
} else {
$('div#load_more_posts').replaceWith("<center>Finished loading all Posts!</center>")
}
}
});
}
});
</script>
Here is the part of the code where the newsfeed is called:
<div class="outputDiv">
<?php echo "$outputList"; ?><!-- Div for this output has been declared above in PHP before echoing -->
</div> <!-- END outputDiv -->
<div id='load_more_posts' style="display:none">
<center>
<img src="../../images/loading.gif" alt="Loading" />
</center>
</div>
And lastly, Here is the Newsfeed display for each review (display_newsfeed.php):
$review_query = mysql_query("SELECT * FROM `reviews` ORDER BY `review_date` DESC LIMIT 0,10");
while($review_row = mysql_fetch_assoc($review_query)){
$review_title = $review_row['review_title'];
$user_id = $review_row['user_id'];
$user_firstname = $review_row['user_firstname'];
$user_lastname = $review_row['user_lastname'];
$review_id = $review_row['review_id'];
$review_body = $review_row['review_body'];
$review_referral = $review_row['review_referral'];
$outputList .= '
<div class="display_newsfeed" id="'.$review_id.' display_newsfeed">
This code is each review
</div>
';

You're missing a closing bracket in your while loop in display_newsfeed.php. You're also referencing a div with an ID of 'outputDiv' in your javascript, but that element doesn't exist (you're assigning it a CLASS of 'outputDiv' in the HTML). Not sure if these were just typos pasting the code here, but either of those could definitely cause the issue.
If none of those is the issue, the best next step would be identifying where the problem is. If your browser has a developer console (or firebug), double check that the AJAX request is going out and see if it's returning the expected HTML. If it is, the problem is definitely with the client-side code (specifically something in the success callback, unless the request isn't going out at all). If not, the problem is definitely with the script on the server.

Related

AJAX change comment on table row click

I'm currently developing a web app that demonstrates how to "sign" different words in ASL. There's a list of terms on the left, and a video and comment section on the right.
See screenshot here: http://i917.photobucket.com/albums/ad19/brycematheson/Screen%20Shot%202015-06-16%20at%2010.05.36%20PM.png
I'm struggling to get the comments to change using AJAX whenever a new term is clicked. Currently, the comments stay the same as new terms are selected. How would I go about using AJAX to change the comment section to update when a new term is selected?
My comment section looks like so. Updating the $id_post=3 section in PHP will change the comment to match the comments with that ID in the database, so that's not an issue, I just need it to do it on the fly.
Here is my comment code in my index.php page:
<?php
// Connect to the database
require_once('models/db-settings.php');
$id_post = '$_POST['rowID']; //the post or the page id
?>
<div class="cmt-container">
<?php
$sql = mysqli_query($mysqli, "SELECT * FROM comments WHERE id_post = '$id_post' ORDER BY id ASC") or die(mysqli_error($mysqli));
while($affcom = mysqli_fetch_array($sql,MYSQLI_ASSOC)) {
$id = $affcom['id'];
$name = $affcom['name'];
$email = $affcom['email'];
$comment = $affcom['comment'];
$date = $affcom['date'];
// Get gravatar Image
// https://fr.gravatar.com/site/implement/images/php/
$default = "mm";
$size = 35;
$grav_url = "http://www.gravatar.com/avatar/".md5(strtolower(trim($email)))."?d=".$default."&s=".$size;
?>
<div class="cmt-cnt">
<img src="<?php echo $grav_url; ?>" />
<div class="thecom">
<h5><?php echo ucfirst($name); ?></h5><span data-utime="1371248446" class="com-dt"><?php echo $date; ?></span>
<br/>
<p>
<?php echo $comment; ?>
</p>
<div style="float:right;"><span class="action">X</span></div>
</div>
</div><!-- end "cmt-cnt" -->
<?php } ?>
<div class="new-com-bt">
<span>Write a comment ...</span>
</div>
<div class="new-com-cnt">
<textarea class="the-new-com"></textarea>
<div class="bt-add-com">Post comment</div>
<div class="bt-cancel-com">Cancel</div>
</div>
<div class="clearfix"></div>
</div>
And my Javascript:
$('#matrix tr').click(function (event) {
var rowID = ($(this).attr('id')); //trying to alert id of the clicked row
$(function(){
e.preventDefault();
$.ajax({
type: 'POST',
url: 'index.php',
data: rowID,
success: function(msg) {
}
});
});
});
What am I doing wrong? Am I missing something?
Thanks in advance.
You aren't actually doing anything with the page once it's returned to you
success: function(msg) {
}
When the ajax completes successfully the code inside this function will execute, whatever was returned by the page will be inside the msg param.
success: function(msg) {
$('#comments-container').html(msg);
}
This will entirely replace the contents of the element(s) that have id="comments-container" with whatever the ajax request returned.
You might properly read the jQuery AJAX documentation page and study some of the examples. http://api.jquery.com/jquery.ajax/
Once you've fixed that you'll run into a problem where it still won't change, this is because you're not sending properly formatted POST data.
data: rowID,
In order to access the POST data like you are trying to (with $_POST[key]) the POST data also needs to be in key-value pairs.
data: "rowID=" + rowID,
Read the comments on the PHP manual page for the $_POST superglobal for a better understanding of this. http://php.net/manual/en/reserved.variables.post.php
EDIT: Oh and if you're planning on releasing this website to the public you might want to look at SQL Injection and how to harden your websites against it. As it stands this would be pretty easily broken into and your database compromised.

jquery effects not visible in php if "echo" is used for output

im having small image gallery that uses fancybox. So on each image there is a hover and popup effect. Below is my code
<div class="one-third column hover">
<a href="large/28crowview_ld.jpg" class="image-box">
<div class="photo">
<span class="text"><span class="anchor"></span></span>
</div>
<img src="large/28crowview_ld.jpg" height="170px" width="260px"/>
</a>
</div>
the above code works perfectly.
but im using a ajax controller that returns the above code using an echo
echo '<div class="one-third column hover">
<a href="large/28crowview_ld.jpg" class="image-box">
<div class="photo">
<span class="text"><span class="anchor"></span></span>
</div>
<img src="large/28crowview_ld.jpg" height="170px" width="260px"/>
</a>
</div>';
but when i use the echo tag the images are displayed but non of the hover effects are visible. it was very odd. and i also noticed the same issue on my social bar.
It works perfectly when i use it in a html view. But when i echo, i see the code in the source but the icons are not visible
echo '<div class="supersocialshare" data-networks="facebook,google,twitter,linkedin,pinterest" data-url="'.$share.'" data-orientation="line"></div>';
all the images are placed correctly, no js conflicts.
Below is the java script im using
<script type="text/javascript">
$(document).ready(function() {
var track_click = 0; //track user click on "load more" button, righ now it is 0 click
var total_pages = <?php echo $total_pages; ?>;
$('#results').load("<?php echo base_url() ?>fetch_pages", {'page':track_click}, function() {track_click++;}); //initial data to load
$(".load_more").click(function (e) { //user clicks on button
$(this).hide(); //hide load more button on click
$('.animation_image').show(); //show loading image
if(track_click <= total_pages) //make sure user clicks are still less than total pages
{
//post page number and load returned data into result element
$.post('<?php echo base_url() ?>fetch_pages',{'page': track_click}, function(data) {
$(".load_more").show(); //bring back load more button
$("#results").append(data); //append data received from server
//scroll page to button element
$("html, body").animate({scrollTop: $("#load_more_button").offset().top}, 500);
//hide loading image
$('.animation_image').hide(); //hide loading image once data is received
track_click++; //user click increment on load button
}).fail(function(xhr, ajaxOptions, thrownError) {
alert(thrownError); //alert any HTTP error
$(".load_more").show(); //bring back load more button
$('.animation_image').hide(); //hide loading image once data is received
});
if(track_click >= total_pages-1)
{
//reached end of the page yet? disable load button
$(".load_more").attr("disabled", "disabled");
}
}
});
});
</script>
inside fetch_pages
$page_number = filter_var($this->input->post('page'), FILTER_SANITIZE_NUMBER_INT, FILTER_FLAG_STRIP_HIGH);
//throw HTTP error if page number is not valid
if(!is_numeric($page_number)){
header('HTTP/1.1 500 Invalid page number!');
exit();
}
$item_per_page = 5;
//get current starting point of records
$position = ($page_number * $item_per_page);
$cottages = $this->properties->getstuff($sub_location,$position, $item_per_page);
foreach ($props as $cots):
echo'<div class="container section" id="'.$cots["id"].'">
<div class="one-third column hover">
<a href="'.$cots["image_url"].'" class="image-box">
<div class="photo">
<span class="text"><span class="anchor"></span></span>
</div>
<img src="'.$cots["image_url"].'" height="170px" width="260px"/>
</a>
</div>';
endforeach;
Im building this project using codeigniter, php and jquery. Any help will be appreciated.
You seem to have some serious problems understanding the overall architecture of a web application, what is happening on the browser of your client and what is happening on the server, what php does, and so on. You should read up on that.
However, your problem is most likely related to the fact that your hover and popup effects are being accomplished by something equivalent to this:
$(".hover").on("hover",function () {
// BLAH
});
If this is the case, then any elements with class hover loaded after the event handler has been attached (that is, through ajax) will not have that event handler attached to them, a simple fix would be to attach the event handler to the container and use a delegated event handler, something like this:
$(document).on("hover",".hover",function () {
// This handler is attached to the document but applies to any .hover elements inside it
});
Another fix would be to run whatever function attaches your "fancybox" functionality to an element after the element has been loaded through ajax. Hard to get it right without some reference code but i assume it would be something like:
$.get(url, function (data) {
var elem = $(data);
$("#container").append(elem);
elem.fancybox();
});
please provide you JavaScript code, I would like to throw my cent. I bet you are using hover method instead of live hover or on hover functions
just like the following :
jQuery('#div').click(...); // this will work fine if you place your code in page not posted back from ajax request or dynamically created
jQuery('#div').live('click',...); // this will work even if the element was created dynamically or from ajax request.
jQuery "live" link
jQuery "On" link
one more thing, be careful the live function is deprecated and removed from jQuery 1.9
According to anpsmn comment i had to re initialize the complete fancybox plugin within
$(window).load(function() {
it worked perfectly..

How do I implement Ajax/JQuery to an existing PHP MYSQL pagination script?

Below is a working pagination script that displays content from a MySQL database. I need to have the pages seamlessly load within the container "#content" rather than have the entire page refreshed. I search extensively for hours but none of the tutorials I encountered helped me implement Ajax/JQuery on this script.
Here is the code I use to display my articles + pagination.
<div id="content">
<?php
include('db.php');
$stmt = $db->query('SELECT * FROM db');
$numrows = $stmt->rowCount();
$rowsperpage=21;
$totalpages=ceil($numrows/$rowsperpage);
if(isset($pageid)&&is_numeric($pageid)){$page=$pageid;}else{$page=1;}
if($page>$totalpages){$page = $totalpages;}
if($page<1){$page=1;}
$offset=($page-1)*$rowsperpage;
$stmt=$db->prepare("SELECT * FROM db ORDER BY ID DESC LIMIT ?,?");
$stmt->bindValue(1, "$offset", PDO::PARAM_STR);
$stmt->bindValue(2, "$rowsperpage", PDO::PARAM_STR);
if($stmt->execute()) {
while ($row = $stmt->fetch()) {
echo '
<article>
article here
</article>
';}}
$range=4;
echo'
<div id="pagination">';
if($page>1){
echo "
<a href='http://www.domain.com/1/'><<</a>";
$prevpage = $page - 1;
echo "
<a href='http://www.domain.com/$prevpage/'><</a>";
}
for ($x = ($page - $range); $x < (($page + $range) + 1); $x++) {
if(($x>0)&&($x<= $totalpages)){
if($x==$page){
echo'
<span class="current">'.$x.'</span>';
}
else{echo"<a href='http://www.domain.com/$x/'>$x</a>";}
}
}
if($page!=$totalpages){
$nextpage=$page+1;
echo"
<a href='http://www.domain.com/$nextpage/'>></a>";
echo "
<a href='http://www.domain.com/$totalpages/'>>></a>";
}
echo '
</div>';
?>
Your setup is a little unclear, but bear with me.
I'm going to assume that on the client side you know when to load the next page (ie the user clicks a button or scrolls to the end of the page etc...) I'm also going to assume that the PHP code you've posted is in its own file and outputs only what you've posted in your question (aka it outputs only the HTML for the articles and nothing else, no wrappers, nothing, if not make it so.
What you're going to want to do is use jQuery (From your question it looks like you already have it on your site so adding another library isn't too taboo) to make an AJAX request to this PHP page. The PHP then echos out what you've posted and the jQuery inserts this on the page inside the #content div.
First a note: I wouldn't recommend having your PHP page output the content div, I would recommend having that stay on the client side and only changing the content of it to what your script returns.
To load new content, you can use this javascript function on the client side:
function makePaginationRequest( pagenum = 1 ) {
// Make ajax request
$.ajax("test2.php", {
// Data to send to the PHP page
data: { "pagenum": pagenum },
// Type of data to receive (html)
dataType: 'html',
// What to do if we encounter a problem fetching it
error: function(xhr, text){
alert("Whoops! The request for new content failed");
},
// What to do when this completes succesfully
success: function(pagination) {
$('#content').html(pagination);
}
})
}
You can place any other parameters you need to pass to the server inside the "data" object (the data: { "pagenum": pagenum }, in key-value form. As you can see from the example, you pass the page number to this function and it passes the "pagenum" request variable to the server.
You'll want to implement a better error handler obviously. As well as change the "test2.htm" filename to that of your PHP script.
A better way of doing this
I feel compelled to mention this:
The way above (what you asked for) is really a messy way of doing this. Whenever you request AJAX data from your server, the server should return content, not markup. You should then insert this content into markup on the client side.
To do this, you would modify your PHP script to first put everything in an array (or an array of array for multiple articles) like this:
while ($row = $stmt->fetch()) {
$output_array[] = array(
"post_title" => $row["title"],
"post_date" => $row["date"],
// etc....
);
}
Then echo it like so:
die(json_encode($output_array));
Then modify your json request:
function makePaginationRequest( pagenum = 1 ) {
$.ajax("test2.htm", {
data: { "pagenum": pagenum },
dataType: 'json',
error: function(xhr, text){
alert("Whoops! The request for new content failed");
},
success: function(pagination) {
// Empty the content area
$('#content').empty();
// Insert each item
for ( var i in pagination ) {
var div = $('<article></article>');
div.append('<span class="title">' + pagination[i].post_title + "</span>");
div.append('<span class="date">' + pagination[i].post_date + "</span>");
$('#content').append(div)
}
}
})
}
jQuery will automagically parse this JSON output into a native javascript object for you.
Taking this approach of having the client make the markup takes alot of load off of your server, and requires less bandwith.
Food for thought, hope that helps.
If you want to do the least amount of rewriting to your original script, the jQuery .load() method might be your best bet. You would basically just need to supply an id to the element that contains all of your articles; something like this should work:
<div id="container">
<div id="articles-container">
<article> ... </article>
</div>
</div>
<div id="pagination">
1 ...
</div>
Then add a script tag and some jQuery code:
<script>
$(function(){
$('#pagination').on('click', 'a', function(e){
e.preventDefault();
var url = $(this).attr('href');
$('#container').load(url + ' #articles-container');
});
});
</script>
.load() will fetch the page, and if you add the optional fragment to the URL, it will filter the result to the element matching the fragment.
EDIT:
Okay, so, to make this work with your current pagination, you need to manually swap the elements. So, assuming your generated markup looks something like this:
<div id="pagination">
1
<span class="current">2</span>
3
4
5
</div>
We want this to happen after the load() completes, so we need to add a callback function to it. I'm also adding a self reference to the clicked element, which we need later:
$(function(){
$('#pagination').on('click', 'a', function(e){
e.preventDefault();
var $this = $(this);
var url = $this.attr('href');
$('#container').load(url + ' #articles-container', function(response, status, jqxhr){
});
});
});
Inside the callback is where we start manipulating #pagination. The first part is easy enough:
var $curr = $('#pagination span.current');
var page = $curr.text();
$curr.replaceWith('' + page + '');
Now we need to replace the link we just clicked:
$this.replaceWith('<span class="current">' + $this.text() + '</span>');
Et viola!, your pagination should be updated. Here's the whole update:
$(function(){
$('#pagination').on('click', 'a', function(e){
e.preventDefault();
var $this = $(this);
var url = $this.attr('href');
$('#container').load(url + ' #articles-container', function(response, status, jqxhr){
var $curr = $('#pagination span.current');
var page = $curr.text();
$curr.replaceWith('' + page + '');
$this.replaceWith('<span class="current">' + $this.text() + '</span>');
});
});
});

How can PHP access the 'style' properties of a div?

So my PHP webiste generates DHTML output that looks like the following:
<div class="toggle-ctrl" onclick="toggleMenu();">
click me to toggle menu
</div>
<div id="site-menu">
<ul>
<li>opt 1</li>
<li>opt 2</li>
</ul>
</div>
<p>Link to Myself</p>
And of course, when clicked, the first div calls some JavaScript which toggles the visibility of the site-menu
function toggleMenu() {
var navigation_pane = document.getElementById('site-menu').style;
if ( navigation_pane.display == 'none' )
navigation_pane.display = 'block';
else
navigation_pane.display = 'none';
}
All this works fine. It's clicking on the link which is bothering me right now. Clicking it (of course) creates a new http request, and my PHP engine re-generates the page again.
The problem occurs when the visibility of the site-menu is 'none'. The PHP engine doesn't know that the menu is hidden, so it generates the same-html again, and the browser places the menu back in front of the surprised-looking user.
The question therefore, is how do I inform PHP (or how can PHP go to check) what the status of the site-menu's visibility is, before it goes to re-generate the page?
There are at least two options other than sending the menu state to the PHP script.
Use AJAX to load just part of the page. If you don't reload the menu, you don't need to re-initialize its style. Before going down this path, examine whether AJAX is suitable. If you implement this solution, don't break browser functionality.
Modern browsers support a storage mechanism. Store the menu state in localStorage when it changes, and set the menu state when the page loads. To support older browsers, you can create an API that uses web storage when available and cookies when not (jQuery.Storage does this).
Menu.js:
/* implementation of Storage, Class and addEventListenerTo left as
an exercise for the reader.
*/
var Menu = {
init: function(id, toggleId) {
if (! toggleId) {
toggleId = id + '-toggle';
}
var toggler = document.getElementById(toggleId),
menu = document.getElementById(id);
menu.toggler = toggler;
/* addEventListenerTo should call the browser-supplied event subscriber
method (e.g. addEventListener or attachEvent)
*/
addEventListenerTo(toggler, 'click',
function(evt) {
Menu.toggle(id);
});
if (! Storage.exists(id+'-open')) {
Storage.set(id+'-open', true);
}
if (Storage.get(id+'-open')) {
Menu.open(id);
} else {
Menu.close(id);
}
},
toggle: function(id) {
var menu = document.getElementById(id);
Class.toggle(menu, 'open closed');
if (Class.has(menu, 'open')) {
menu.toggler.firstChild.nodeValue = 'close menu';
Storage.set(id + '-open', true);
} else {
menu.toggler.firstChild.nodeValue = 'open menu';
Storage.set(id + '-open', false);
}
},
setState: function (id, toAdd, toRemove) {
var menu = document.getElementById(id);
Class.remove(menu, toRemove);
Class.add(menu, toAdd);
},
open: function(id) {
this.setState(id, 'open', 'closed');
},
close: function(id) {
this.setState(id, 'closed', 'open');
}
};
some CSS file:
.closed { display: none; }
page:
<div id="site-menu-toggle" class="toggle-ctrl">close menu</div>
<div id="site-menu" class="open">
<ul>
<li>opt 1</li>
<li>opt 2</li>
</ul>
</div>
<p>Link to Myself</p>
<script type="text/javascript">
Menu.init('site-menu');
</script>
You can play with a live version of the Menu.js approach on jsFiddle. Using jQuery, you can do away with Menu.js, resulting in a much more succinct implementation:
<script type="text/javascript">
$('#site-menu-toggle').click(function (evt) {
var $menu = $('#site-menu');
$menu.toggleClass('open close');
$.Storage.set('site-menu-state', $menu.attr('class'));
if ($menu.hasClass('open')) {
$('#site-menu-toggle').text('close menu');
} else {
$('#site-menu-toggle').text('open menu');
}
});
$(function() {
var state = $.Storage.get('site-menu-state');
if (! state) {
$.Storage.set('site-menu-state', $('#site-menu').attr('class'));
} else {
$('#site-menu').attr('class', state);
}
});
</script>
There's a jFiddle for the jQuery menu state implementation that you can play with.
Since differences in the menu state don't conceptually make for different resources, it doesn't matter whether having the menu open or closed is bookmarkable or affected by history.
NB. don't use the text "click me", it's too verbose and redundant (what other action is there? Affordances should be implicit.). Instead, you can use a graphic to indicate open/close, or simply say "open menu"/"close menu".
The question therefore, is how do I inform PHP (or how can PHP go to
check) what the status of the site-menu's visibility is, before it
goes to re-generate the page?
It can't. By the time the HTML is delivered to the browser, PHP is no longer in the picture. The only way you could make PHP aware of this would be to send a parameter in the URL indicating the menu is hidden, or set a cookie and have the cookie indicate visibility of the object. Then PHP can check for the presence of this value and set the visibility of the div when it renders it.
You could accomplish this in a number of ways, for example:
Use document.cookie to set the cookie in your toggleMenu function.
Use ajax to notify PHP in the toggleMenu function and have PHP set a cookie or session value
Append a flag to the link indicating the visibility of the menu from the toggleMenu function.
Actually, there are several types of answers to your question.
While it may sound there's no way to do what you want, there are, in fact, many ways.
Cookies
The obvious. Cookies can be accessed by javascript as well as PHP. Just modify the cookie whenever the menu is shown/hidden through javascript (there's the excellent jQuery cookie plugin).
Form input
If you are submitting a form, simply have a hidden input keep the value of the menu's visibility:
<input type="hidden" name="menu-visibility" value="0"/>
Again, you need javascript to keep this input updated.
Update relevant parts of the page
This is the hip & leet new trend. Well, actually, it's been there for some 6 years or so. Basically, don't submit anything and don't reload the page. Update the parts of the page that actually need updating, through AJAX.
Local Storage
As #outis mentioned, today browsers have something similar to cookies, except they keep it for themselves (hence locally). It's a pretty new feature, to be honest, I wouldn't trust it considering there are better ways to accomplish what you need.
In addition to drew010's suggestions: You could also create a form with a hidden input element named, let's say, 'menu_status' whose value gets set by toggleMenu(). Then when you click on your link, use javascript to POST or GET the form. Then you read the value server-side with php using either $_POST["menu_status"] or $_GET["menu_status"], depending on the form method.
UPDATE: Something like this:
<form name="session_form" action="" method="POST">
<input type="hidden" name="menu_state" value="block">
</form>
<?php $menu_state = isset($_POST["menu_state"]) ? $_POST["menu_state"] : "block"; ?>
<div id="site-menu" style="display:<?php echo $menu_state; ?>">
<ul>
<li>opt 1</li>
<li>opt 2</li>
</ul>
</div>
<p>Link to Myself</p>
function toggleMenu() {
var navigation_pane = document.getElementById('site-menu').style;
if ( navigation_pane.display == 'none' )
navigation_pane.display = 'block';
else
navigation_pane.display = 'none';
document.forms.session_form.menu_state.value = navigation_pane.display;
}
EDIT: Using jQuery ajax could involve something like this:
<div class="toggle-ctrl">click me to toggle menu</div>
<?php $menu_state = isset($_POST["menu_state"]) ? $_POST["menu_state"] : "block"; ?>
<div id="site-menu" style="display:<?php echo $menu_state; ?>">
<ul>
<li>opt 1</li>
<li>opt 2</li>
</ul>
</div>
<p>Link to Myself</p>
$("div.toggle-ctrl").click(function(){
$("#site-menu").toggle();
});
$("#go").click(function(e) {
e.preventDefault();
var menu_state = $("#site-menu").css("display");
$.post("", {menu_state:menu_state}, function (response) {
$("html").html(response);
});
});
Or without using ajax or a form, just append a parameter to the link and use $_GET instead of $_POST in your php:
$("#go").click(function(e) {
e.preventDefault();
var menu_state = $("#site-menu").css("display");
document.location.href = "index.php?menu_state=" + menu_state;
});
This seems to me the simplest solution.
I know it's not cool to answer your own question, but another possible solution occurred to me last night, and it only requires 1 new line of code to be written (sort of).
The first part of the solution has already been implicitly suggested by many of you. Modify the JavaScript to write to a cookie:
function toggleMenu() {
var navigation_pane = document.getElementById('site-menu').style;
if ( navigation_pane.display == 'none' )
navigation_pane.display = 'block';
else
navigation_pane.display = 'none';
document.cookie = "menu_vis=" + navigation_pane.display; // +1 line of code
}
Now, what are the possibilities if your CSS file just so happens to be a PHP file in disguise? my_css.php would look something like this:
<?php
header("Content-type: text/css");
?>
#site-menu {
display: <?php echo isset($_COOKIE['menu_vis']) ? $_COOKIE['menu_vis'] : 'block'; ?>; /* line of code modified, but not added! */
}
Tested this morning, and it works.
I find it a neat solution, because it means that I don't have to bend my PHP or HTML design around any presentational concerns.
--
I appreciate that there are more "encompassing" solutions out there. If I was a better JavaScript developer, (or made use of jQuery or the like), I could build more complicated classes which could then be applied more generally to other HTML elements. I may come back to investigate such solutions later, but that's just not where my project is at the moment.
Thank you everyone for all your replies. I wouldn't have found this solution without bouncing these ideas off you guys.

How do I show next result in MySQL on "onclick" in JavaScript?

I want to show a certain amount of results (say, 5) and make a:
<a href="" onclick="<?php ShowNextResult(); ?>">
And use onlick to show the next 5 results.
EDIT ::
HTML
<div id="results">
<div class="result"></div>
<div class="result"></div>
<div class="result"></div>
</div>
<a href="#" id="showMore" />Show more</a>
JAVASCRIPT
Use Jquery as below
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
$('#showMore').click(function(event) {
event.preventDefault();
$number = $('.result').size();
$.ajax({
type: "POST",
url: "getNext.php",
data: "count=$number",
success: function(results){
$('#results').append(results);
}
});
});
});
</script>
PHP
you should make a new php page (getNext.php ) that will get query results
<?php
$con = mysql_connect("localhost","peter","abc123");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}
mysql_select_db("my_db", $con);
$result = mysql_query("SELECT * FROM Persons LIMIT {$_POST['count']},5");
while($row = mysql_fetch_array($result))
{
echo "<div class='result'>".$row['FirstName'] . " " . $row['LastName']."</div>";
}
mysql_close($con);
?>
HELP
you can use SQL something like
SELECT x,xx,xxx FROM XxXxXs Limit $_POST['count'],5
Since you specifically mention JavaScript I assume you don't want to reload the page or anything like that. Your onClick will have to trigger an AJAX call to a php page on your server that will handle the request and give you back the next five records (or the last 5, or random ones, etc...).
JQuery is really popular for doing this and have built in functionality to make this process easier.
http://api.jquery.com/jQuery.ajax/
Here are some tutorials: http://docs.jquery.com/Tutorials
Your best bet is to write this functionality w/o using JavaScript. Make the page accept arguments to show specific records. Once you have that code done, then put the AJAX on top of it, but that way you'll have the older stuff to fall back on if you need to for compatibility or things don't work the way you need them to.
These are pretty general answers, do you need specific help making the query to only show the next 5 records? Or the specific PHP code to tie it together? Or just the JS to do the AJAX stuff? Could you be more descriptive if you need more info.
change
data: "count=$number",
to
data: "count=" + $number,
because then it isn't work!
Here's my solution that showing quiz questions partially with next button means on each click at Next Button 5 more question will display.
<?php
$strSQL="SELECT * FROM `quizes` WHERE Q1 IS NOT NULL ORDER BY RAND()";
$result=mysql_query($strSQL);
while($row=mysql_fetch_array($result)){
$c=0;
$q[]= $row['Q1']; // This is database record that has all question stored as array
?>
<?php
for($inc=0; $inc < $ret; $inc++){ ?>
<table>
<tr id="<?php echo "i".$inc ?>">
<td id="qs"> <?php print_r($q[$inc]); ?></td>
</tr></table>
<!-- here in i am display all question with loop in this variable $q[$inc] -->
<?php } ?>
// Now we are going to display partial
instead of all so data will display partially with next button
Next/Show More
//this is anchor/button on which more questions will load and display when clicked
//CSS question are placing in tr (table row) so first hide all question
<style>
tr{
display:none
}
</style>
//jquery now we will show partial question 5-questions at each click
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("[id=i0],[id=i1],[id=i2],[id=i3],[id=i4],[id=i5]").show();
//Display first 5-question on page load other question will
//show when use will click on next button
var i=0;
$("#more").click(function(){ // Next button click function
//questions tr id we set in above code is looping like this i1,i2,i3,i4,i5,i6...
i=i+5; //at each click increment of 5 question
var e=i+5;
//start after the last displayed question like if previous result was 1-5 question then next result should be 5-10 questions...
for(var c=i; c < e; c++ ){
$("[id=i"+c+"]").show();
}
});
});
</script>

Categories