How To AJAXify WordPress Theme

ajax wordpress How To AJAXify WordPress Theme

Chris Coyier has made a wonderful screencast about AJAXing WordPress theme. To AJAXify WordPress theme, he uses jQuery to make any internal link on the site will load into the main content area without requiring a page refresh, including search when the link is clicked. Althought the script works fine, it has 2 disadvantages: the internal links’ href property are changed (hashized) and the back/forward buttons are not supported. So I decided to improve the script to make the AJAX functionality better.

I use a blank Thematic child theme as my test theme. Just download Thematic theme and put it in theme folder (you don’t need to activate it). It contains a folder named thematicsamplechildtheme which is a sample blank child theme for Thematic. Copy it into themes folder and rename it to thematic-child, this is the theme that we will work on.

Step 1. Create needed javascript files

To support back/forward buttons while using AJAX, I’ll use the jQuery hashchange event plugin by Ben Alman, you can grab it here. After downloading, create a folder js inside theme folder (which is thematic-child/js in my test) and move the javascript file into it.

We will use a custom javascript code, so make a blank javascript file called ajax.js in the folder thematic-child/js. Our AJAX code will be put in this file.

Step 2. Register scripts in WordPress theme

To ajaxify WordPress theme, first we need to include javascript files above into our theme by using function wp_enqueue_script(). Put the following code into the functions.php file:

if ( ! is_admin() )
{
    $url = get_stylesheet_directory_uri() . '/js/';
    wp_enqueue_script( 'hash-change', "{$url}jquery.ba-hashchange.min.js", array('jquery'), '', true);
    wp_enqueue_script( 'ajax-theme', "{$url}ajax.js", array( 'hash-change' ), '', true);
}

The first line will register the hash-change script, which needs jQuery library. The second line will register our AJAX script (which I call ajax-theme), it needs jQuery and hash-change scripts. Both scripts are located in the footer for better performance.

For more information about wp_enqueue_script(), please read the Codex.

Step 3. Implement AJAX code

3.1. Get site url and place holder

Now open the ajax.js file inside thematic-child/js folder. We start our code with:

jQuery(document).ready(function($) {
    var $mainContent = $("#container"),
        siteUrl = "http://" + top.location.host.toString(),
        url = ''; 

// more code here

});

Note that jQuery need to be used in noConflict mode, so I pass the $ symbol as a function’s argument to make sure it can be used inside function (for ease, of course).

We get the place holder of our main content, which is #container in Thematic. It might be different if you use another theme. To know this section, you can use Firebug to find as in the following screenshot:

firebug How To AJAXify WordPress Theme

To get internal links, we need to know our site url, which is stored in siteUrl variable.

3.2. Add event listener to internal links’ click

After that, we will add an event to internal links’ click, which will change the url’s hash:

$(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/])", "click", function() {
    location.hash = this.pathname;
    return false;
});

The selector looks so complicated, doesn’t it? Don’t worry, it has the following parts:

  • a[href^='"+siteUrl+"']: which means all links that begin with our site’s url (internal links)
  • :not([href*=/wp-admin/]): the links don’t contain /wp-admin/ string (the links in admin dashboard). This might be the Edit post link or link to user’s profile in comment form
  • :not([href*=/wp-login.php]): the login/logout link, of course we don’t want to load content via ajax from these pages
  • :not([href$=/feed/]): and the last is feed links. This maybe the content feed link, comment feed link of whole blog or particular post. We don’t want to load content via ajax from these pages, too

So, when we click on an internal link, which is not admin link, login link or feed link, we’ll change the url’s hash to link’s pathname. For example, if our link is http://localhost/wp/a-paginated-post/, then when it’s clicked, the location will be http://localhost/wp/#/wp/a-paginated-post/.

The return function prevent browser to go to original link.

In this script, I use the delegate() function to add event listener to click event. This method is implemented in jQuery 1.4 and is recommended instead of using live() function. Unfortunately jQuery 1.4 is included only since WordPress 3.0, so if you’re using WordPress 2.9.x and ealier, use the live() method instead of:

$("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/])").live("click", function() {
    location.hash = this.pathname;
    return false;
});

Note that the href attribute of internal links are not modified. This solves the first problem in Chris Coyer’s code.

3.3. Add event listener to search form

Adding event listener to search form when it’s submitted is very similar to adding event listener to internal link’s click:

$("#searchform").submit(function(e) {
    location.hash = '?s=' + $("#s").val();
    e.preventDefault();
});

When search form is submitted, we put the search parameter and search query into url’s hash. Then prevent the default action to not redirect to search result page.

3.4. Load content when hash changed

When url’s hash is changed, we will get the new content and put it in the #container section:

$(window).bind('hashchange', function(){
    url = window.location.hash.substring(1); 

    if (!url) {
        return;
    } 

    url = url + " #content"; 

    $mainContent.animate({opacity: "0.1"}).html('<p>Please wait...</>').load(url, function() {
        $mainContent.animate({opacity: "1"});
    });
});

First, we get the current hash. If it’s empty, then do nothing. Else, we create the needed url to get content. The url needs to be added #content because we don’t want to get all page content, but only the #content section. The #content section in Thematic is the child element of #container (the only child), so when we get it, we can immediately put it inside #container.

If you use another theme, check the id of the content section with Firebug as I mentioned above and change #content to proper value.

We use the opacity animation to fade out the content, then put a “Please wait…” string to tell users that the page’s being loaded. When the page has been loaded, we just animate the opacity to 1 to show the content.

This code is simple, but it works beautifully. Because we use the hash-change library, the script works well with back/forward buttons. This solved the second problem in Chris Coyer’s code.

3.5. Wait! When page first loads

When the blog first loads, if the location is the home page (for example http://localhost/wp/), then our code works fine. But after some times you navigate through the blog and get a location of a blog post: http://localhost/wp/#/wp/a-paginated-post/, you paste it into a new tab and run. What happens? The browser still loads the homepage, not the specified page we want!

To solve this problem, just use the following code:

$(window).trigger('hashchange');

This will check the url’s hash. If it’s changed (i.e. different from default value), then the hash-change event is fired, and we get exactly the content we want.

So, our final javascript code is:

jQuery(document).ready(function($) {
    var $mainContent = $("#container"),
        siteUrl = "http://" + top.location.host.toString(),
        url = ''; 

    $(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/])", "click", function() {
        location.hash = this.pathname;
        return false;
    }); 

    $("#searchform").submit(function(e) {
        location.hash = '?s=' + $("#s").val();
        e.preventDefault();
    }); 

    $(window).bind('hashchange', function(){
        url = window.location.hash.substring(1); 

        if (!url) {
            return;
        } 

        url = url + " #content"; 

        $mainContent.animate({opacity: "0.1"}).html('<p>Please wait...</>').load(url, function() {
            $mainContent.animate({opacity: "1"});
        });
    });

    $(window).trigger('hashchange');
});

Save it into ajax.js file inside thematic-child/js folder. Refresh the browser to see how it works.

The script can be changed easily to fit your WordPress theme, and now you already have an AJAXed WordPress theme. I hope this tutorial is useful for you when implement AJAX functionality in your WordPress blog. If you have some questions or suggestions, please leave me a comment.

144 Comments

  1. The idea performs fantastic, thanks very much for taking a little while as well as environment this specific upwards, it would will need several modifications with regard to distinct concept though the idea is usually beautiful, carry on the excellent function!!!

    Reply
  2. I tried to use this and I am getting a Cannot read property 'msie' of undefined with the hash-change JS. Anyone else noticing this since I am using jQuery 1.9

    Reply
  3. Hi,

    Thanks for your post. Great stuff. Though my website is not really taking nicely to this. I’m running jQuery 1.10. I get this error in my console:

    Uncaught Error: Syntax error, unrecognized expression: [href*=/wp-admin/]

    The search form works great, but the other links on my page don’t. Could you suggest anything?

    Many thanks.

    Reply
    • The not: selectors simply require some extra single quote marks around the piece of the url it is searching eg: [href*='/wp-admin/']

      Reply
  4. I could not get this to work. I get this error:
    Fatal error: Call to undefined function get_stylesheet_directory_uri() in /………/wp-includes/functions.php on line 3995

    Reply
  5. will we still benefit with SEO when the theme is ajaxified? Will search engine understand the content?

    Reply
    • Yes. The content is not hidden, and link to other pages are still crawable and indexable. The difference here is just how we load the content when the link is clicked.

      Reply
  6. Hi. Just wanted to share that $.browser is no longer supported by jQuery 1.9 and you need to use jQuery migrate plugin or replace $.browser with $.support. Other than that.. gr8 tut. Thanks
    ” The $.browser property is deprecated in jQuery 1.3, and its functionality may be moved to a team-supported plugin in a future release of jQuery. “

    Reply
  7. NOTE: Reposting due to derpy formatting in my previous note. Mod, will you please delete my previous question? Thank you.

    I just got this working on my site, thanks for a great tutorial!

    The only problem is that when I click internal navigation links, the plugin appends the current page URL to the requested URL.

    For instance, if I’m on http://mysite.com/blog and click a link to “About”, the script attempts to load http://mysite.com/blog/#/about/, instead of the correct http://mysite.com/#/about/. You can see the issue here: http://wheek.it/gpgye

    Also, is there a way to remove the /#/? I’ve been working on this for hours, I’d appreciate any and all help!

    Thank you!
    - Brian

    Reply
  8. I just got this working on my site, thanks for a great tutorial!

    The only problem is that when I click internal navigation links, the plugin appends the current page URL to the requested URL.

    For instance, if I’m on http://mysite.com/blog and click a link to “About”, the script attempts to load http://mysite.com/blog/#/about/, instead of the correct http://mysite.com/#/about/. You can see the issue here:

    Also, is there a way to remove the /#/? I’ve been working on this for hours, I’d appreciate any and all help!

    Thank you!
    - Brian

    Reply
  9. It would be great to update this tutorial to use History API, so you don’t have to use hash. Best way to do that would be using History.js as it nicely degrades to hash for browsers that are lacking support. Ajax works fine with this, even in IE6.

    Reply
  10. Thanks for this great tutorial, good explanation and easy to setup. With the help of comment from darorck it works fine on latest WordPress release (3.5.1).

    The only problem is how to make posting a new comment not reloading the page and displaying the new comment directly. This issue inhibits me to use my ajaxified theme on a production site. Would really love to implement it without a plugin but even can’t find a suitable WordPress plugin which actually works.

    Reply
  11. Hi!

    This works really good in most browsers. But guess what! Not in Internet Explorer. Not as it should anyway.

    It works to go from the startpage to other pages.

    How it should look: domain.com/#/newpage

    In IE: domain.com/#newpage – Notice missing slash.

    How do I make it work in IE?

    Thank you!

    Reply
  12. Thanks a lot, it took some time, but i have made it working in my theme:-))

    Reply
  13. Hey guys, I think this tutorial is going to be super useful (seems like it already has). I am having a little trouble with getting the second step down though (Register scripts in WordPress theme) I just can’t seem to get them working. Any help would be awesome.

    Reply
  14. Cheers for this – works like a charm. It does however need updating for the latest version of jQuery.
    One thing which may come in handy for other folks is the changing of the “current-menu-item” class for CSS styling.

    Adding the below code sorts that out (you will have to adjust according to your themes needs).

    $(function() {
    $(‘#menu-top-nav li’).click(function() {
    $(‘#menu-top-nav li’).each(function() {
    $(this).removeClass(‘current-menu-item’);
    });
    $(this).addClass(‘current-menu-item’);
    });
    });

    Hope that helps someone out.

    Reply
  15. Awesome tutorial! Ajax has been one of those last remaining issues I’ve always wanted to use on my wordpress websites. This tutorial was simple enough for me to understand and implement it on a custom theme and control how I pull information. Thank you so much for this tutorial!

    Reply
  16. If you are having issues loading the home page (it goes to yourwebsite.com/#/ and fails)

    Change the code to add an if statement that wraps around ” url = window.location.hash.substring(1);”

    Like so:

    $(window).bind(‘hashchange’, function(){
    if (location.hash != “#/”) {
    url = window.location.hash.substring(1);
    };

    Reply
    • Does the location of where we integrate these lines of code in ajax.js matter?

      Thanks!

      Reply
  17. i use wp ver 3.5 and have this url: http://localhost/wordpress

    what i have to put in


    siteUrl = "http://" + top.location.host.toString(),
    url = '';

    I have never used AJAX or PHP before so I would love it if someone could help me out or point me in the right direction.

    Thanks,

    Reply
  18. This is the best ajax tutorial :)

    Thank you for this, I have made my client very very happy :)

    Reply
  19. Very good tutorial and very flexible. Right now, with the WP 3.5 and the update to jQuery 1.8.3 it need a little fix in this script as .delegate() has been superseded by the .on() method since jQuery 1.7:


    $(document).delegate("a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/])", "click", function() {
    location.hash = this.pathname;
    return false;
    });


    $(document).on("click", "a[href^='"+siteUrl+"']:not([href*='/wp-admin/']):not([href*='/wp-login.php']):not([href$='/feed/'])", function() {
    location.hash = this.pathname;
    return false;
    });

    Reply
  20. Thanxs for the tutorial.

    I´ve try but not load the content of posts. Only i can see the “Please wait…” but after that doesn´t appears.

    Where is the error?

    Any idea?

    Thanxs

    Reply
  21. Nice but i think that too much Ajax on a page is not good for the users. So u have a Problem when u use Ajax and load the site in a div and the user want back form site b to site a and take the Browser back function. When the user take this, the sidebar stands also on site b but in the Container Dive he see site a.

    Reply
  22. Hi,
    I would like to display a list of posts for cat 5 by default, and with tab menu option to display posts from different categories when clicked.

    Something like in dealspl.us when a menu tab is clicked, the new content would load dynamically.
    I know you can load .html file but with wordprss and .php files. How do I do it? Thanks and
    your help is appreciated.

    thanks

    Reply
  23. Very cool! Does anyone know if loading pages like this affect SEO at all? Just wondering if spiders will be still be able to crawl ajaxed pages.

    Reply
  24. How can we transfer the current-menu-item class to the active page menu link?
    It is always active on the home menu link, no matter what menu link i clicked.

    Any ideas?

    Reply
  25. The tutorial was great, and I’m really close to installing the ajax load function. Thanks for putting these instructions together!

    However, the ‘Download Javascript file” link isn’t working. Do you think you can update this when you get a chance?

    Thanks so much!
    - Brian

    Reply
  26. works great. but my installed plugins doesnt work anymore. specially contact form 7. when i click submit or send. it loads a blank page. and also on my homepage. the jj-nextgen-slider works fine at first load, but when i click for example on about us, then click again on home, the slider doesnt work anymore.

    Reply
  27. Hi, does anyone know how to turn off ajax load only for single post click, to load single page without ajax.

    Reply
    • I have successfully edited this script by adding some extra exclude code to the $(document).delegate section… depending on your permalink structure this can be a simple process by just excluding the single-post permalink category for example… I have added a bunch of lines to exclude most pages on the site except for single pages in certain post-types or categories, and by utilizing the %category_type%/%post_name%/ permalink structure.

      Reply
      • Hi, tnx for answer, i still cant exclude ajax for simple page, i know that need to edit delegate, my permalink structure is /%category%/%postname%.html , i have try something like this to exclude /clothing/post name.html
        $(document).delegate(“a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/]):not([href$=/clothing/])”, “click”, function() { ….. } but no success still open with ajax.

        Reply
        • luckily, i think i know this one too! try :not([href*=/clothing/*]) instead of :not([href$=/clothing/]) i think the * instead of the $ makes it expand to a wider range of pages. you do not need to add the .html extension to ANY wordpress pages or permalink, so I would recommend updating your permalinks without .html but instead with a / at the end of them. You may need to click update twice for it to fully update your website.

          Hope this helps!

        • Good day, why no one answeared my comment? is it available to use ajax with ?page_id= permalink? and what means :not([href$=/clothing/]) ???

          #comment-35298

        • I have tried with * in place of $, also i have change my permalinks but still open with ajax

        • I used :not([href*=/news/*]) for my single pages in the “news” category and it works. I’m sorry I don’t have anymore suggestions for you.

  28. Good evening. i have problem! i couldn’t find anything i need about ajax loading, but at last i have came here, done everything in this tutor and after also dl’ed it! but cant fix the problem cause of lack of knowings!
    Some of plugins aint working anymore or aint getting styling if they have them in their specificated folder, also wp-panel have lost their images (now there is blank blocks), and when i’m try to go on other language page of my wulti-website with language-bar-flags plugin i get http://url/#/en and cause of that it does nothing! please help or send me some alternative ajaxify method!
    thank you!

    Reply
    • good day! Found another problem, this script works only with “/blog/”permalink, but with default “?page_id=1″ aint working!

      Reply
  29. Hi, we keep getting an error in IE 7 & 8 saying this: *Syntax error, unrecognized expression: [href*=/wp-admin.php/]* Can you possibly advise on what the issue is and maybe how to correct it? Thanks, and I’ll look forward to a quick reply!

    Reply
    • I know your comment is over a year old but just in case anyone is wondering you need to escape the forward slash. The expression would look like this:

      [href*='/'wp-admin.php'/']

      Reply
  30. Hi,
    I am using ajax to load the content, and perfect till there.
    But I am having problems with the page being loaded. I don’t know how to load the plugins I need to get the info shown.
    I mean to initialize WP and use the plugins I need.
    I have
    require(‘../../../../wp-blog-header.php’);
    But it des not initialize the plugins.. any help?

    Thanks!!!

    Reply
  31. Definitely imagine that which you stated. Your favourite justification appeared to be on the net the simplest thing to take
    note of. I say to you, I definitely get irked at the same time as folks think about issues that
    they plainly do not recognise about. You managed to hit the
    nail upon the highest as neatly as defined out the whole thing
    without having side-effects , people can take a signal.
    Will likely be back to get more. Thank you

    Reply
  32. Can anyone tell me how to adjust this code to have a loading image instead of the “Please wait…” text? I have seen it done on other sites : http://themeclubhouse.digwp.com/ but am having a hard time deciphering how this could easily work with the above code, which is spectacular although somewhat daunting at first glance! Just what I needed to meet my clients needs… any help or links to threads/tutorials would be wonderful! Thanks

    Reply
      • I’m sorry, looks like my code was clipped. Let’s try this again:

        “”

        Reply
        • The code is still clipped, would love to see what you have! Perhaps e-mail it to me at skiddysmith at gmail dot com?

          Thanks

      • I’m experiencing the same issues with the back button updating the URL but not changing the browsers content correctly.

        Reply
  33. Hi there, I’m actually having an issue implementing this with Contact Form 7.

    Contact Form 7 uses Ajax too and when I navigate to the page with the contact form and click “submit” it actually refreshes my page. If I navigate directly to the contact form page (without the hash in the URL) it works as expected.

    I tried to build upon your example of the search form but have not had much luck. Any help would be greatly appreciated.

    Thank you!

    Reply
  34. Thank you for the awesome tutorial. Very concise and enlightening! I love that you took the time to explain each step.

    Reply
  35. Hey there nice Tutorial!
    But some i got some little issues..
    When you click the Send Comment Button I had to ask if a Comment hash has been added and if so it will be handled normal (not loaded with ajax) ->

    `if (url.indexOf(“comment”)!= -1) { return; }`

    Also i had to add this request when someone clicks the “Reply” Link to reply to a comment ->

    `else if (url.indexOf(“respond”)!= -1) { return; }`

    Hope this helps someone!

    Greetings Benny

    Reply
  36. I keep listening to the reports lecture about receiving boundless online grant applications so I have been looking around for the top site to get one. Could you tell me please, where could i acquire some?

    Reply
  37. this is the script with this it works in jquery but it does not load the specific post:

    $(document).ready(function(){
    $(“.project-thumbnails a”).click(function(event){
    event.preventDefault();
    $(‘#project-container’).slideDown(‘slow’);
    return false;
    });

    $(‘a.project-close’).click(function(event){
    event.preventDefault();
    $(‘#project-container’).slideUp(‘slow’);
    return false;
    });

    });

    how can i combine it with yours?

    Reply
  38. hey master, how can i trigger a hidden div with this ajax script within with an onclick handler?
    this is my site: http://microle-systems.com/wordpress3/thegrunt/
    i would like to include your script but not in content => it should be inside a hidden div with opens up
    by onclick on detail-link. hope you got an idea. best regards from germany

    Reply
  39. i have the above ajax working perfectly however when i am in a post (ie.post-1) and click to the next post (post-2) the ajax loads the new content however my url goes from: **mysite.com/post-1** to **mysite.com/post-1/#/post-2/**

    how do i get rid of the unwanted post in the url??

    Reply
    • I would love to know this too!! Also is this technique SEO friendly?

      Reply
  40. ^ ^
    Should of looked at the comments more closely. Olivier.b (Thank you) has all the answers. I’ve got it working. I’ve also got some fancy animations within the AJAX call. If anyone is interested I’ll post once its working sound.

    Ta

    V

    Reply
    • Hey Victor,

      I’d be very keen to see what your’ve come up with.. :)

      also do you have issues with spaces in the search box?

      thanks

      Reply
      • Hi Rob

        Here’s what I have so far. My site isn’t live so I can’t show you it. I have some expanding divs and bits like that because it a portfolio site.

        http://pastebin.com/aTyKutUk

        I haven’t added a search function (yet?) so I haven’t encountered the search box issue. I’ll paste the full thing once I get it completed.

        V

        Reply
  41. Hey – I managed to get this working pretty fast, Thanks for the tut…. but I can’t seem to get it working in OPERA. It seems that Jquery isn’t adding the # in the url so the page redirects rather than firing. If I manually add the # to the url it works. So i’m guessing it’s somthing to do with internal links bit.

    Can anyone help?

    Ta

    V

    Reply
  42. Does anyone else have issues in the search box when using a search term with a space??
    searching for “Hello” will bring up the Hello World post. but searching for “Hello World” bring a blank screen?

    It also does this on the demo version

    please help.

    Reply
    • This is how I fixed this white space in search terms issue:

      $(“.searchform”).submit(function(e) {

      $search = $(“#s”).val();
      $search = $.trim($search);
      $search = $search.replace(/\s+/g, ‘+’);

      location.hash = ‘?s=’ + $search;
      e.preventDefault();
      });

      This will remove the white spaces and replace them with ‘+’ in the url. Hope this helps!

      Reply
  43. My simple fix for IE browser.. ;-)

    $(document).delegate(“a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/])”, “click”, function() {

    if ($.browser.msie) {
    var myie = “/” + this.pathname;
    location.hash = myie;
    //alert(location.hash);
    }else{
    location.hash = this.pathname;
    }
    return false;
    });

    Reply
    • thanks for your help!! but can you tell, where should i put this code…?

      please help me..!

      Reply
      • jQuery(document).ready(function($) {

        var $mainContent = $(“#container”),
        siteUrl = “http://” + top.location.host.toString(),
        url = ”;

        $(document).delegate(“a[href^='"+siteUrl+"']:not([href*=/wp-admin/]):not([href*=/wp-login.php]):not([href$=/feed/])”, “click”, function() {

        if ($.browser.msie) {

        var myie = “/” + this.pathname;
        location.hash = myie;
        //alert(location.hash);

        }else{

        location.hash = this.pathname;

        }

        return false;
        });

        $(“#searchform”).submit(function(e) {
        location.hash = ‘?s=’ + $(“#s”).val();
        e.preventDefault();
        });
        $(window).bind(‘hashchange’, function(){
        url = window.location.hash.substring(1);
        if (!url) {
        return;
        }
        url = url + ” #content”;
        $mainContent.animate({opacity: “0.1″}).html(‘<p>Please wait…</>’).load(url, function() {
        $mainContent.animate({opacity: “1″});
        });
        });
        $(window).trigger(‘hashchange’);
        });

        Reply
        • This is true till IE 8, IE 9 and 10 don’t need this fix so the condition has to be changed to:

          if ($.browser.msie && $.browser.version != 6.0 && $.browser.version != 7.0 && $.browser.version != 8.0) {
          var myie = "/" + this.pathname;
          location.hash = myie;
          }
          else {
          location.hash = this.pathname;
          }

        • My last comment is not true. The fact is that the condition works till IE 9, for IE 10 you have to make an exception changing it like that:


          if ($.browser.msie && $.browser.version != 10.0) {
          var myie = "/" + this.pathname;
          location.hash = myie;
          }
          else {
          location.hash = this.pathname;
          }

  44. I am having trouble getting this to work on pages other than the home page – I put a version of it in the footer of my site to help people find store locations, and it works on the home page, but when the url is something like http://www.ojosmovement.com/retailers/#?s=portland it just waits and waits and never loads a result.

    can someone help me out?

    Reply
  45. thanks for this tutorial – I had it up and running in no time!

    I wanted to post here to say that people may have problems with this on their sites because the implementation of .load(), in this case specifying a target div to load the content into, strips any scripts from the retrieved page. This could explain some of the behaviors people have posted about.

    Reply
  46. Fantastic tutorial! A question though– how would you change the code if you want to ajaxify content on a particular page rather than site-wide?

    Reply
  47. In some themes, when you click on an internal link, the sidebar also changes. Does it make sense, and is it possible to enlarge the scope, and instead of working with #content, work with #main (at least in thematic theme).

    Reply
  48. hi, thanks for this nice tuto. I’ve managed to get a nice “ajaxified” wordpress 3.3 site using thematic theme.

    i can’t give the address for now, but as soon as it is online i will share my work.

    Here are a few tips to help :

    - for ie, add :

    if ($.browser.msie) {
    url = “/” + url;
    }
    to correct the bug of the missing / in the url

    - for ie8 and opera, add the missing quotes into the line

    $(document).delegate(“a[href^='"+siteUrl+"']:not([href*='/wp-admin/']):not([href*='/wp-login.php']):not([href$='/feed/'])”

    (for each href*=’ ‘)

    - for all browser : The .load() function strip out javascript from loaded content, and javascript from first loaded page can’t target newly loaded selectors. My solution was to put my jquery events into the .load() callback function.

    exemple :

    $(“#content”).load(url, function() {
    $(“#main”).animate({left: “+=385″}, 500, ‘swing’);

    $(“.titre”).click(function(){
    $(“.titre”).removeClass(‘current’);
    $(this).addClass(‘current’);
    });

    $(‘.soustitre li’).click(function(){
    $(“.soustitre li”).removeClass(‘current’);
    });
    }

    Reply
    • Olivier.b I would appreciate a final-complete example of your project cause im using ajax for all plugin which is very similar to this but in ie8 it refreshes the header picture and logo. By

      Reply
    • Thanks for the tips! Where is the best location to add the “if ($.browser.msie)” lines of code? Thanks!

      Reply
  49. You used Thematic theme as an ajaxify example. Could I use the same code in a 2011 WordPress Child Theme?

    Reply
  50. Hello,

    first i would like to thank you for the great tutorial. It works perfectly.

    I have a question.
    In my page I have different .js files, all with jquery. On of them features an animation of pictures, turning from black and white to coloured pictures.

    For the record, this is the fade.js file, which doesn’t work anymore after implementing the ajaxed request.

    $.noConflict();
    jQuery(document).ready(function($){
    }

    $(“img.person”).hover(
    function() {
    $(this).stop().animate({“opacity”: “0″}, “slow”);
    },
    function() {
    $(this).stop().animate({“opacity”: “1″}, “slow”);
    });

    });

    Best, Timo

    Reply
  51. Hi. I tried to combine it and wanted to load a jcarousel with and he gave me this bug : $(‘#mydiv’).jcarousel is not a function. Do you have any idea why it’slike this?

    Reply
    • The bug seems to say that the jcarousel hasn’t been loaded. You should view the source to check that.

      Reply
  52. Hey. Thanks for a great tutorial.
    I’m having a little problem. The first link in my menu keeps having the class “current_page_item” even though it is another pages content that is being shown.
    Have I missed something?

    Reply
    • I’m having the same/similar problem! “current-menu-item” isn’t working for me any more. Once I ajax-ified, It was only highlighting one menu item (same one over and over), and now it’s not highlighting anything at all. Did anyone find a solution to this or a workaround? Thanks in advance!

      Reply
      • Did you find a solution for this? I would like similar functionality and not sure how to adjust! Thanks

        Reply
  53. Actually figured out a simple fix for IE, just change the permalink in WordPress to custom and add a another / in the front. So mine is: /%/%postname%/ .

    Reply
  54. Works great for Chrome and Firefox but seems to be an issue with IE 9. The # is missing the trailing slash when loading it in IE, would anybody happen to know how to fix this issue? Thanks.

    Reply
  55. That would be great to maintain the scripts working. I haven’t tried yet, but will only use it if there’s a way…

    Reply
  56. That’s a great tutorial! You did a great job explaining each detail and I followed along with ease even though I’ve never tried AJAX before.
    I was able to get it working, and even write a further conditional to only target pages that begin with a specific word. However, no matter what I have tried, the javascript and jQuery script do not execute on the page that’s loaded into the div container, I’ve tried placing the scripts in the actual container.

    Any tips?

    Reply
    • Hey Frank,

      You’ll have to call your javascript as a callback after the .load function. jQuery .load strips javascript out of the content being loaded. for example:
      $mainContent.load(url, function() {
      $mainContent.fadeIn(500);
      //your extra javascript here to be executed on loaded content
      });

      email me if you need help and I can walk you through it

      Reply
  57. Hello,

    Thank you for this tutorial. Is there a way to make it run for Internet Explorer 8 ?

    Reply
  58. Hi, all smartly works! )) But there was a problem! after receipt of the contents of scrolling does not work! how to make it work?

    Thank you!

    Reply
  59. Hi! I have a problem with the hashtags and navigating to frontpage. I don’t use this method at the frontpage, I use it on subpage to show my work. Navigation to Work page works nice, because of this -> :not([href*=/work/]). But I cannot go to frontpage anymore, because I don’t know what to write to event listeners. Any thoughts for this?

    Thanks!

    Reply
    • For the record, I solved the frontpage problem with a redirect plugin. I made a new page called “Home” and redirected it to real frontpage.

      Reply
  60. Great it works for the most part. There is a problem when users click the submit button for Bbpress and contact forms.
    The the ajax call keeps on loading loading loading.

    Reply
  61. Thanks for the tutorial. It works fine with wp 3.2.1 too. Is there a way to use this with multiple menus and containers? I tried to by changing $(document).delegate to the id of each menu, changing the variable mainContent in every version and container and content id but it shows me the please wait… in the right container but not the loaded conten is shown in the 1st container. Any idea how it will work?
    Thanks.

    Reply
  62. Mine works fine! Just, widgets doesn’t load… Any help on that?
    Tnx…

    Reply
    • I would love an answer to this question. I’m trying to do the same myself so I can incorporate Disqus.

      Reply
  63. oh… i need your help to. would like to see the demo file… i´m working on my site but without much success… take a look: http:www.thousandrottenkings.com

    Reply
    • I think u apply this technique in this comment box also. But the mail feature I want is not detected here. If a user does not fill Name and Email field, wordpress redirects to a new error page. I want to get rid of this redirection… It happens here too.

      Reply
  64. I need your help please.

    Trying to get this working in my theme, I copied over the js directory with both scripts into my theme. Added the if statement to my functions.php.

    Now no of the links work. I do see the hash in the url.

    I’m a n00b at coding for WordPress and I don’t know php. Only C and QuakeC.

    I would appreciate any help. Thank you in advance, have a great weekend.

    Reply
  65. Hi guys, me again.
    I love this script and tutorial. It works beautifully where it works but somehow there is something within the code that at least works differently with wp 3.2.1. Here is what I tracked down.

    Landing page is ok when loaded.
    I can click a post and it fades in.
    I can click a different page on the menu and it fades in.
    If I click the “Home Button” (which is linked to the landing page), the text “Loading…” appears but nothing is loading.
    Same happens if I click to a category that is listed in the sidebar (which is linked to the archive.

    I noticed this:
    The tutorial says that the link (created with the hashchange plugin) should look like this.
    http://localhost/wp/#/wp/a-paginated-post/

    but my link looks like this
    http://localhost/wp/#wp/a-paginated-post/

    Can you see the difference? The slash between # and wp is missing. as soon as I add this slash to the address, the content gets loaded.

    Does anybody know what I could change on the script to make it work properly? I would appreciate your help very much because this here is the best ajax approach for wp that I found on the net.

    Reply
  66. Does not work with 3.2.1
    Will this be updated? Actually I liked what I saw but it was not loading when clicking the category links in the sidebar and not when using the “Back Home Button”. I am usin “Wostok”, yes with a W and not with a V.

    Reply
  67. it works great, thank you very much for taking some time and setting this up, it might need some changes for different theme but the concept is beautiful, keep up the good work!!!

    Reply
  68. can anybody confirm whether the script works in WP 3.2.1 or not?

    Reply
  69. thanks, this is great.
    however, i got two problems: nextgengallery doesn’t work and all audio players don’t work. what i tried: excluding mp3 and jpg links via :not([href*=.mp3]):not([href*=.jpg]). this helps only in that jpgs now open in the same browser window, but the thickbox of nextgengallery doesn’t work, and mp3 links or [audio] embeddings still don’t work.
    also only delegating links from my navigation bar via “$(document).delegate(“#menubar a”, “click”, function() {” does NOT help with the gallery and audio player, although they obviously occur in a different div, not in #menubar.

    any idea what i could do?

    Reply
    • i found out, that i case of the mediaplayer the flash somehow isn’t loaded. so it’s not an issue concerning the link (because it isn’t clicked yet) but something else. any idea anyone?

      Reply
  70. cant get this to work.. :S 
    atm the url changes correctly but it isnt loaded into the div, im quite sure those names are correct tho. am i supposed to have a loop inside the div where content is placed or should that be empty ?

    Reply
  71. I use fancy box for my images…it works when you first load any page, but if you then navigation and load a new page, it no longer works.

    Reply
    • Oh I think you should change the jQuery selector for links that shouldn’t be ajax (like your popup images). This is different on each blog so I can’t tell you exactly how to do it.

      Reply
      • But could you give an example? This might help all of the people on here that are asking the same question. I.e with a link that is image here how would you add a selector or whatever to allow the lightbox script to popup?

        Reply
    • Anyone find a solution to this issue? I’m using colorbox and am having a similar problem. Image does actually open in colorbox, which is great, but it also changes the page to the URL for the image, instead of staying on the originating page.

      For example, if I click on the image on the home page, the image opens in the modal overlay, but the page behind it is no longer the home page, but a page with an empty content area, but the URL of the image.

      Suggestions?

      Reply

Leave a Reply