Re-frased question do to new info
I'm trying to show a limited set of results on a search (i.e. LIMIT 10 in query) then have a button that will load the next 10 (now LIMIT 20 in same query).
The problem is that when I press the button, it not only refreshes the the specified div - but it re-runs the doSearch at the very top of the page - and thereby resetting the LIMIT to 10...
So if I
1. load the result-page
2. comment out the doSearch at top of page
and first then...
3. click the button
It works as perscribed... it now show 20 results... and if I click again it shows 30... etc.
And if I uncomment the doSearch at the very top of page and click the button... it now shows 10 results again...
the code in question in the ajax-code is
var showResult = self.closest('#showResultsAll').find('[id^="showResults"]');
showResult.load(location.href + " #showResults>*", "");
I can't see why my code would re-run the doSearch at the top of page... but hopeully some of you wise folks can see the error of my ways and set me on the right path...
My basic setup:
page with results:
<?php // get search results limit 10 ?>
.
.
.
<div id="showResultsAll">
.
.
.
<div id="showResults">
// Loop through and show results
<div id="moreResultsButton">
<input type="hidden" name="search" id="search" value="<?php // search terms ?>">
<button id="moreResults" value="<?php // number of results found ?>">
jquery.js
$(document).ready(function(){
"use strict";
$(document).on('click','button[id^="moreResults"]', function(){
var self = $(this);
var closestDiv = self.closest('#moreResultsButton');
var search = closestDiv.find('[id^="search"]').val();
var count = self.val();
var countNew = + count + 10;
$.ajax({
type: "POST",
url:'../scripts/moreresults.php',
data:"countNew="+countNew+"&search="+search,
success:function(){
var showResult = self.closest('#showResultsAll').find('[id^="showResults"]');
showResult.load(location.href + " #showResults>*", "");
}
});
});
});
moreresults.php
session_start ();
require ( "../scripts/functions.php" );
// Set variable
$search = $_POST['search'];
$limit = $_POST['countNew'];
doSearch ( $pdo , $search , $limit ); // same function that found the search results in the first place
Update
So found a solution loosely based on an answer given below by #delCano (although I'm still curious as to why my original code insisted on rerunning the doSearch at the top of the page)
Solution:
I split everything up by first dropping the limit in the doSearch and just let it find all results and then did the 'limiting' in the show-results part of the page, and then just added 10 to that in my jQuery
New code:
page with results
<?php // doSearch no limit ?>
.
.
.
<div id="showResultsAll">
.
.
.
<div id="showResults">
// Loop through and show results - limiting like this
// if isset $_POST['show'] (ie. button clicked)
// if $_POST['show'] less than $_SESSION['totalResults'] (ie. more results coming)
// $show = $_POST['show'] (ie. 20, 30, etc.)
// else
// $show = $_SESSION['totalResults'] (ie. 11, 12, ..., 21, 22, ..., 31, 32, ..., etc.)
// else (if button not clicked limit results to max. 10)
// if $_SESSION['totalResults'] more than 10
// $show = 10
// else
// $show = $_SESSION['totalResults'] (ie. 1, 2, 3, etc.)
// loop trough $show number of results
<div class="<?php if $show == $_SESSION['totalResults'] echo "disabled" // Only active if more results are available ?>" id="moreResultsButton">
<button id="moreResults" value="<?php echo $show; ?>">
jQuery.js
$(document).ready(function(){
"use strict";
$(document).on('click','button[id^="moreResults"]', function(){
var self = $(this);
var show = self.val();
var showNew = + show + 10;
$.ajax({
type: "POST",
url:'',
data:"show="+showNew,
success:function(){
self.closest('#showResultsAll').find('[id^="showResults"]').load(location.href + " #showResults>*", "");
}
});
});
});
OK, this is not the best answer, just a development from the comments above. I'll try and write a better answer tomorrow.
However, for the time being, my quick workaround would be:
Remove, as you mention, the doSearch from the top of the page, and set all the initial numbers to 0.
Replace your jQuery with this:
$(document).ready(function(){
"use strict";
$('button#moreResults').click(addResults);
function addResults(){
var self = $(this);
var closestDiv = self.closest('#moreResultsButton');
var search = closestDiv.find('[id^="search"]').val();
var count = self.val();
var countNew = + count + 10;
$.ajax({
type: "POST",
url:'../scripts/moreresults.php',
data:"countNew="+countNew+"&search="+search,
success:function(){
var showResult = self.closest('#showResultsAll').find('[id^="showResults"]');
showResult.load(location.href + " #showResults>*", "");
}
});
}
// load the first ten results
addResults();
});
Please note I did minimal changes to your Javascript. This is not necessarily the most optimal way to do it; I'll revise and edit it tomorrow.
Edit: major refactoring
doSearch is a PHP function that prints the search results to screen. I would change this into a function that returns an array of results. I don't have your code on this, and I don't know how it looks, but it should return something similar to:
array(
array( 'name' => 'One', 'surname' => 'Smith' ),
array( 'name' => 'Two', 'surname' => 'Smythe' ),
....
)
moreresults.php is the PHP that is called to load new results. Since all the rest of the logic will be done in Javascript, this is for now the ONLY PHP code we call. I would include doSearch() in this file now.
session_start ();
require ( "../scripts/functions.php" );
function doSearch( $pdo, $search, $limit) {
/* do logic here */
return $array_of_results;
}
// Set variable
$search = $_POST['search'];
$limit = $_POST['countNew'];
$results = doSearch ( $pdo , $search , $limit );
header('Content-Type: application/json'); // This will tell the client the type of content returned.
echo json_encode($results); // It is a good idea to make all data transmissions between your server-side code (PHP) and your front-end code (Javascript) in JSON. It's also a good idea to never output anything in your PHP code until the very end, where you have all the required data. It makes it easier to debug later on.
Now, the HTML. It doesn't need any PHP preprocessing now, since it will always start the same. We also don't need the tracking of the variables here, since all the logic would be in the Javascript part now.
.
.
.
<div id="showResultsAll">
.
.
.
<ul id="showResults">
</ul>
<button id="loadMore">Load more results</button>
</div>
.
.
.
The Javascript now bears the weight of most of the logic.
$(function() { // Shorthand for "$(document).ready(function()..."
var count = 0;
$("#loadMore").click(loadMoreResults);
function loadMoreResults() {
var url = "../scripts/moreresults.php";
var search = $("#search").val();
count += 10;
var data = {
'countNew': count,
'search': search
};
$.post(url, data, showResults, 'json' );
}
function showResults(data) {
$("#showResults").empty().append(`
<li>${data.name} ${data.surname}</li>
`);
}
});
Notes:
Since I didn't know what kind of data you're working with, I used a list of names and surnames as an example.
Likewise, I presented the results as a unordered list () and list items(); you might prefer a table, or something different.
The code is completely untested. I tried to be careful, but I may have made some typos or other mistakes.
If I were you, I would try to start by learning some jQuery basics before launching myself into Ajax. The FreeCodeCamp has a nice jQuery course.
Code architecture is extremely important, and not often well explained in online courses. As a summary:
Always plan ahead your code. Pick up a pen&paper, or your favourite text editor, and answer yourself the question: "What must the code do?". Then decompose the answer in smaller steps. Then separate each step into smaller steps, and so on.
Whenever you have a piece of code you might need twice, wrap it into a function. Think of functions as small "tasks"
Separate as much as possible the logic from the presentation. You should have part of your code working on the data itself, and part of it working on showing the data, and they should be almost independent from each other. You might want to look at the MVC pattern (Model-View-Controller); it may be in process of replacing, but it is a good starting point. This, by the way, is valid both on the backend (doSearch would be the logic, moreresults the presentation) and the frontend (html is the presentation, javascript the logic).
To finish, the code I gave you is not perfect, but I think is a better start. You'll assuredly find many ways to improve it
Related
Sometimes function reload(); does't update the div's content. I call this function when clicking a button. Sometimes only one div won't update. Random div, on a random click. Sometimes first click won't work. The div content won't show any error, just a previous not updated number. and when I click the button again it updates and shows the correct one.
Example of the bug (Increasing the #number_input by one every time I click):
div content shows: 1, 2, 2, 4
The problem is with those 2s, 3 is missing. In database the number is correct.
I'm running a local server (XAMPP). Same problem in Firefox, Chrome and IE.
No errors in firebug console. Requests are done correctly but returned value sometimes wrong. Usually only one array item is wrong, the one returned from the database.
Exactly same ajax code with different parameters (on complete) on different button works fine.
PS: Changed my var names into shorter ones so they are eye friendly
Button HTML:
<button id="xButton" class="btn btn-info">Text</button>
Button JS:
document.getElementById('xButton').onclick = function() {
var val = $('#number_input').val();
if (val > 0)
{
var xx = 1;
var yy = 1;
properties(xx, yy, val); //this updates the database by current val + val. Works correctly. Values always updated, no errors there. Clean and simple code. No way this is the source of problem.
number_input.value = 0;
xButton.textContent = ("bla bla"); //just resets the text
p1_reload();
}
}
jQuery:
function reload() {
$.ajax({
type: 'POST',
url: 'example.php',
cache: false,
data: {reload: "action"},
dataType:"json",
success: function(data) {
var xres = new Array();
xres = data;
document.getElementById("x1").textContent = xres[0];
document.getElementById("x2").textContent = xres[1];
document.getElementById("x3").textContent = xres[2];
document.getElementById("x4").textContent = xres[3];
//these two functions has not connection with the updated divs. They don't update or even read them. So, there shouldn't be any problems.
xFunction();
yFunction();
}
});
}
PHP:
if(isset($_POST['reload'])) {
if ( $_SERVER['REQUEST_METHOD'] == 'POST' ) {
try
{
require_once("session.php");
$auth_user = new xClass();
$user_id = $_SESSION['user_session'];
$stmt = $auth_user->runQuery("SELECT * FROM blabla WHERE user_id=:user_id LIMIT 1");
$stmt->execute(array(":user_id"=>$user_id));
$userRow=$stmt->fetch(PDO::FETCH_ASSOC);
$xxx = $userRow['xxx'];
$yyy = $userRow['yyy'];
$zzz = $userRow['zzz'];
$qqq = ($xxx * $yyy) + ($zzz + $yyy + $xxx);
$xres = array();
$xres[0] = $xxx;
$xres[1] = $yyy;
$xres[2] = $zzz;
$xres[3] = $qqq;
$result = json_encode($xres);
echo $result;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
}
Database return simple integer numbers. No triggers or decimal numbers.
jQuery version: 1.12.4 min.
Clicking every few second (no frequent clicking). Request and response complete in 10-38 ms.
The problem is somewhere in your button js as well as jQuery source. Try replacing textContent with innerHTML(for plain js) or html(JQuery)After replacement it would be
document.getElementById("x4").innerHTML = xres[3]; or as you are using jQuery you could have $("#x4").html(xres[3]).
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>');
});
});
});
I recently came upon a site that has done exactly what I want as far as pagination goes. I have the same basic setup as the site I just found.
I would like to have prev and next links to navigate through my portfolio. Each project would be in a separate file (1.php, 2.php, 3.php, etc.) For example, if I am on the 1.php page and I click "next project" it will take me to 2.php.
The site I am referencing to accomplishes this with javascript. I don't think it's jQuery:
function nextPg(step) {
var str = window.location.href;
if(pNum = str.match(/(\d+)\.php/i)){
pNum = pNum[1] * 1 + step+'';
if ((pNum<1) || (pNum > 20)) { pNum = 1; }
pNum = "".substr(0, 4-pNum.length)+pNum;
window.location = str.replace(/\d+\.php/i, pNum+'.php');
}
}
And then the HTML:
Next Project
I can't really decipher the code above, but I assume the script detects what page you are on and the injects a number into the next page link that is one higher than the current page.
I suppose I could copy this code but it seems like it's not the best solution. Is there a way to do this with php(for people with javascript turned off)? And if not, can this script be converted for use with jQuery?
Also, if it can be done with php, can it be done without dirty URLs?
For example, http://www.example.com/index.php?next=31
I would like to retain link-ability.
I have searched on stackoverflow on this topic. There are many questions about pagination within a page, but none about navigating to another page that I could find.
From your question you know how many pages there are going to be. From this I mean that the content for the pages themselves are hardcoded, and not dynamically loaded from a database.
If this is the approach you're going to take you can take the same course in your javascript: set an array up with the filenames that you will be requesting, and then attach event handlers to your prev/next buttons to cycle through the array. You will also need to keep track of the 'current' page, and check that incrementing/decrementing the current page will not take you out of the bounds of your page array.
My solution below does the loading of the next page via AJAX, and does not change the actual location of the browser. This seems like a better approach to me, but your situation may be different. If so, you can just replace the related AJAX calls with window.location = pages[curPage] statements.
jQuery: (untested)
$(function() {
var pages = [
'1.php',
'2.php',
'3.php'
];
var curPage = 0;
$('.next').bind('click', function() {
curPage++;
if(curPage > pages.length)
curPage = 0;
$.ajax({
url: pages[curPage],
success: function(html) {
$('#pageContentContainer').html(html);
}
});
});
$('.prev').bind('click', function() {
curPage--;
if(curPage < 0)
curPage = (pages.length -1);
$.ajax({
url: pages[curPage],
success: function(html) {
$('#pageContentContainer').html(html);
}
});
});
});
HTML:
<div id = "pageContentContainer">
This is the default content to display upon page load.
</div>
<a class = "prev">Previous</a>
<a class = "next">Next</a>
To migrate this solution to one that does not have the pages themselves hardcoded but instead loaded from an external database, you could simply write a PHP script that outputs a JSON encoded array of the pages, and then call that script via AJAX and parse the JSON to replace the pages array above.
var pages = [];
$.ajax({
url: '/ajax/pages.php',
success: function(json) {
pages = JSON.parse(json);
}
});
You can do this without ever effecting the structure of the URL.
Create a function too control the page flow, with an ajax call
function changePage(page){
$.ajax({
type: 'POST',
url: 'myPaginationFile.php',
data: 'page='+page,
success: function(data){
//work with the returned data.
}
});
}
This function MUST be created as a Global function.
Now we call the function on page load so we always land at the first page initially.
changePage('1');
Then we need to create a Pagination File to handle our requests, and output what we need.
<?php
//include whatever you need here. We'll use MySQL for this example
$page = $_REQUEST['page'];
if($page){
$q = $("SELECT * FROM my_table");
$cur_page = $page; // what page are we on
$per_page = 15; //how many results do we want to show per page?
$results = mysql_query($q) or die("MySQL Error:" .mysql_error()); //query
$num_rows = mysql_num_rows($result); // how many rows are returned
$prev_page = $page-1 // previous page is this page, minus 1 page.
$next_page = $page+1 //next page is this page, plus 1 page.
$page_start = (($per_page * $page)-$per_page); //where does our page index start
if($num_rows<=$per_page){
$num_pages = 1;
//we checked to see if the rows we received were less than 15.
//if true, then we only have 1 page.
}else if(($num_rows % $per_page)==0){
$num_pages = ($num_rows/$per_page);
}else{
$num_pages = ($num_rows/$per_page)+1;
$num_pages = (int)$num_pages;
}
$q. = "order by myColumn ASC LIMIT $page_start, $per_page";
//add our pagination, order by our column, sort it by ascending
$result = mysql_query($q) or die ("MySQL Error: ".mysql_error());
while($row = mysql_fetch_array($result){
echo $row[0].','.$row[1].','.$row[2];
if($prev_page){
echo ' Previous ';
for(i=1;$i<=$num_pages;$i++){
if($1 != $page){
echo "<a href=\"JavaScript:changePage('".$i."');\";> ".$i."</a>";
}else{
echo '<a class="current_page"><b>'.$i.'</a>';
}
}
if($page != $num_pages){
echo "<a class='next_link' href='#' id='next-".$next_page."'> Next </a>';
}
}
}
}
I choose to explicitly define the next and previous functions; so here we go with jQuery!
$(".prev_link").live('click', function(e){
e.preventDefault();//not modifying URL's here.
var page = $(this).attr("id");
var page = page.replace(/prev-/g, '');
changePage(page);
});
$(".next_link").live('click', function(e){
e.preventDefault(); // not modifying URL's here
var page = $(this).attr("id");
var page = page.replace(/next-/g, '');
changePage(page);
});
Then finally, we go back to our changePage function that we built initially and we set a target for our data to go to, preferably a DIV already existing within the DOM.
...
success: function(data){
$("#paginationDiv").html(data);
}
I hope this gives you at least some insight into how I'd perform pagination with ajax and php without modifying the URL bar.
Good luck!
I recently learned that when using onclick, for a button, the field name and button id have to each be unique. While thats not a problem, depending on how many rows my script outputs, this could be a lot of waste.
For example, i have a while loop, it does this for each person on my server (minecraft), so it could be 10, it could be 50.
this is the code to create the js objects
$kickbtn .= " $('#kick_btn$k').click(function(event) {
var player_name$k = jQuery('input[name=\"player$k\"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name$k} );
alert('Successfully kicked');
});\n\n";
this is the form data
<form name=\"$pdata[name]\" action=\"\">
<input type=\"hidden\" name=\"player$k\" value=\"$pdata[name]\">
<input type=\"submit\" id=\"kick_btn$k\" value=\"Kick Player\">
</form>
$k++;
Is there an easier way to accomplish this without creating all this excess code?
The output is nice in the html, and it does work, just hoping theres something a little more dynamic i can do, and not so messy in the code. Below is from the parsed code and works and looks good.
$('#kick_btn14').click(function(event) {
var player_name14 = jQuery('input[name="player14"]').val()
jQuery.get('testing.php?action=kick', { player_input: player_name14} );
alert('Successfully kicked');
});
Only one delegated event handler is needed, which means attaching it to a parent/container element, unless you want 50+ click handlers in your document which will unnecessarily slow things down:
// bind to all elements starting with 'kick_btn' within #container
// (could even be 'body')
$("#container").delegate('[id^="kick_btn"]', "click", function(event) {
// get the current player number from the id of the clicked button
var num = this.id.replace("kick_btn", "");
var player_name = jQuery('input[name="player' + num + '"]').val();
jQuery.get('testing.php?action=kick', {
player_input: player_name + num
});
alert('Successfully kicked');
});
Reference:
http://api.jquery.com/attribute-starts-with-selector/
http://api.jquery.com/delegate/
I am trying to do pagination using javascript but all in vain, please help..
<script language="Javascript">
function nextclicked()
{
document.getElementById("clickednext").value = document.getElementById("clickednext").value + 1;
document.forms["newsmanager"].submit();
}
</script>
<form name = "newsmanager" method="post" action="NewsManager.php">
<input type = "hidden" id="clickednext" name="clickednext" >
if(isset($_POST['clickednext']) && $_POST['clickednext']>=1)
{
$_POST['clickednext'] = $_POST['clickednext'] +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .$_POST['clickednext']. ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
UPDATE :
<div class=d2 align=left>
<a href="#" onclick=" nextclicked(); submit();" >
Next
</a>
UPDATE ENDS......
The first time when i click the Next hyperlink label, then it works, that is, 10 is assigned $_POST['clickednext'] and the next 10 values appear from the database, but the second time i click the label , then it doesn't?
Your code is completely wrong.
You should scrap it and start all over again.
I will show you how to do so.
I have a rule when it comes to Ajax, and it goes like this.
If you cannot do the functionality without Ajax, there's no way you should attempt to do it with Ajax.
If you know anything about javascript, you'll know that XmlHttpRequest makes working with Ajax hellish. Hence why we have javascript frameworks such as JQuery and Mootools. You might also like a php ajax framework called PHPLiveX. I only use JQuery, so here's how to do the solution in JQuery.
Step 1: Strip your ajax and create the solution in php
This pagination tutorial in php will help.
Step 2a: Create the ajax with PHPLiveX
PHPLiveX is really cool and underated, as it allows you to use php functions without reloading the whole page, in a more convienient way, than if you'd used javascript.
PHPLiveX will help you the best.
It's pretty straightforward. You call a php function to do something, return some values, and choose the target: of where you want the values to go.
I personally would use PHPLiveX for this job, as it's better suited. JQuery is more for postdata.
Step 2b: Create the ajax in JQuery
I'm going to assume that you know how to select elements by id with JQuery and append or replaceWith them. If not you can look the function up.
Below is the code required to submit a POST or GET with JQuery. Adapt this to your code. You'll have to modify the code below to add appending and stuff.
$(".tornfieldcard").click(function() {
var dataString = $("#addfieldForm").serialize();
//lets get the form data and use that
var newValue = $("#newValue").val();
var itemid4 = $(this).attr("itemid4");
var dataString = "itemid=" + itemid + "&newValue=" + newValue;
//or get the attr/valu from elements
$("#loading5").show();
$("#loading5").fadeIn(400).html('<img src="icons/loading.gif">');
$.ajax({
type: "POST",
url: "ajaxcontrols.php",
data: dataString,
cache: false,
success: function(html){
$("#loading5").remove();
$(".fieldcardNEW").fadeOut('slow');
$('.fieldcardNEW').remove();
$("#conveyorbelt_"+itemid4+"").append("<div class=\"fieldcard\"><b>"+attribute+"</b> <br><div itemid=\""+itemid4+"\" attribute=\""+attribute+"\">"+value+"</div></div>");
}
});
Here's a little algorithm I wrote using php to create pagination:
$x=$numStories;
$y=$x%5;
$z=($x-$y)/5;
if($y!=0){
$numPages=$z+1;
}
else{
$numPages=$z;
}
Where 5 is the number of stories per page, and $numStories is the total amount of stories (or in your case, news articles) you wish to use.
Then, just display the amount of pages ($numPages) in any way you'd like, and your good to go.
[EDIT]
I created an archive.php page, that took a page number as a GET parameter (archive.php?page=3). From there, I selected the first five entries in my database after $pageNum (in this case 3) * 10 (or however many posts per page you are wanting to display.
The best thing to do is make as much of your code dynamic and flexible, so that it is self sustaining.
[EDIT 2]
<script>
function nextclicked()
{
document.forms["newsmanager"].submit();
}
</script>
<?php
$currentPage = $_POST['page'];
$numStories = //get the total amount of entries
$x=$numStories;
$y=$x%10;
$z=($x-$y)/10;
if($y!=0){
$numPages=$z+1;
}
else{
$numPages=$z;
}
if(isset($currentPage) && $currentPage>=1)
{
$currentPage = $currentPage +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .$currentPage. ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
?>
<form>
<input type='hidden' name='page' text='' value='<?php echo "$currentPage"' />
</form>
Next-->
PHP is server-side language. you have to put your php code to
<?php
=====
<script language="Javascript">
function nextclicked()
{
document.getElementById("next").value = document.getElementById("next").value + 1;
document.forms["newsmanager"].submit();
}
</script>
<form name = "newsmanager" method="post" action="NewsManager.php">
<input type = "hidden" id="clickednext" name="clickednext" >
<?php
if(isset($_POST['clickednext']) && $_POST['clickednext']>=1)
{
$_POST['clickednext'] = $_POST['clickednext'] +9;
$NewsQuery = "SELECT NewsDetails FROM News LIMIT " .intval($_POST['clickednext']). ",10";
}
else
{
$NewsQuery = "SELECT NewsDetails FROM News LIMIT 0,10";
}
$result = mysqli_query($dbc,$NewsQuery);
}
?>
additionally, user can't click to hidden form field. you need, for example button and have onclick event ready
<button name="next" value="1" onclick="nextclicked();">Next</button>