jQuery hashchange how to do? - ajax

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.

Related

"Load More Posts" with Ajax in wordpress

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:

jQuery Mobile cache pages in order

I have a list of a tags that are hidden. I tried using the data-prefetch attribute as described in the jquery mobile docs. The only problem is it fires off an ajax request for all of them at once and there is no garentee of the order that they get loaded in.
The ordering is very important in what pages are shown next via swipe.
So I decided to try and cache the links programatically via this bit of code.
var last_cache_page = false;
function cache_next_page(){
if(last_cache_page == false){
var cache_link = $('.cache').first();
last_cache_page = cache_link;
}
else{
var cache_link = last_cache_page.nextAll('.cache');
last_cache_page = cache_link;
}
//Start Caching any other pages that we want to swip to
$.mobile.loadPage(cache_link.attr('href'), {showLoadMsg: false});
}
So on $(document).on('pageshow') I call cache_next_page(). That part works fine the real problem is that when using $.mobile.loadPage no jquery mobile page related events fire once the first cached page is interested into the dom.
I have tried pageshow, pageinit and pageload but they only fire the first time the page is loaded. Now if I load the first page which starts the caching directly. That is to say with out visiting any other pages in the application it DOES trigger all the expected events such as pageload.
It is only when you start on page_1 and then go to page_2 (which has the code to start the cache) that it fails to have a pageload event triggered when the cached page is inserted into the dom.
I found out there there is a .done on the object that is returned from .loadPage so I have modified my code as follows to allow it to cache my links in order.
var last_cache_page = false;
function start_caching(){
if(last_cache_page == false){
var cache_link = $('.cache').first();
last_cache_page = cache_link;
}
else{
var cache_link = last_cache_page.nextAll('.cache').first();
last_cache_page = cache_link;
}
if(cache_link.length == 1){
//Start Caching any other pages that we want to swipe to
new_page = $.mobile.loadPage(cache_link.attr('href'), {showLoadMsg: false});
new_page.done(function(){
start_caching();
});
}
}

jQuery stops working after ajax request that adds fields to a form in Drupal 7

I don't think this is a Drupal-specific question, but more of a general jquery/ajax issue:
Basically, I'm trying to use javascript to add up form fields and display the result in a "subtotal" field within the same form. Everything is working fine until i click the option to add another field (via ajax), which then changes my "subtotal" field to zero, and won't work again until I remove the field.
Here is the function that adds up the fields:
function calculateInvoiceFields(){
var total = 0;
var rate = 0;
var quantity = 0;
var i = 0;
var $ = jQuery;
$("#field-aminvoice-data-values tr").each(function(){
// quantity field number
quantity = $("#edit-field-aminvoice-data-und-"+i+"-field-aminvoice-quantity-und-0-value").val();
// rate field as number
rate = $("#edit-field-aminvoice-data-und-"+i+"-field-aminvoice-rate-und-0-value").val();
if(!isNaN(quantity) && !isNaN(rate)){
total += quantity*rate;
}
i++;
});
return total;
}
And here are the functions that get fired for .ready and .live:
jQuery(document).ready(function(){
var $ = jQuery;
$(".field-type-commerce-price input").val(calculateInvoiceFields());
});
jQuery(function(){
var $ = jQuery;
$(".form-text").live('change', function(){
$(".field-type-commerce-price input").val(calculateInvoiceFields());
});
});
Any ideas would be a big help. Thanks in advance!
I recommend using 'on' for any binding statement. and 'off' for unbinding.
The reason it doesn't work after an AJAX call, is because you need to be watching for that element to be added to the DOM, and an event attached to it after it gets loaded. If you load a new element in, and there is nothing watching for it, it won't add the event watch to that new DOM element.
As below:
function calculateInvoiceFields(){
/*..*/
return total;
}
$(document).ready(function(){
$(".field-type-commerce-price input").val(calculateInvoiceFields());
$("body").on('change', ".form-text", function(){
$(".field-type-commerce-price input").val(calculateInvoiceFields());
});
});
usually it stops working when an error has been thrown. did you check out your javascript console (firefox firebug, or built in for chrome) for any indication of an error?

jquery mobile ajax sends both GET and POST requests

Here is the problem:
By default jQuery Mobile is using GET requests for all links in the application, so I got this small script to remove it from each link.
$('a').each(function () {
$(this).attr("data-ajax", "false");
});
But I have a pager in which I actually want to use AJAX. The pager link uses HttpPost request for a controller action. So I commented the above jQuery code so that I can actually use AJAX.
The problem is that when I click on the link there are two requests sent out, one is HttpGet - which is the jQuery Mobile AJAX default (which I don't want), and the second one is the HttpPost that I actually want to work. When I have the above jQuery code working, AJAX is turned off completely and it just goes to the URL and reloads the window.
I am using asp.net MVC 3. Thank you
Instead of disabling AJAX-linking, you can hijack clicks on the links and decide whether or not to use $.post():
$(document).delegate('a', 'click', function (event) {
//prevent the default click behavior from occuring
event.preventDefault();
//cache this link and it's href attribute
var $this = $(this),
href = $this.attr('href');
//check to see if this link has the `ajax-post` class
if ($this.hasClass('ajax-post')) {
//split the href attribute by the question mark to get just the query string, then iterate over all the key => value pairs and add them to an object to be added to the `$.post` request
var data = {};
if (href.indexOf('?') > -1) {
var tmp = href.split('?')[1].split('&'),
itmp = [];
for (var i = 0, len = tmp.length; i < len; i++) {
itmp = tmp[i].split('=');
data.[itmp[0]] = itmp[1];
}
}
//send POST request and show loading message
$.mobile.showPageLoadingMsg();
$.post(href, data, function (serverResponse) {
//append the server response to the `body` element (assuming your server-side script is outputting the proper HTML to append to the `body` element)
$('body').append(serverResponse);
//now change to the newly added page and remove the loading message
$.mobile.changePage($('#page-id'));
$.mobile.hidePageLoadingMsg();
});
} else {
$.mobile.changePage(href);
}
});
The above code expects you to add the ajax-post class to any link you want to use the $.post() method.
On a general note, event.preventDefault() is useful to stop any other handling of an event so you can do what you want with the event. If you use event.preventDefault() you must declare event as an argument for the function it's in.
Also .each() isn't necessary in your code:
$('a').attr("data-ajax", "false");
will work just fine.
You can also turn off AJAX-linking globally by binding to the mobileinit event like this:
$(document).bind("mobileinit", function(){
$.mobile.ajaxEnabled = false;
});
Source: http://jquerymobile.com/demos/1.0/docs/api/globalconfig.html

jquery: bind click event to ajax-loaded elmente? live() won't work?

hey guys,
I have an input field that looks for matched characters on a page. This page simply lists anchor links. So when typing I constantly load() (using the jquery load() method) this page with all the links and I check for a matched set of characters. If a matched link is found it's displayed to the user. However all those links should have e.preventDefault() on them.
It simply won't work. #found is the container that shows the matched elements. All links that are clicked should have preventDefault() on them.
edit:
/*Animated scroll for anchorlinks*/
var anchor = '',
pageOffset = '',
viewOffset = 30,
scrollPos = '';
$(function() {
$("a[href*='#']").each(function() {
$(this).addClass('anchorLink');
$(this).bind('click', function(e) {
e.preventDefault();
//console.log('test');
anchor = $(this).attr('href').split('#')[1];
pageOffset = $("#"+anchor).offset();
scrollPos = pageOffset.top - viewOffset;
$('html, body').animate({scrollTop:scrollPos}, '500');
})
});
});
Well, I'm looking for all href's that contain a #. So I know those elements are anchors that jump to other elements. I don't want my page to jump, but rather scroll smoothly to this element with this specific #id.
This works fine when I use bind('click', ... for normal page-elements that have been loaded when the page is opened. It doesn't work for anchors that have been loaded via ajax! If I change the bind to live nothing does change for the ajax loaded elements - they still don't work. However normal anchors that have always been on the page are not triggering the function as well. So nothing works with live()!
When you say "it won't work" do you mean that your function is not been called or that you can not cancel out of the function? As far as I know you can not cancel out live events. With jQuery 1.4 you can use return false to cancel out live event propagation. Calling e.preventDefault() won't work.
Edit: right so this code should in principal work. What it still won't do is, it won't add the 'anchorLink' class to your new anchors. However if the clicks work then let me know and I will give you the right code to add the class too!
var anchor = '',
pageOffset = '',
viewOffset = 30,
scrollPos = '';
$(function() {
$("a[href*='#']").each(function() {
$(this).addClass('anchorLink');
});
$("a").live('click', function(e) {
if ($(this).attr("href").indexOf("#") > -1) {
e.preventDefault();
//console.log('test');
anchor = $(this).attr('href').split('#')[1];
pageOffset = $("#" + anchor).offset();
scrollPos = pageOffset.top - viewOffset;
$('html, body').animate({ scrollTop: scrollPos }, '500');
//nikhil: e.preventDefault() might not work, try return false here
}
});
});

Resources