This is my first post, but I've been using the site for years. However, I'm stuck on what should be a fairly simple problem with pagination. I have a group of links being populated with php,
function create_pagination($page,$echo=false)
{
$max_rows = isset($_SESSION['maxListViewRows']) ? $_SESSION['maxListViewRows'] : 15;
$total_rows = isset($_SESSION['total_rows']) ? $_SESSION['total_rows'] : 1;
$pages = ceil($total_rows / $max_rows);
if( $page > $pages) $page = $pages;
$start_row = $page == 1 ? 1 : ( ($page - 1) * $max_rows ) + 1;
$rows_disp = ($start_row + $max_rows) <= $total_rows ? ($start_row + $max_rows) - 1 : $total_rows;
$facility_number_summary = 'Showing ' . $start_row . ' - ' . $rows_disp . ' of ' . $total_rows . ' rows.<br /> <p class="carapg">(MESSAGE IRRELEVANT TO THE QUESTION)</p>';
$pagination_functions = '';
for($i = 1; $i <= $pages; $i++)
{
$pagination_functions.= $i != $page ? '' . $i . ''
: '<span class="page_link" id="page_' . $i . '">' . $i . '</span>';
}
$results = array('facility_number_summary'=>$facility_number_summary, 'pagination_functions'=>$pagination_functions);
$returned = '<div id="max_left">' . $results['facility_number_summary'] . '</div>
<div id="max_right">' . $results['pagination_functions'] . '</div>
<div class="break"></div>';
if( $echo ){ echo $returned; return; }
return $returned;
}
And after that, I parse the div with jquery and compress them.
function draw_pagination(page)
{
if(page == undefined){
page = 1;
}
var postData = { 'ajax' : 'pagination',
'page' : page };
$.ajax({
type : "POST",
url : "/ajax/account.php",
data : postData,
success :
function(data){
$("#fac_results_max").html(data);
get_page_count();
}
});
}
function get_page_count()
{
var count = $("#max_right").children().length;
if( count < 11 )
return;
var content = '';
var spacer = false;
$("#max_right").children().each(
function(index)
{
if( $(this).html() > 5 && $(this).html() <= ( count - 5 ) )
{
$(this).css('display','none');
if( !spacer )
{
content += '...';
spacer = true;
}
}
else
{
content += $(this).html();
}
}
);
$("#max_right").html(content);
}
I am going to take the elements that are hidden and append them to a div that drops down so that the user can select from them. The problem I'm having is the
content += $(this).html()
It is only returning the inside of the html, as I expect it to, but I don't know what to call on it to return the actual html of the entire element referred to by 'this'. Sorry if it's a dumb question, but I'm stumped.
Thanks in advance for your responses.
Try this:
content += $(this).clone().wrap('<div>').parent().html();
AFAIK, there exists no nice way to get the contents AND the tags of the element using jQuery, so instead we clone the element, wrap it in <div> tags, bump up to the parent (the <div>) and then get its html.
WHy not just use $('#target').append($(this)); ?
If you want the whol element, and not the HTML of the first child then just use the element.
http://api.jquery.com/category/attributes/
content += $(this).parent().html();
And give the element 'this' a dummy wrapper.
Or also try, but it may be unrelated
content += $(this).contents();
I don't see any need to turn individual elements into html strings. Simply use some math and slice() method.
http://api.jquery.com/slice/
EDIT: you should actually do this before inserting the return in your ajax success. Can manipulate the returned html without needing to insert it, then insert after manipulation
Example isn't 100% fine tuned but will look something like this
function get_page_count()
{
/* cache jQuery objects when needing to search them again for efficiency*/
var $max=$("#max_right"), $kids=$max.children()
var count = $kids.length;
if( count < 11 )
return;
var $temp=$('<div/>').append( $kids.slice(0,5)).append('...').append( $kids.slice(- 5,-1));
$max.html(temp.html());
}
Related
In the view, right before the footer, I want to load three JavaScript files. So, the controller sets three variables. For example, $js_1 = "bootstrap.js", $js_2 = '' and $js_3 = "tinymce.js", which may or may not be empty. The logic is, it should echo only if the variable is not empty. I also want to use the ternary if operator.
This was the best I could try.
for ($i = 1; $i <= 3; $i++)
{
echo (!empty ('$js_' . $i)) ? get_jscript('$js_' . $i) : NULL;
}
The function get_jscript() simply returns the HTML script src.
function get_jscript($js)
{
return '<script type="text/javascript" src="' . $js . '"></script> ';
}
Please note that I intend to ask this question to primarily learn the correct PHP syntax and not just load JS in the view.
if you can create a array like this->
$javascript = array('js_1' => "bootstrap.js", 'js_2' => '', 'js_3' = "tinymce.js");
then in your view you have to just call a method
loop_javascript($javascript);
it's better to create a function in codeigniter helper and call that helper in controller's function (check how to use helpers in codeingiter) https://ellislab.com/codeigniter/user-guide/general/helpers.html->
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
if ( ! function_exists('loop_javascript'))
{
function loop_javascript($jscript_array)
{
foreach($jscript_array as $key =>$value){
if($value != ''){
echo '<script type="text/javascript" src="' . $value. '"></script>';
}
}
}
}
This has some great info on how to use variable variables.
for ($i = 1; $i <= 3; $i++)
{
echo (!empty (${'js_'.$i})) ? get_jscript(${'js_'.$i}) : NULL;
}
for ($i = 1; $i <= 3; $i++)
{
if(!empty($js.'_'.$i)){ echo get_jscript($js.'_'.$i); echo "</br>";}
}
function get_jscript($js)
{
return '<script type="text/javascript" src="' . $js . '"></script> ';
}
We have a form that Span Across multiple pages and the form is full of checkboxes and radio-buttons. Requirement is that when a user navigates across multiple pages of the form, the user should be able to see the checkboxes and radio-buttons he has already Selected before the form Submit button is pressed.
I am copying the code segement that is used to generate the Checkboxes in the form - this is a Sample code Only.
<form action="car_model.php" method="post" name="car_form" id="car_form">
$q10 = "SELECT ...
$r10 = mysqli_query ($dbc, $q10);
if (mysqli_num_rows($r10) > 0) {
while ($row10 = mysqli_fetch_array($r10, MYSQLI_ASSOC))
{
echo '<p class="normal_text"><input type="checkbox" name="model_selection[]" value="' . $row10['model_id'] . '" onclick="return KeepCount()"; />' . $row10['car_model_name'] . '</p></br>';
}
}
</form>
if ($pages > 1) {
echo '<br /><p>';
// Determine what page the script is on:
$current_page = ($start/$display) + 1;
// If it's not the first page, make a Previous button:
if ($current_page != 1) {
echo 'Previous ';
}
// Make all the numbered pages:
for ($i = 1; $i <= $pages; $i++) {
if ($i != $current_page) {
echo '' . $i . ' ';
} else {
echo $i . ' ';
}
}
// If it's not the last page, make a Next button:
if ($current_page != $pages) {
echo 'Next';
}
echo '</p>';
}
I understand that JQuery is a Good tool for this purpose - how to use it?
If using server side session variables is not an option then you could implement it in such a way that when you click "next" instead of loading a new page you just hide the current content place holder of the visible part of the form and show the next one at it's place and the same when clicking back.
This can easily be done with jQuery. Here is a very simple example to get you started:
$("#next").click( function () {
$("#page1").hide();
$("#page2").show();
});
$("#back").click( function () {
$("#page1").show();
$("#page2").hide();
});
Fiddle
Good luck!
I am currently using the plugin WP-CommentNavi for comments pagination but whenever a page is clicked it goes to the highest comments page (oldest comments). My comments are purposely displayed newest first and therefore I need the default pagination page to be 1 whenever a link is clicked.
I notice there is the same default for other pagination plugins too whereby the highest pagination page (ie if there are 5 pages) page 5 is displayed.
At the moment when I load page tellhi####.com/newcastle the page that will be loaded is tellhi####.com/newcastle/comment-page-2/ whereas I want tellhi####.com/newcastle/comment-page-1/ to be loaded
I can't be sure this is the relevant code to what I am trying to achieve but I feel the answer might lie in here (below). If not, please tell me and disregard this code.
### Function: Comment Navigation: Boxed Style Paging
function wp_commentnavi($before = '', $after = '') {
global $wp_query;
$comments_per_page = intval(get_query_var('comments_per_page'));
$paged = intval(get_query_var('cpage'));
$commentnavi_options = get_option('commentnavi_options');
$numcomments = intval($wp_query->comment_count);
$max_page = intval($wp_query->max_num_comment_pages);
if(empty($paged) || $paged == 0) {
$paged = 1;
}
$pages_to_show = intval($commentnavi_options['num_pages']);
$pages_to_show_minus_1 = $pages_to_show-1;
$half_page_start = floor($pages_to_show_minus_1/2);
$half_page_end = ceil($pages_to_show_minus_1/2);
$start_page = $paged - $half_page_start;
if($start_page <= 0) {
$start_page = 1;
}
$end_page = $paged + $half_page_end;
if(($end_page - $start_page) != $pages_to_show_minus_1) {
$end_page = $start_page + $pages_to_show_minus_1;
}
if($end_page > $max_page) {
$start_page = $max_page - $pages_to_show_minus_1;
$end_page = $max_page;
}
if($start_page <= 0) {
$start_page = 1;
}
if($max_page > 1 || intval($commentnavi_options['always_show']) == 1) {
$pages_text = str_replace("%CURRENT_PAGE%", number_format_i18n($paged), $commentnavi_options['pages_text']);
$pages_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $pages_text);
echo $before.'<div class="wp-commentnavi">'."\n";
switch(intval($commentnavi_options['style'])) {
case 1:
if(!empty($pages_text)) {
echo '<span class="pages">'.$pages_text.'</span>';
}
if ($start_page >= 2 && $pages_to_show < $max_page) {
$first_page_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $commentnavi_options['first_text']);
echo ''.$first_page_text.'';
if(!empty($commentnavi_options['dotleft_text'])) {
echo '<span class="extend">'.$commentnavi_options['dotleft_text'].'</span>';
}
}
previous_comments_link($commentnavi_options['prev_text']);
for($i = $start_page; $i <= $end_page; $i++) {
if($i == $paged) {
$current_page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $commentnavi_options['current_text']);
echo '<span class="current">'.$current_page_text.'</span>';
} else {
$page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $commentnavi_options['page_text']);
echo ''.$page_text.'';
}
}
next_comments_link($commentnavi_options['next_text'], $max_page);
if ($end_page < $max_page) {
if(!empty($commentnavi_options['dotright_text'])) {
echo '<span class="extend">'.$commentnavi_options['dotright_text'].'</span>';
}
$last_page_text = str_replace("%TOTAL_PAGES%", number_format_i18n($max_page), $commentnavi_options['last_text']);
echo ''.$last_page_text.'';
}
break;
case 2;
echo '<form action="'.admin_url('admin.php?page='.plugin_basename(__FILE__)).'" method="get">'."\n";
echo '<select size="1" onchange="document.location.href = this.options[this.selectedIndex].value;">'."\n";
for($i = 1; $i <= $max_page; $i++) {
$page_num = $i;
if($page_num == 1) {
$page_num = 0;
}
if($i == $paged) {
$current_page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $commentnavi_options['current_text']);
echo '<option value="'.clean_url(get_comments_pagenum_link($page_num)).'" selected="selected" class="current">'.$current_page_text."</option>\n";
} else {
$page_text = str_replace("%PAGE_NUMBER%", number_format_i18n($i), $commentnavi_options['page_text']);
echo '<option value="'.clean_url(get_comments_pagenum_link($page_num)).'">'.$page_text."</option>\n";
}
}
echo "</select>\n";
echo "</form>\n";
break;
}
echo '</div>'.$after."\n";
}
}
In short I need, anytime a page is clicked, for the comments pagination to be on page 1, not the highest page available. Just so you know I have tried the discussion settings on the wordpress dashboard. Nothing on google either!
Failing a full answer, does anyone know the actual php code that determines what pagination page is loaded by default?
I received this response via an e-mail but due to my PHP knowledge am unable to implement it, any ideas? ...
Just reverse the loop. That'll fix it. Here's the relevant part:
http://pastie.org/8166399 You need to go back, i.e. use $i--
Would this change the default start page or just reverse the comments? Hope I have been clear in my question! Will appreciate any response at all.
Thanks in advance, Paul
The option was in Wordpress all along. See picture: http://oi40.tinypic.com/35aj3pt.jpg
If anyone has the answer to the specific code you manipulate, still answer the question here because someone doing this without Wordpress could very well encounter this problem also.
I have a comics website. A feature it has is to allow users to search comics... the search will instantly parse the input and return thumbnail results based on matching title and keywords.
Originally, the search would return all of the results, and the bounding search box would expand infinitely downward, holding every single comic result. I thought it may be a nice touch to limit the results to 4, and display a message like "load 5 remaining images" if the user chooses to do so.
If they click on that message, I wanted limiting php variable to be removed or changed.
So far, it loads with the limit, and shows a link...
EDIT: Latest Code:
search_field.php (the search file that get's included on a page... this file calls search.php via JQuery):
<?php $site = (isset($_GET['site']) ? ($_GET['site']) : null); ?>
<div id="sidebar" class="searchborder">
<!--Allow users to search for comic-->
<!--<span class="search">Search for <?php// echo (($site == "artwork") ? 'artwork' : 'a comic'); ?> </span>-->
<script type="text/javascript">
function GetSearch(mySearchString){
$.get("./scripts/search.php", {_input : mySearchString, _site : '<?php echo $site ?>'},
function(returned_data) {
$("#output").html(returned_data);
}
);
}
</script>
<center>
<table>
<tr>
<td>
<span class="search">
<img src="./images/SiteDesign/Search.png" />
<input type="text" onkeyup="GetSearch(this.value)" name="input" value="" />
<!--<input id="site" type="hidden" value="<?php// echo $site; ?>">-->
</span>
</td>
</tr>
</table>
</center>
<span id="output"> </span>
</div>
search.php, the file that's called to parse the string and return the results:
<?php
//Query all images:
include 'dbconnect.php';
$site = $_GET['_site'];
$input = (isset($_GET['_input']) ? ($_GET['_input']) : 0);
$siteChoice = (isset($_GET['_choice']) ? ($_GET['_choice']) : $site);
$start = (isset($_GET['_start']) ? ($_GET['_start']) : null);
echo "start: " . $start;
//if user goes to hittingtreeswithsticks.com... no "site" value will be set... so I need to set one
if ($site == null) {
$site = "comics";
}
if ($siteChoice == "artwork") {
$sql = "SELECT id, title, keywords, thumb FROM artwork";
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else if ($siteChoice == "comics") {
$sql = "SELECT id, title, keywords, thumb FROM comics";
$thumbpath = "./images/Comics/ComicThumbnails/";
}
else {
$sql = "SELECT id, title, keywords, thumb FROM $site";
if ($site == "artwork") {
$thumbpath = "./images/Artwork/ArtThumbnails/";
}
else {
$thumbpath = "./images/Comics/ComicThumbnails/";
}
}
/* For this to work, need all comics replicated in an "All Comics" file along with "All Thumbnails"
else {
$sql = "SELECT id, title, thumb FROM comics
UNION
SELECT id, title, thumb FROM artwork";
$thumbpath = "./images/AllThumbnails/";
}*/
$imgpaths = $mysqli->query($sql);
mysqli_close($mysqli);
$idresult = array();
$imgresult = array();
$thumbresult = array();
//CHECK IF $INPUT == IMAGE PATH
if (strlen($input) > 0)
{
while ($row = $imgpaths->fetch_assoc())
{
//query against key words, not the image title (no one will remember the title)
if (stripos($row['keywords'], $input) !== false || strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
//if (strtolower($input)==strtolower(substr($row['title'],0,strlen($input))))
{
array_push($idresult, $row['id']);
array_push($imgresult, $row['title']);
array_push($thumbresult, $row['thumb']);
}
}
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
if (count($imgresult) > $max) {
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo "<br/><i><a href='.?action=homepage&site=" . $siteChoice . "&start=4' class='loadSearch'>load " . $difference . " more result" . (($difference != 1) ? 's' : '') . "... </a></i>";
}
else {
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
}
echo "</ul>";
}
}
?>
<script type="text/javascript">
$(".loadSearch").click(function() {
//alert("Test");
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
});
</script>
Try this:
<script type="text/javascript">
$("#loadSearch").click(function() {
$.get('URL WITH QUERY', function(data) {
$('#results').html(data);
});
});
</script>
From what i get all you need is when "load more" is clicked only new results should be shown.
Load more has to be a url same as your search url.
Search/Autocomplete URL - example.com/autocomplete?q=xkd
Load More URL - example.com/autocomplete?q=xkd&start=4&max=1000
Just add two parameters to your url. start and max. Pass them to your queries and you get exact result.
Only verify Start < Max and are integers intval() and not 0 empty(). Also if Max <= 4 then dont show load more.
I would give all of your results back, then try to determine your results. If more then 4, loop out the first 4 results. If the user clicks on the load more button your start looping from your 4th element. That way you only need to hit the server once (per search).
Try to give back your results in json, so you can format it the way you like in your html file.
In pseudo code:
searchTerm = 'hello';
resultsFromServer = getResults($searchterm);
resultcounter = count(resultsFromServer);
if(resultcounter > 4)
loop 4 results
else
loop all results
$(".loadSearch").click(function(e) {
//alert("Test");
e.preventDefault();
$.get("./search.php", {_start : 4},
function (returned_data) {
$("#moreResults").html(returned_data);
}
);
I ended up going with jquery show and hide functions.
PHP Snippet:
//ECHO RESULTS ARRAY
if(count($imgresult) == 0)
{
echo "<p>no suggestions</p>";
}
else
{
echo "<ul>";
$k = 0;
$max = 4;
while ($k < count($imgresult) && $k < $max)
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
$difference = count($imgresult)-$k;
echo '<div id="moreResults">';
while ($k < count($imgresult))
{
echo '<li>
<span class="sidebarimages"><a href=".?action=viewimage&site=' . $siteChoice . '&id=' . $idresult[$k] . '">
<img src="./scripts/thumber.php?img=.'.$thumbpath.$thumbresult[$k].'&mw=90&mh=90"/></a></span>
</li>';
$k++;
}
echo '</div>';
if (count($imgresult) > $max) {
?>
<br />Load <?php echo $difference; ?> more result<?php echo (($difference != 1) ? 's' : ''); ?>...
<?php
}
echo "</ul>";
}
}
Jquery:
<script type="text/javascript">
$("#moreResults").hide();
$("#showMore").click(function() {
$("#moreResults").show();
$("#showMore").hide();
});
I want to modify this code which works pretty good but (or I don't know because I'm new with php) I can't limit the number of li's displayed for the main elements in the menu. The actual code will echo all elements it finds, I want to limit the times
<li><a href='{$sLink}' {$sOnclick} target='_parent'>{$sPictureRep}{$sText}</a>
this line is echoed.. let's say to echo just the first 15 elements + a "MORE" button under which to display the rest of the elements as sub-menus.. (this is a 2 level horizontal menu). Can someone please help me? I really tried a lot but I'm not an expert in PHP..
Thanks!
<?php
require_once( '../../../inc/header.inc.php' );
require_once( DIRECTORY_PATH_INC . 'membership_levels.inc.php' );
require_once( DIRECTORY_PATH_ROOT . "templates/tmpl_{$tmpl}/scripts/TemplMenu.php" );
class SimpleMenu extends TemplMenu
{
function getCode()
{
$this->iElementsCntInLine = 100;
$this->getMenuInfo();
$this->genTopItems();
return $this->sCode;
}
function genTopItem($sText, $sLink, $sTarget, $sOnclick, $bActive, $iItemID, $isBold = false, $sPicture = '')
{
$sActiveStyle = ($bActive) ? ' id="tm_active"' : '';
if (!$bActive) {
$sAlt= $sOnclick ? ( ' alt="' . $sOnclick . '"' ) : '';
$sTarget = $sTarget ? ( ' target="_parent"' ) : '';
}
$sLink = (strpos($sLink, 'http://') === false && !strlen($sOnclick)) ? $this->sSiteUrl . $sLink : $sLink;
$sSubMenu = $this->getAllSubMenus($iItemID);
$sImgTabStyle = $sPictureRep = '';
if ($isBold && $sPicture != '') {
$sPicturePath = getTemplateIcon($sPicture);
$sPictureRep = "<img src='{$sPicturePath}' style='vertical-align:middle;width:16px;height:16px;' />";
$sText = ' ';
$sImgTabStyle = 'style="width:38px;"';
}
$sMainSubs = ($sSubMenu=='') ? '' : " {$sSubMenu} </a>";
$this->sCode .= "
<li><a href='{$sLink}' {$sOnclick} target='_parent'>{$sPictureRep}{$sText}</a>
<div id='submenu'>
<ul>
<li>{$sMainSubs}</li>
</ul>
</div>
</li>
";
}
}
$objMenu = new SimpleMenu();
echo "<ul id='ddmenu'>";
echo $objMenu->getCode();
echo "</ul>";
?>
It's difficult to tell exactly where you want to do this in your code, but I figure you're looking for something like:
<?php
for ($i = 0; i < 15; i ++){
echo "<li><a href='{$sLink}' {$sOnclick} target='_parent'>{$sPictureRep}{$sText}</a>"
}
echo "<li><a href='more' target='_parent'>More...</a>"
?>