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>
Related
So I've got a data table that is updated with two different sets of buttons. The jquery is thus;
$('body').on('click', "button", function () {
var $but_name = $(this).attr("name");
var $but_id = $(this).attr("id");
if($but_name==="sky_week") {
$("#adv_stats").load("index.php #adv_stats", {this_week:$but_id});
} else if($but_name==="ASC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"ASC",sort_type:$but_id});
} else if($but_name==="DESC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"DESC",sort_type:$but_id});
}
});
It literally just grabs the id of the button clicked and passes what was clicked to the load to refresh the data table.
(On an unrelated note, I'm new to jquery but I've got my load pointing at itself. So index.php is the page the code is on and I've just got it pointing at a div lower down to update that. It works - and shouldn't get stuck on an infinite loop because it's only triggered on clicks - but I feel like it's wrong and bad coding. Can someone confirm or deny this?)
The issue I have is that when you click the ASC or DESC buttons, it doesn't pull the week through because that's on a different button. I think it's because of the PHP at the top of the page that pulls it;
$this_week = $_POST['this_week'] ?? '202118';
$up_down = $_POST['up_down_type'] ?? 'ASC';
$sort = $_POST['sort_type'] ?? 'nt_login';
$breakdown = get_adv_breakdown($this_week, $sort, $up_down);
And it's because of the '?? '202118' bit, which is defaulting to 202118 as the week instead of the currently selected week.
How do I get it to update the ASC values and keep the currently selected week? I feel like I need to somehow store the week somewhere else, but this is hitting the limit of my jquery knowledge.
Here's a visual of the final page, showing the two different sets of buttons;
https://i.stack.imgur.com/UU8Kd.png
I've added the html that generates the buttons;
<td align="center">Advisor<button name="ASC" id="nt_login"><i class="arrow up"></i></button><button name="DESC" id="nt_login"><i class="arrow down"></button></td>
etc
etc
And a little loop that adds the last 12 weeks;
<div id="week-buttons">
<p align="center"><?php foreach($no_weeks as $week) { ?>
<button name="sky_week" class="sky-primary-button w-button" id='<?php echo h($week['Week']); ?>' onclick="this.blur();">
<?php echo h($week['Week']); ?>
</button>
<?php } ?></p>
</div>
It looks like you are reloading your page whenever you do a sort. In order to preserve the value of $this_week you will need to pass that as a $_POST value to your page when you fire .load()
It should be as simple as doing something like this:
$('body').on('click', "button", function () {
var $but_name = $(this).attr("name");
var $but_id = $(this).attr("id");
if($but_name==="sky_week") {
$("#adv_stats").load("index.php #adv_stats", {this_week:$but_id}); // this seems to be an error?
} else if($but_name==="ASC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"ASC",sort_type:$but_id, this_week: $this_week});
} else if($but_name==="DESC") {
$("#adv_stats").load("index.php #adv_stats", {up_down_type:"DESC",sort_type:$but_id, this_week: $this_week});
}
});
I'm developing a kind of question search engine based on Course wise, Subject wise by entering the keyword or question.
Here I am querying the database based on search term against 3 tables namely table_one, table_two, and table_three. Code as follows
<?php
if(isset($_GET['submit']))
{
$query = $_GET['query'];
$query = htmlspecialchars($query);
$query = mysqli_escape_string($link,$query);
$searchTerms = explode(' ', $query);
$searchTermBits = array();
foreach ($searchTerms as $term) {
$term = trim($term);
if (!empty($term)) {
$searchTermBits[] = "question LIKE '%$term%'";
}
}
$subject_id = $_GET['subject'];
$course_id = $_GET['course'];
$min_length = 1;
if(strlen($query) >= $min_length)
{
$res = "SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_one
WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')
UNION ALL
SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_two
WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')
UNION ALL
SELECT id,course_id,subject_id,question,option_a,option_b,option_c,option_d,option_e,correct_ans,fmge_year,contributor FROM table_three
WHERE (".implode(' OR ', $searchTermBits).") AND (`subject_id` LIKE '%".$subject_id."%') AND (`course_id` LIKE '%".$course_id."%')";
$raw_results = mysqli_query($link,$res) or die (mysqli_error());
if(mysqli_num_rows($raw_results) > 0)
{
echo "<h3 style='text-align:center;color:#3366CC'><span style='color:#000000'>Search Results For : </span> $query </h3>";
while($results = mysqli_fetch_array($raw_results))
{
echo "<div class='content'>";
echo"<h4 id=".$results['id'].">" .preg_replace("/".preg_quote($query, "/")."/i", "<span class=\"highlight\">$query</span>", $results['question']) . "</h4>";
echo"<p id=".$results['id']."><span style='padding-left:20px'>option A : " .$results['option_a']."</span> <br><span style='padding-left:20px'> option B : ".$results['option_b']."</span><br/><span style='padding-left:20px'>option C : ".$results['option_c'].
"</span><br><span style='padding-left:20px'>option D : ".$results['option_d']."</span><br><span style='padding-left:20px'> option E : ".$results['option_e']."</span><br><span style='color:#253E66;font-weight:bold;padding-left:20px'>Correct Ans : ".$results['correct_ans'].
"</span><br><span style='padding-left:20px'>Question Year : ".$results['question_year']."</span><br><span style='padding-left:20px'>Contributor : ".$results['contributor']."</span><br />
<a onclick=addQuestion('".$results['id']."') href='#'><span class='button'>Add to Question Bank</span></a></p>";
echo "</div>";
}
}
else{
echo "<span style='height:21px;syle=background-color: #F1F0FF;font-size:25px;color:#CC0000'>Your search - $query - did not match any queries.</span> ";
}
}
}
?>
I'm Calling the following addQuestion() function when i click the Add to Question Bank link.
<script>
function addQuestion(val)
{
var conf=confirm("Are you sure you want to add this question to Question Bank")
if(conf){
//Here I Want some code to update my database.
}
}
</script>
The script above displaying confirmation box when i click the button,
My Question is,
After confirmation I want to insert my question into the new table in the database and display message like "Question added" in front of the question permanently as i know i can't write PHP inside Jquery function Any help may appreciated.
You can achieve this by including the ajax.
put the ajax code which may looks like the following:
if(conf){
$.ajax({
type: "POST",
url: "$$phpfilepath",
data: {param:'$$value'},
success: function(data) {
// do the message display code
}
});
}
Don't forget to include the jquery cdn link in the head tag of the html page.
you need to send an ajax request.
you need to send it either by a post or get method to a php script that will return json so you can be updated on the page with results.
the answer above has an example ajax script sent with a post method:
data needs to be sielized if you are submitting it via form or an array.
this should help you
http://www.w3schools.com/php/php_ajax_database.asp
https://api.jquery.com/serialize/
Onclick - You need to do that with ajax. So basically, you need PHP plus javascript involved. You can use Jquery of similar JS library for easy ajax support.
Just and example with jquery library version 1.11.2 how to include:
<head>
<script src="jquery-1.11.2.min.js"></script>
</head>
For example, if this is your input field you want to save and button for submitting:
<input id="title" name="title" />
<input type="submit" value="Save">
Change it to button and give it javascript save() function (can be any name you give).
<input type="button" onclick="save($('#title').val());" value="Save">
In this example, I added 1 param to that save function, which is supposed to grab a value from html input filed with id "title".
On this page, there that html is, you need to include mentioned jquery(or similar) library and also include piece of javascript function for generating ajax request, which is named "save" here.
If you included jquery library, you must call javascript function for saving your data before your tag:
<script type"text/javascript">
function save(){
$.ajax({
type: "POST",
url: "yourpath/yourfile.php",
data: {title: title},
success: function(data) {
alert("Ajax save executed!");
}
});
}
</script>
When javascript function you named save() will execute, it will send POST request to yourpath/yourfile.php
There, you can easily get your POST data by in yourpath/yourfile.php:
if(isset($_POST['title'])){
// do something with POST data, save in db.. (make sure to include security when inserting to db)
}
If you want to send it with GET, you easily replace POST with GET:
function save(){
$.ajax({
type: "GET",
and also in .php file you write:
if(isset($_GET['title'])){
// do something with POST data, save in db.. (make sure to include security when inserting to db)
}
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!
Javascript:
var counter = 1;
var limit = 5;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var newdiv = document.createElement('div');
newdiv.innerHTML = " <br><select name='vehicle[]' id = 'vehicle'><option value = ''>Vehicle "+ (counter + 1) +"</option><option value = '.$brand.' '.$name.'>'.$brand.' '.$name.'</option>";
document.getElementById(divName).appendChild(newdiv);
counter++;
}
}
PHP/HTML:
<script type = "text/javascript" src="js/addinput.js"></script>
<form name="form1" method="POST" action="services.php" onsubmit="return valid()">
<br><br><br><center>
<table class="form" border=1>
<tr>
<td class="head" colspan="2" >Select Vehicle:</td>
</tr>
<tr ></tr>
<tr>
<td colspan="2" class="info">
<div id="dynamicInput">
<br><select name = "vehicle[]" id = "vehicle1">
<option value = "">Vehicle 1</option>';
include_once "vehicledbconnect.php";
$queryveh = mysql_query("SELECT * FROM vehicletbl");
while($fetch_2 = mysql_fetch_array($queryveh)) {
$brand = $fetch_2['vehbrand'];
$name = $fetch_2['vehname'];
echo '<option value = "'.$brand.' '.$name.'">'.$brand.' '.$name.'</option>';
}
echo '</select>';
echo '<input type="button" value="Add another vehicle" onClick="addInput(\'dynamicInput\');"></div>';
Hi. Is it possible to insert PHP values in a javascript? I have a program here that if the customer click the submit button (echo '), a new drop-down form will appear. And I want the drop down form to contain all of the values of the query ($queryveh = mysql_query("SELECT * FROM vehicletbl");). In my default drop-down form, all values of the query are shown. Please help me guys. I am desperate for an answer. Javascript is my weakness. Thanks a lot.
edit:
newdiv.innerHTML = " <br><select name='vehicle[]' id = 'vehicle'><option value = ''>Vehicle "+ (counter + 1) +"</option>" + "<?php include 'vehicledbconnect.php'; $queryveh = mysql_query('SELECT * FROM vehicletbl'); while($fetch_2 = mysql_fetch_array($queryveh)) { $brand = $fetch_2['vehbrand']; $name = $fetch_2['vehname']; <option value = '.$brand.' '.$name.'>'.$brand.' '.$name.'</option> }?>";
Can this be the solution? I've tried but it's not working, if this can be the solution, maybe there's only something wrong with my code here.
The only way to retrieve values from a server from javascript is to use AJAX.
Well you can do it without AJAX if you don't mind a page refresh, but I don't think that is what you want.
I would use a jQuery load function. This is the simplest example I can muster up for you.
You will need to download jQuery (http://docs.jquery.com/Downloading_jQuery) and include it in your html header:
<script type="text/javascript" src="js/jquery-1.4.2.min.js"></script>
Then you can make a simple function to call; either as a onclick or onchange depending on your preference.
function reloadDropDown()
{
document.getElementById('dynamicInput').innerHTML = 'Loading ...';
var v_name = document.formname.elementname.value;
$('#dynamicInput').load("dropdownload.php", { vehicle_name : v_name });
}
Let me go through this. dropdownload.php would have your '$queryveh' made drop down code. Javascript basically plonks whatever happens in dropdownload.php on to a div with the id 'dynamicInput' When javascript loads dropdownload.php it sends via POST a variable by the name vehicle_name which you can use as $_POST['vehicle_name'] within dropdownload.php.
So, dropdownload.php may look something like this.
<?php
$queryveh = mysql_query("SELECT * FROM vehicletbl WHERE vehname = '{$_POST['vehicle_name']}'");
// collect the data and put it in to an Array I like to do this so I can check the array to make sure it has something in it if not return an error message but I will skip that for the purpose of this explanation.
while($ucRow = mysql_fetch_array($queryveh, MYSQL_ASSOC)) array_push($resultsArray, $ucRow);
?>
<select name = "vehicle[]" id = "vehicle1">
<?php
foreach ($resultsArray as $fetch_row){
?>
<option value = "<?php echo $fetch_row['vehbrand'].' '.$fetch_row['vehname'].'; ?>"><?php echo $fetch_row['vehbrand'].' '.$fetch_row['vehname']; ?></option>
<?php } ?>
</select>
?>
I'm not entirely certain on the end result you are after but that is a basic jQuery ajax call. If you can grasp that, you are half way to a truly dynamic web page / app with some further practice with this area. Hope that gives you a direction to go in :)
JavaScript gets evaluated on the client ..so like Html ..so it is to be used the same way.
-> yes, you just use php in your javascript as long as its defined to be evaluated by php first (usually within a .php file)
edit:
just to clarify, if you want to get values within javascript from the server by php.. you need to have a look at what danishgoel said: Ajax (Asynchronous JavaScript) ..see - since Rikudo Sennin disrespected the link, another http://en.wikipedia.org/wiki/XMLHttpRequest ..or even better have a look at a javascript framework that does most of the stuff for you (f.e. jQuery)
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>