"Load More Posts" with Ajax in wordpress - ajax

I am trying to create ajax pagination on Blog Page..
What I need to do is to display 5 posts initially and then load 5 more when "load more posts" link is clicked.
Below is the javascript I am using:
<script>
jQuery(document).ready(function() {
// ajax pagination
jQuery('.nextPage a').live('click', function() {
// if not using wp_pagination, change this to correct ID
var link = jQuery(this).attr('href');
// #main is the ID of the outer div wrapping your posts
jQuery('.blogPostsWrapper').html('<div><h2>Loading...</h2></div>');
// #entries is the ID of the inner div wrapping your posts
jQuery('.blogPostsWrapper').load(link+' .post')
});
}); // end ready function
</script>
The problem is that when I click the link the old posts get replaced by the new ones, I need to show old posts as well as the new posts...
Here is the Updated jQuery Code which enables the ajax pagination.
jQuery(document).ready(function(){
jQuery('.nextPage a').live('click', function(e){
e.preventDefault();
var link = jQuery(this).attr('href');
jQuery('.blogPostsWrapper').html('Loading...');
jQuery('.blogPostsWrapper').load(link+' .post');
});
});
The only problem now is the old posts get removed, i need to keep both old and new posts..

Here is the final code I used and now everything works perfectly...
// Ajax Pagination
jQuery(document).ready(function($){
$('.nextPage a').live('click', function(e) {
e.preventDefault();
$('.blogPostsWrapper').append("<div class=\"loader\"> </div>");
var link = jQuery(this).attr('href');
var $content = '.blogPostsWrapper';
var $nav_wrap = '.blogPaging';
var $anchor = '.blogPaging .nextPage a';
var $next_href = $($anchor).attr('href'); // Get URL for the next set of posts
$.get(link+'', function(data){
var $timestamp = new Date().getTime();
var $new_content = $($content, data).wrapInner('').html(); // Grab just the content
$('.blogPostsWrapper .loader').remove();
$next_href = $($anchor, data).attr('href'); // Get the new href
$($nav_wrap).before($new_content); // Append the new content
$('#rtz-' + $timestamp).hide().fadeIn('slow'); // Animate load
$('.netxPage a').attr('href', $next_href); // Change the next URL
$('.blogPostsWrapper .blogPaging:last').remove(); // Remove the original navigation
});
});
}); // end ready function

Could you maybe try the following code? This is how I got this working on my own site.
replace:
jQuery('.blogPostsWrapper').load(link+' .post')
with:
$.get(link+' .post', function(data){
$('.blogPostsWrapper').append(data);
});

You should use jQuery append() to add the new posts without using the old ones.
jQuery load() Will replace the data found in your element . Quoted from jQuery API:
.load() sets the HTML contents of the matched element to the returned
data. This means that most uses of the method can be quite simple:

Related

Packery not arranging additional divs when loaded via AJAX

I am using packery to arrange blog posts in a masonry format. This works fine for posts that are initially displayed on the page but when I load new posts - when the pagination links are clicked - via AJAX the posts just get added to the container but do no 'repack' or re-arrange in a masonry format.
I am using WordPress and using my own AJAX call, see code below:
// For jQuery noConflict
(function($) {
$(document).ready(function() {
// Find out the page number
var pageNumber;
$('.custom-pagination a.page-numbers').click(function() {
pageNumber = $(this).html();
});
// AJAX call to load more posts when pagination links are clicked
$(document).on( 'click', '.custom-pagination a.page-numbers', function( event ) {
event.preventDefault();
page = pageNumber;
$.ajax({
url: ajaxpagination.ajaxurl,
type: 'post',
data: {
action: 'ajax_pagination',
query_vars: ajaxpagination.query_vars,
page: page
},
success: function( html ) {
var $container = $('#all-posts').packery();
$container.append( html );
$container.packery( 'appended', html );
}
});
});
});
})(jQuery);
// End jQuery noConflict
Can anyone point me in the right direction on how to call packery again to re-arrange my posts in a masonry format after they are loaded via AJAX?
Thanks.
I had the same issue, and took care of it server-side (web2py/python), in accordance with the instructions here:
# this function is called via ajax
def function_that_loads_the_new_content():
...
new_divs = #generate new content
new_divs_as_string = ''.join([str(x) for x in new_divs])
# this script runs when the new content is appended to the container
update_results = \
"var $items = $('%s');$pack.append($items).packery( 'appended', $items );" \
% new_divs_as_string
return update_results
The idea is to use packery's appending functionality after the new elements have been added to the container element. The above script is essentially equivalent to this template offered in the packery page:
$('.append-button').on( 'click', function() {
// create new item elements
var $items = $('<div class="grid-item">...</div>');
// append items to grid
$grid.append( $items )
// add and lay out newly appended items
.packery( 'appended', $items );
});

Javascript load and post

I have this function in javascript
function save(){
//$("#complex").submit();
//Complex List
$(document).ready(function(){
var proofer_filter = document.getElementById('proofer').value;
var proofer_filter = proofer_filter.split(' ').join('_')
var status_filter = document.getElementById('status_filter').value;
var status_filter = status_filter.split(' ').join('_');
var cstart = document.getElementById('cstart').value;
var cstart = cstart.split(' ').join('_');
var cend = document.getElementById('cend').value;
var cend = cend.split(' ').join('_');
$("#complex_list").load("pages/complexlist.php?proofer="+proofer_filter+"&status_filter="+status_filter+"&start="+cstart+"&end="+cend+"&dept=<?php echo str_replace(" ","_",$department)?>");
}
);
//Complex Form
var account_type = document.getElementById('account_type').value;
var account_type = account_type.split(' ').join('_');
var log_id = document.getElementById('complexid').value;
$(document).ready(function(){
$("#show_form").load("pages/complexform.php?refno="+log_id+"&dept="+account_type+"&user=<?php echo str_replace(" ","_",$user)?>&save=y");
}
);
}
It is a page with two divs wherein each div loads a remote page. One of this divs is a form which has a submit button. When clicking it the form values does not post. Thus I could not use it as a php variable. Can anyone help?
split out your javascript into 2 sections
<script>
$(document).ready(function(){
$("#complex_list").load("pages/complexlist.php?proofer="+proofer_filter+"&status_filter="+status_filter+"&start="+cstart+"&end="+cend+"&dept=<?php echo str_replace(" ","_",$department)?>");
$("#show_form").load("pages/complexform.php?refno="+log_id+"&dept="+account_type+"&user=<?php echo str_replace(" ","_",$user)?>&save=y");
saveForm.init();
});
you will also need to create the function to save the form and an event listener for when someone clicks on your save button.
var saveForm= {
init: function () {
$('#submit-button').on('click', function () {
//only set all of your values if you are planning to submit an ajax form otherwise just submit the form with the last line of the event listener.
var proofer_filter = document.getElementById('proofer').value;
var proofer_filter = proofer_filter.split(' ').join('_')
var status_filter = document.getElementById('status_filter').value;
....
etc
//make sure to put your submit form in here too.
$( "#form" ).submit();
//if you are using ajax to submit the form, use the variables above to pass into the ajax call.
});
}
}
</script>
If you do not know where you are going wrong, use the Developer tools (F12) in Chrome when you are developing

jQuery hashchange how to do?

I have made a jQuery thing; with will load content without refreshing the page. The code for that is:
$(document).ready(function(){
// initial
$('#content').load('content/index.php');
// handle menu clicks
$('#navBar ul li ').click(function(){
var page = $(this).children('a').attr('href');
$('#content').load('content/'+ page +'.php');
return false;
});
});
Now I want to have a sort of history thing in that, the code for that is:
(function(){
// Bind an event to window.onhashchange that, when the hash changes, gets the
// hash and adds the class "selected" to any matching nav link.
$(window).hashchange( function(){
var hash = location.hash;
// Set the page title based on the hash.
document.title = 'The hash is ' + ( hash.replace( /^#/, '' ) || 'blank' ) + '.';
// Iterate over all nav links, setting the "selected" class as-appropriate.
$('#nav a').each(function(){
var that = $(this);
that[ that.attr( 'href' ) === hash ? 'addClass' : 'removeClass' ]( 'selected' );
});
})
// Since the event is only triggered when the hash changes, we need to trigger
// the event now, to handle the hash the page may have loaded with.
$(window).hashchange();
});
Found on: http://benalman.com/code/projects/jquery-hashchange/examples/hashchange/
My Question is: how can i make the second code working with the first?
Since you haven't gotten an answer yet I will write it. You need the plugin jQuery hashchange for the code to run.
https://github.com/cowboy/jquery-hashchange
To implement a cache you could do something like
$('#content').load('content/index.php');
//create a cache object
var cache = {};
// handle menu clicks
$('#navBar ul li ').click(function(){
var page = $(this).children('a').attr('href');
//check if the page was already requested
if(cache[page] === undefined){
//if not fetch the page from the server
$.get('content/'+ page +'.php', function(data){
$('#content').html(data);
//save data in cache
cache[page] = data;
}else{
//use data from cache
$('#content').html(cache[page]);
}
return false;
});
Use History JS. It works for HTML5 pushState and also falls back to HTML 4 hashtags. Also works for keeping the state model when the page is refreshed.

jQuery address plugin, pathname change when using AJAX

I have a Wordpress blog at http://themes.visualise.ca/visualise and when a user clicks on a thumbnail the post is loaded with AJAX (using the jQuery address plugin) . I would like the URL to change at the same time to i.e. for the second thumbnail the url should change to http://themes.visualise.ca/visualise/portfolio/samuel but with the following code it changes to http://themes.visualise.ca/visualise/visualise/portfolio/samuel.
1) So my question is there a way to make the jQuery address replace the current pathname by the destination url's pathname instead of simply adding it at the end? I would like the solution to work also with http://themes.visualise.ca/ to http://themes.visualise.ca/visualise/portfolio/samuel because the blog might not be hosting in a folder like it is right now.
2) Or maybe there is another way to achieve this?
Here is the jQuery code:
$('.ajaxed,li.menu-item-object-page a').live('click', function(event) {
var link = $(this).attr('href');
var rewritepath = $(this)[0].pathname;
$("html,body").animate({scrollTop: 0}, 300);
$('#content,.plus').stop().fadeOut('slow', function(){
$('#board-wrapper').slideDown('slow');
$('#board').fadeOut('slow', function(){
$('#board').stop().load(link, function(){
$('#board').delay(1000).fadeIn('slow', function(){
var board_h2 = $('#board').height();
$('#board-wrapper').css('height', board_h2 + 'px');
});
});
});
});
$.address.crawlable(true).path(rewritepath);
return false;
});
Many thanks for your time and help.
What I did is that I removed the root site url from link url and it works.
$('.ajaxed,li.menu-item-object-page a').live('click', function(event) {
var link = $(this).attr('href');
var toRemove = MySettings.url;
var url_pathname = MySettings.url[0].pathname;
var rewritepath = link.replace(toRemove,'');
...
});

JQuery mobile collapsible with Ajax

trying to display the JQMobile collapsible containing an unsorted list. The collapsible is not shown when the list is appended using an ajax call. The collapsible is correctly shown when the list is added statically. Any advice?
thanks
<script>
$(document).ready(function() {
var updateSectionsPage = function() {
// 1. Get the page and list we need to work with
var $page = $('#homeList');
// 2. Build the URL we need using the data stored on the main view page
var strUrl = 'http://xyz';
// 3. Get the sections and append them to the list
$.ajax({
url: strUrl,
dataType: 'json',
cache: false,
success: function(data) {
$sections = $page.find('#sections');
// 3.1 Delete the existing content, if any
$sections.empty();
// 3.2 Create a new collapsible
$sections.html('<div id="collapsible" data-role="collapsible" data-collapsed="true" data-theme="a" data-content-theme="a"></div>');
// 3.3 Create the title of collapsible
$sections.html('<h3>ColdPlay</h3>');
// 3.4 Create the list and store it into a JQuery object
$sections.html('<ul id="list" data-role="listview" data-inset="false"></ul>');
$list = $page.find('#list');
// 3.5 Build HTML that contains the desired information
for (var j in data.list[0].list){
var strHtml = '<li><img src="' + data.list[0].list[j].img + '" /><h4>' + data.list[0].list[j].title + '</h4></li>';
// Make it into a jQuery object...
var item = $(strHtml);
// ...so we can append it to our list.
$list.append(item);
}
// Call the listview widget.
$list.listview();
},
error: function() {
alert("An error occurred. please, try it again!");
}
});
}(); // 4. Call the updateSectionsPage() function
})
</script>
I think you just need to turn your $list.listview(); call into $list.listview('refresh');.
Also, you may benefit from changing up the way you append you new list items. Check this post out. You do not want to nest an append call within a loop if you can avoid it. You will also benefit from not wrapping your strHtml with the jQuery $ selector as it may not be necessary.
That optimization link is courtesy of another SO post here.
Once you create the list,use the following code snippet-
$list.listview('refresh');
$page.trigger('create');
in place of $list.listview();
Also it is not considered a best practice to use $(document).ready() in jquery mobile.See the note below
Important: Use pageInit(), not $(document).ready()
The first thing you learn in jQuery is to call code inside the
$(document).ready() function so everything will execute as soon as the
DOM is loaded. However, in jQuery Mobile, Ajax is used to load the
contents of each page into the DOM as you navigate, and the DOM ready
handler only executes for the first page. To execute code whenever a
new page is loaded and created, you can bind to the pageinit event.
This event is explained in detail at the bottom of this page.
From http://jquerymobile.com/demos/1.0/docs/api/events.html
thanks guys, the issue in my code was on the missing collapsible() widget call. Once the html page is dynamically created, we need to render it with jqmobile widget calls: listview() and collapsible(). Here the working code.
function fillSectionsPage() {
// 1. Get the page we need to work with
var $page = $('#sectionList');
// 2. Build the URL we need using the data stored on the main view page
var strUrl = 'http://xyz';
// 3. Get the sections and append them to the list
$.ajax({
url: strUrl,
dataType: 'json',
cache: false,
success: function(data) {
$sections = $page.find('#sections');
// 3.1 Delete the existing content, if any
$sections.empty();
// 3.2 Append a new collapsible and store it into a JQuery object
$sections.append('<div id="collapsible" data-role="collapsible" data-collapsed="true" data-theme="c" data-content-theme="c"></div>');
$collapsible = $page.find('#collapsible');
// 3.3 Append the title of collapsible
$collapsible.append('<h3>' + data.list[0].title + '</h3>');
// 3.4 Append the list header and store it into a JQuery object
$collapsible.append('<ul id="list" data-role="listview" data-inset="false"></ul>');
$list = $page.find('#list');
// 3.5 Build the list items
var htlmList = [];
for (var j in data.list[0].list){
htlmList[j] = '<li><img src="' + data.list[0].list[j].img + '" /><h4>' + data.list[0].list[j].title + '</h4></li>';
}
// 3.6 Append the list items to the list header
$list.append(htlmList.join(''));
// 3.7 Render the listview and the collapsible
$list.listview();
$collapsible.collapsible();
},
error: function() {
alert("An error occurred, please, try it again!");
}
});
}
Hope to check that tutorial, Collapsible content and Ajax loading with jQuery Mobile and this for How do I toggle the jQuery Mobile Accordion with a button click?

Resources