wordpress ajax pagination breaks after 10 pages - ajax

Can someone help me with ajax pagination please, i'm on it 2 days already and can't figure it out. I have Load More style pagination, this is the code, preety classic(down below).
Everything works as planing except when the placeholder reaches page 10. Then, hell break loose and nothing is loading anymore. The button still works untill maxpages is reached and so the button gets removed, but nothing happens with more than 10 placeholders. The website i'm currently using this scriptand the place you can test yourself is this: http://filmhdonline.com/category/toate-filmele/
I would appreciate someone having an ideea what i'm talking about. Thanks in advance.
jQuery(document).ready(function() {
// The number of the next page to load (/page/x/).
var pageNum = parseInt(pbd_alp.startPage);
// The maximum number of pages the current query can return.
var max = parseInt(pbd_alp.maxPages);
// The link of the next page of posts.
var nextLink = pbd_alp.nextLink; pageNum++;
//Load more videos translation
var more = pbd_alp.more;
//Loading videos translation
var loading = pbd_alp.loading;
/**
* Replace the traditional navigation with our own,
* but only if there is at least one page of new posts to load.
*/
if(pageNum <= max) {
// Remove the traditional navigation.
jQuery('.pagination').remove();
// Insert the "More Posts" link.
if( jQuery('#content').find('ul.listing-videos').length == 1 ){
jQuery('#content ul.listing-videos').append('<li class="more-posts pbd-alp-placeholder-' + pageNum + '"></li>');
jQuery('#content').append('<p id="pbd-alp-load-posts" class="pagination">' + more + '</p>');
}
}
/**
* Load new posts when the link is clicked.
*/
jQuery('#pbd-alp-load-posts a').click(function() {
// Are there more posts to load?
if(pageNum <= max) {
// Show that we're working.
jQuery(this).text(loading);
jQuery('.pbd-alp-placeholder-'+ pageNum).load(nextLink + ' #content ul.listing-videos li',
function() {
//jQuery('.pbd-alp-placeholder-'+ pageNum).children('li').unwrap();
console.log(pageNum);
jQuery(this).children().hide();
$newContent = jQuery(this).children().unwrap();
$newContent.fadeIn('fast');
// Update page number and nextLink.
pageNum++;
nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
**// Add a new placeholder, for when user clicks again.
jQuery('#content ul.listing-videos').append('<li class="more-posts pbd-alp-placeholder-'+ pageNum +'"></li>');**
// Update the button message.
if(pageNum <= max) {
jQuery('#pbd-alp-load-posts a').text('Vezi mai multe');
} else {
jQuery('#pbd-alp-load-posts a').remove();
}
}
);
} else {
jQuery('#pbd-alp-load-posts a').append('.');
}
return false;
});
});

For ajax pagination in wordpress, You can use the plugin like https://wordpress.org/plugins/wp-pagenavi/.
OR
<div id="content">
<?php
$new_query = new WP_Query();
$new_query->query('post_type=post&showposts=1'.'&paged='.$paged);
?>
<?php while ($new_query->have_posts()) : $new_query->the_post(); ?>
<?php the_title(); ?>
<?php endwhile; ?>
<div id="pagination">
<?php next_posts_link('« Older Entries', $new_query->max_num_pages) ?>
<?php previous_posts_link('Newer Entries »') ?>
</div>
</div><!-- #content -->
<script>
jQuery(function($) {
$('#content').on('click', '#pagination a', function(e){
e.preventDefault();
var link = $(this).attr('href');
$('#content').fadeOut(500, function(){
$(this).load(link + ' #content', function() {
$(this).fadeIn(500);
});
});
});
});
</script>

I Have the same problem.
If it still happening, replace:
nextLink = nextLink.replace(/\/page\/[0-9]?/, '/page/'+ pageNum);
to
nextLink = nextLink.replace(/\/page\/[0-9]*/, '/page/'+ pageNum);
Problem in wrong regex [0-9]? match only single number from 1 to 9. From 10 it takes only 1. Instead [0-9]* match from 0 to infinity. So, it breaks after 9 (form 0 to 9), because next 10 and it's take fore use only 1.

Related

Can't get wordpress ajax form to submit

I am porting an application to WordPress. It uses a form to select what attributes the customer is looking for in an Adult Family Home via checkboxes and drop-downs. It re-searches the database on each onchange and keyup. Originally I had the application standalone in PHP, but when I migrated it to WordPress I started having issues.
Currently in WP I have the code conditionalized ($DavesWay == 1) to do ajax the normal no-WordPress-way and ($DavesWay == 0) to do it the WordPress-way.
In the non-WordPress-way, the ajax works fine EXCEPT that I get a WP header and menu between the search form and the results-div that Ajax puts the data in. I get no errors from WP or in the JS console. In the WP-way The search form displayed, but nothing happens when I check any of the checkboxes. The JS console displays
POST http://localhost/demo4/wp-admin/admin-ajax.php 400 (Bad Request)
But I don't see any way to tell exactly what it is complaining about. How should I troubleshoot this?
Troubleshooting = Examine the HTML output, lots of echos and exits in PHP code, look at JS console.
function submitPg1(theForm) {
// Used with onChange from "most" form elements, but not on those that change the page
// rather than the select criteria. Such as rowsPerPage, pageNumber etc.
setById("pageNo", "1"); // set inital page
mySubmit();
}
function mySubmit(theForm) { // The actual ajax submit
// DO NOT set page number
jQuery.ajax({ // create an AJAX call...
data: jQuery("#asi_search_form").serialize(), // get the form data
type: jQuery("#asi_search_form").attr("method"), // GET or POST
url: jQuery("#asi_search_form").attr("action"), // the file to call
success: function (response) { // on success..
jQuery("#result").html(response); // update the DIV
}
})
}
function setById(id, value) { // Used to set vales by Id
x = document.getElementById(id).value;
x.value = value;
}
// 1st submit with blank selection
jQuery(document).ready(function () { submitPg1(this.form) });
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
Code fragments: (from the displayed page source)
<div id="asi_container" class="asi_container" >
<noscript><h2>This site requires Javascript and cookies to function. See the Help page for how to enable them.</h2></noscript>
<div id="searchForm">
<form id="asi_search_form" name="asi_search_form" method="post" action="http://localhost/demo4/wp-admin/admin-ajax.php">
<input type="hidden" name="action" value="asi_LTCfetchAll_ajax" style="display: none; visibility: hidden; opacity: 0;">
<table id="greenTable" class="asi_table" title="The Green areas are for site administration, not typical users">
<tbody>
PHP code:
$DavesWay = 0;
if ($DavesWay == 1){ //echo "Daves Way Setup"; // Dave's way, which works but prints the menu twice
if( $operation == "submit"){
require("asi_LTCfetchAll.php"); // for each onchange or onkeyup
}else{
add_filter( 'the_content', 'asi_tc_admin', '12' ); // Initial page refresh # must be >12
}
}else{
// The WordPress way that I could't get to work -- asi_LTCfetch never gets called
function asi_LTCfetchAll_ajax(){
//echo "<br /> Goto to Submit function"; // DEBUG
require($asi_plugin_dir . "/includes" . '/asi_LTCfetchAll.php');
}
add_action( "wp_ajax_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // admin users
add_action( "wp_ajax_nopriv_asi_LTCfetchAll_ajax", "asi_LTCfetchAll_ajax" ); // non-logged in users
add_filter( "the_content", "asi_tc_admin", "12" ); // Initial page refresh # must be >12
}
Try changing the JavaScript to the way WordPress recommends it in their documentation:
var data = {
'action': 'my_action',
'whatever': 1234
};
jQuery.post(ajaxurl, data, function(response) {
alert('Got this from the server: ' + response);
});
I suggest trying following URL: https://codex.wordpress.org/AJAX_in_Plugins
Also you can use the plugin: https://wordpress.org/plugins/ajax-search-lite/

dompdf page_script() variables

I'm trying to generate a PDF with multiple sets of page numberings and with unnumbered pages as well. I will not be able to tell in advance how long each set of pages is as they are dynamically generated. For example, the PDF may contain 10 total pages where pages 1-4 have "Page X of 4" in the footer, page 5 is unnumbered, pages 6-8 have "Page X of 3", and pages 9-10 are unnumbered.
Right now I have page numberings implemented using the page_script() and text() functions. Essentially, what I think I need, is a way to be able to pass variable from the document to the page_script() function as the PDF is generated. This would allow me to add something like <?php $page_count = false; ?> or <?php $page_count_reset = true; ?> at different places in the document and act accordingly in the page_script() function. As far as I can tell, this doesn't seem possible.
I am able to set globals within the document <?php $GLOBALS['page_count'] = false; ?> and read them from within page_script() BUT these are processed all at once. So whatever I set the last $GLOBALS['page_count'] to in the document is what $GLOBALS['page_count'] is in the entire page_script() function.
I hope this makes some kind of sense. My next step is to generate multiple PDFs and join them together but that's something I don't want to do unless I have to. Does anyone have any thought?
You're on the right track. Almost there, actually. What you need to do is track your sections in your global variable. The following snippets can be placed in your HTML for use with dompdf 0.6.1.
1) Set up some global variables first thing in the body:
$GLOBALS['start_pages'] = array( );
$GLOBALS['current_start_page'] = null;
$GLOBALS['show_page_numbers'] = false;
2) At the start of each section fill out the start_pages global:
$GLOBALS['current_start_page'] = $pdf->get_page_number();
$GLOBALS['start_pages'][$pdf->get_page_number()] = array(
'show_page_numbers' => true,
'page_count' => 1
);
3) At the end of each section, record the number of pages:
$GLOBALS['start_pages'][$GLOBALS['current_start_page']]['page_count'] = $pdf->get_page_number() - $GLOBALS['current_start_page'] + 1;
4) Use page script to write out your page numbering for each section:
$pdf->page_script('
if ($pdf) {
if (array_key_exists($PAGE_NUM, $GLOBALS["start_pages"])) {
$GLOBALS["current_start_page"] = $PAGE_NUM;
$GLOBALS["show_page_numbers"] = $GLOBALS["start_pages"][$GLOBALS["current_start_page"]]["show_page_numbers"];
}
if ($GLOBALS["show_page_numbers"]) {
$font = Font_Metrics::get_font("helvetica", "bold");
$pdf->text(10, 10, "Page " . ($PAGE_NUM - $GLOBALS["current_start_page"] + 1) . " of " . $GLOBALS["start_pages"][$GLOBALS["current_start_page"]]["page_count"], $font, 12);
}
}
');
The final document would look something like this:
<html>
<body>
<script type="text/php">
// setup
$GLOBALS['start_pages'] = array( );
$GLOBALS['current_start_page'] = null;
$GLOBALS['show_page_numbers'] = false;
</script>
<script type="text/php">
// section start
$GLOBALS['current_start_page'] = $pdf->get_page_number();
$GLOBALS['start_pages'][$pdf->get_page_number()] = array(
'show_page_numbers' => true,
'page_count' => 1
);
</script>
<p>lorem ipsum ... <!-- lots of text -->
<script type="text/php">
// record total number of pages for the section
$GLOBALS['start_pages'][$GLOBALS['current_start_page']]['page_count'] = $pdf->get_page_number() - $GLOBALS['current_start_page'] + 1;
</script>
<div style="page-break-before: always;"></div>
<script type="text/php">
// section start
$GLOBALS['current_start_page'] = $pdf->get_page_number();
$GLOBALS['start_pages'][$pdf->get_page_number()] = array(
'show_page_numbers' => false,
'page_count' => 1
);
</script>
<p>lorem ipsum ... <!-- lots of text -->
<script type="text/php">
// record total number of pages for the section
$GLOBALS['start_pages'][$GLOBALS['current_start_page']]['page_count'] = $pdf->get_page_number() - $GLOBALS['current_start_page'] + 1;
</script>
<script type="text/php">
$pdf->page_script('
if ($pdf) {
if (array_key_exists($PAGE_NUM, $GLOBALS["start_pages"])) {
$GLOBALS["current_start_page"] = $PAGE_NUM;
$GLOBALS["show_page_numbers"] = $GLOBALS["start_pages"][$GLOBALS["current_start_page"]]["show_page_numbers"];
}
if ($GLOBALS["show_page_numbers"]) {
$font = Font_Metrics::get_font("helvetica", "bold");
$pdf->text(10, 10, "Page " . ($PAGE_NUM - $GLOBALS["current_start_page"] + 1) . " of " . $GLOBALS["start_pages"][$GLOBALS["current_start_page"]]["page_count"], $font, 12);
}
}
');
</script>
</body>
</html>
You can see a sample of this in practice here: http://eclecticgeek.com/dompdf/debug.php?identifier=e980df4efacf5202c2f1d31579f09c56

Google style page loading , Bulk records not on onload, display some and fetch remain in back?

I'm developing a web application,after login the user is redirected to the inbox page,
where he will find many widgets, each with hundreds of records.
So it is taking too much time to open inbox page after login success.Very much performance issue.
So i want to display some(5-10) records in each widget
and after the page loads in the backend(user doesn't know) the request will be processing still and fetch the records and append them to the widget records.
Eg. If you open google images and search for cricket, it will display the page with images and if you scroll down only you will come to know the ajax request going and appending the response to the web page,
But it is not waiting till the entire page is loaded.
I must develop my application in the same way.
Any idea is Highly Appreciated and sample code too.
This should work for you, Mr.Chowdary.
You would need something to handle your requests in the backend. Since you did NOT specify whether you used Java or PHP or Python or whatever, I used PHP - its what I know best :D
PSEUDO CODE (loadmore.jsp)
Begin
widget = URL(widget) //the widget id or name
page = URL(page) //the page being retrieved
switch (widget)
{
case "widget1":
data_for_widget1 = paginated_query1(page)
print data_for_widget1
break
case "widget2":
data_for_widget2 = paginated_query2(page)
print data_for_widget2
break
default :
print "Invalid Widget"
break
}
End
PHP Version
<?php
if (isset($_GET['page'])) {
$widget = $_GET['page'];
$page = $_GET['page'];
switch ($widget) {
case "MyWidget1": //dynamic example
$manyManyItems; //A massive array of items
$pages = array_chunk($manyManyItems, 5); //break it up into chunks of 5 items
if( array_key_exists ($pages[$page]) )
for ($i = 0; $i < count($pages[$page]); $i++) { //load those chunks
echo '<div class="item">'.$pages[$page][$i].'</div>';
}
else {
echo "zero"; //code word that tells ajax that there is nothing more to load
}
break;
case "MyWidget2": //manual example
if($page==1) { //loads the first chunck manually
echo '<div class="item">dynamic content 1</div>';
echo '<div class="item">dynamic content 2</div>';
echo '<div class="item">dynamic content 3</div>';
}
elseif($page==2) { //loads the next batch
echo '<div class="item">dynamic content 1</div>';
echo '<div class="item">dynamic content 2</div>';
echo '<div class="item">dynamic content 3</div>';
}
else
echo "zero"; //code word that tells ajax that there is nothing more to load
break;
default:
echo "zero"; //code word that tells ajax that there is nothing more to load
}
}
?>
HTML
Each widget could look like this
<div id="MyWidget1" class="widget" data-widgetPage="0">
<div class="item">default content</div>
<div class="item">another default content</div>
...
<div class="loadmoreajaxloader" style="display:none;"><center>Loading...</center></div>
</div>
Javascript
<script type="text/javascript">
$(".widget").scroll(function()
{
if($(this).scrollTop() == $(this).height() - $(this).height())
{
var nextPage = eval($(this).attr("data-widgetPage") + 1);
$(this).find('.loadmoreajaxloader').show();
$.ajax({
url: "loadmore.php?widget="+$(this).attr("id")+"&page="+nextPage,
success: function(html)
{
if(html != "zero")
{
$(this).append(html);
$(this).('.loadmoreajaxloader').hide();
}else
{
$(this).find('.loadmoreajaxloader').html('<center>No more posts to show.</center>');
}
}
});
$(this).attr("data-widgetPage", nextPage);
}
});
</script>
Success with the app.
I got to know the following answer suits my requirement from the following site.. Jquery endless scrolling

one dropdown appears on the selection of other dropdown using codeigniter

I am trying to create dynamic dropdown of category and on selection of this category sub-category dropdown should appear. I have done this using OOP PHP but really having tought time with codeigniter.
Firstly I have created this category dropdown
<?php
$js =' onChange="callAjaxFunction(this.value)"';
echo form_dropdown('category', $categories, null, $js); ?>
Javascript to show sub-category
<script>
// JavaScript Document
var enableCache = false;
var jsCache = new Array();
var AjaxObjects = new Array(new sack(),new sack());
function ShowContent(divId,ajaxIndex,url)
{
document.getElementById(divId).innerHTML = AjaxObjects[ajaxIndex].response;
if(enableCache){
jsCache[url] = AjaxObjects[ajaxIndex].response;
}
AjaxObjects[ajaxIndex] = false;
document.getElementById("ajax_container").innerHTML = '';
}
function ShiftChanger(divId,url,id) {
//to show the div
document.getElementById(divId).innerHTML="";
if(enableCache && jsCache[url]){
document.getElementById(divId).innerHTML = jsCache[url];
return;
}
var ajaxIndex = AjaxObjects.length;
AjaxObjects[ajaxIndex] = new sack();
AjaxObjects[ajaxIndex].requestFile = url+"?id="+id;
document.getElementById("ajax_container").innerHTML = '<img src=ajax_loader.gif hspace=10 vspace=10 />'; AjaxObjects[ajaxIndex].onCompletion = function(){ ShowContent(divId,ajaxIndex,url+"?id="+id);};
AjaxObjects[ajaxIndex].runAJAX();
}
function callAjaxFunction(value)
{
ShiftChanger('shiftcontainer','ajax_category.php',value);
}
</script>
But this is not working. As you can see ajax_category.php is not being able to pass. I think it should be done with controller, I had tried that also but nothing seems as working. I am really stuck with this. Please anyone with little help. Really getting depressed with it :(.

AJAX Div Refresh with PHP

I am trying to refresh some elements on my page every so often. I know theres a million topics on here about that and I have tried to get mine working, but here is what I need to refresh..
This is the code that gets generated when the page loads:
<div id="galleria">
<?php
$a = array();
$dir = '../public/wp-content/uploads/2012/01';
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
if (preg_match("/\.png$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpg$/", $file)) $a[] = $file;
elseif (preg_match("/\.jpeg$/", $file)) $a[] = $file;
}
closedir($handle);
}
$totalImgs = count($a);
$imgUsed = array();
for ($j = 0; $j < 100; $j++)
{
do
{
$randIndex = mt_rand(0, $totalImgs);
}
while ($imgUsed[$randIndex] === TRUE);
$imgUsed[$randIndex] = TRUE;
echo "<img src='" . $dir . '/' . $a[$randIndex] . "' />";
}
?>
</div>
I would like to automatically refresh this every 10 seconds but not reload the page. I have read up on ajax and it seems this is possible but I cannot seem to get it to work.
All this is doing is showing the galleria div, and loading the 100 images inside the div. Then the galleria script takes over and displays it nicely. Will AJAX work better or JQuery?
Thank you for your help!
"Will AJAX work better or jQuery?" -- AJAX is a technique, jQuery is a library. As it turns out, jQuery has an excellent API for AJAX.
Let's call this bit of PHP "galleria.php". On original page load, it is inserted into the parent PHP page using good ol' <?php include('galleria.php')?>. Now the end user is seeing the full initialized page.
To update it, you have a number of AJAX options available, but the easiest is to include jQuery on your page and then you can use .load() in a script:
var updateGallery = setInterval(function() {
$('#someDiv').load('galleria.php');
}, 10000);
There's room for tweaking... maybe galleria.php doesn't include the <div id="galleria">, which is set on the page. In which case you would load right into #galleria instead of #someDiv and save yourself an unnecessary container. Maybe you cache the $('#someDiv') object by declaring it in a different scope so that it can be re-used. But this is the general gist.
Use setInterval function with ajax call.
http://jquery-howto.blogspot.com/2009/04/ajax-update-content-every-x-seconds.html
As I wrote here you can fill a div with a jQuery ajax call.
<html>
<head>
<script type="text/javascript">
function refresh_gallery(){
$.ajax({
type: "POST",
url: "generate_gallery.php", // your PHP generating ONLY the inner DIV code
data: "showimages=100",
success: function(html){
$("#output").html(html);
}
});
}
$(function() {
refresh_gallery(); //first initialize
setTimeout(refresh_gallery(),10000); // refresh every 10 secs
});
</script>
</head>
<body>
<div id="output"></div>
</body>
</html>

Resources