Category: AJAX

Manipulating browser URL using Javascript without refreshing the page

In modern browsers, one of the most interesting feature is that you can change the browser url without refreshing the page. During this process you can store the state of the history so that you can pull the necessary data when someone hits the back-button in the browser and then take necessary action based on that. It’s not as complicated as it may sound now. Let’s write some code to see how it works.

[sourcecode language=”javascript”]
var stateObject = {};
var title = "Wow Title";
var newUrl = "/my/awesome/url";
history.pushState(stateObject,title,newUrl);
[/sourcecode]

History objects pushState() method takes three parameter as you can see in the above example. First one, a json object, is very important. Because this is where you will be storing arbitrary data related to the current url. Second parameter will be the title of the document, and third one is the new url. You will see your browser’s address bar is updated with the new url, but the page was not refreshed 🙂

Let’s see another example where we will be storing some arbitrary data against each url.

[sourcecode language=”javascript”]
for(i=0;i<5;i++){
var stateObject = {id: i};
var title = "Wow Title "+i;
var newUrl = "/my/awesome/url/"+i;
history.pushState(stateObject,title,newUrl);
}
[/sourcecode]

Now run and hit the browser back button to see how the url is being changed. For each time the url is changed, it is storing a history state object with the value “id”. But how can retrieve the history state and do something based on that. We need to add an event listener for “popstate” event which is fired everytime the history object’s state is changed.

[sourcecode language=”javascript”]
for(i=0;i<5;i++){
var stateObject = {id: i};
var title = "Wow Title "+i;
var newUrl = "/my/awesome/url/"+i;
history.pushState(stateObject,title,newUrl);
alert(i);
}

window.addEventListener(‘popstate’, function(event) {
readState(event.state);
});

function readState(data){
alert(data.id);
}
[/sourcecode]

Now you can see whenever you hit the back button, a “popstate” event is fired. Our event listener then retrieves the history state object which was associated with that url and prompt the value of “id”.

It’s easy and pretty interesting, eh?

Caching Ajax requests in WordPress

In modern WordPress themes, theme developers are serving the page requests via ajax. Both paginated blog page and single posts (might be in full or partial) are served. Though WordPress is very fast if properly tuned, but it’s meaningless to pull the same data from WordPress database again and again unless there is any change. Which means, you can safely cache such ajax requests and reduce loads on your database by adding a few lines of extra code in your theme’s functions.php. In this article, we will learn how to take advantage of such caching in WordPress

Step 1: Register Ajax callback for serving paginated blog pages
Here is a typical codeblock that can serve paginated blog pages via ajax. There is no caching yet
[sourcecode language=”php”]
add_action("wp_ajax_blog", "get_blog");
add_action("wp_ajax_nopriv_blog", "get_blog");

function get_blog(){
global $post;
$page = $_REQUEST[‘page’];
if(!$page) $page=1;
$pp = get_option("posts_per_page");
$offset = ($page*1-1)*$pp;
$args = array(
"posts_per_page"=>$pp,
"offset"=>$offset
);
$posts = get_posts($args); //get the posts
foreach($posts as $post){
setup_postdata( $post );
get_template_part("templates/post",get_post_format($post->ID));
}
die();
}
[/sourcecode]

Now if you go to the url “http://your_blog_url/wp-admin/admin-ajax.php?page=1 ” you can see the latest posts, change the page value to 2,3,4 and so on to see previous posts. Each posts in the loop are rendered via get_templates(). Please note how we used the get_post_format() function in the loop to serve different templates based on post formats.

So what is bad in this code? Nothing, yet Everything! If 100 users are visiting your blog and they are visiting blog pages, each and every time these posts are pulled from database. Each and everytime they are pulling the very same data until you had edited any post, or created a new post. So why this extra load should go to DB? lets minimize it 🙂

Step 2: Add caching layer
here is a revised format of the code block above, but now with caching.
[sourcecode language=”php”]
add_action("wp_ajax_blog", "get_blog");
add_action("wp_ajax_nopriv_blog", "get_blog");

function get_blog(){
global $post;
$page = $_REQUEST[‘page’];
if(!$page) $page=1;

/** supply from cache **/
$page_from_cache = get_option( "artpress_page{$page}", 0 );
if($page_from_cache){
die($page_from_cache);
}
/** cache end **/

$pp = get_option("posts_per_page");
$offset = ($page*1-1)*$pp;
$args = array(
"posts_per_page"=>$pp,
"offset"=>$offset

);
$posts = get_posts($args);

ob_start();
foreach($posts as $post){
setup_postdata( $post );
get_template_part("templates/post",get_post_format($post->ID));
}
$new_cache = ob_get_flush();

/** save the cache **/
update_option( "artpress_page{$page}",$new_cache);
/** end cache **/
die($new_cache);
}
[/sourcecode]

In the code above, we first checked the page number. Then, checked in the wordpress options table if there is a cache present with a key named “artpress_page”. Now, for the first time it wont be there. So we just pull the records from the database as usually and then using the output buffering functions we capture the output, instead of pushing instantly to the browser. And then we update the options table with this output. So next time when same page will be requested, database wont be hit. Ok, database will be hit (this options table data is coming from the db) but you can see it wont touch the posts table again, and avoid running expensive queries (which includes many joins) in that table. It also saves CPU a bit.

Step 3: Invalidate cache whenever a post is edited, or created
This is an important step. We need to flush the cache whenever a new post or page is created to make sure our blog shows the up to date data.

[sourcecode language=”php”]
add_action("save_post","invalidate_cache");
function invalidate_cache(){
$counts = wp_count_posts();
$total_published_posts = $counts->publish;
$posts_per_page = get_option( "posts_per_page");
$total_page = ceil($total_published_posts/$posts_per_page);
for($i=1;$i<=$total_page;$i++){
delete_option( "artpress_page{$i}" );
}
}
[/sourcecode]

Now, we are in good shape. Our ajax requests are served from cache and properly purges whenever necessary. You can serve your single post same way.

If you want to serve single posts from the cache, one thing you need to keep in mind is that you are loading up an important table “options” with a lot of data. So you can change the code above and store the cache in filesystem instead of options table. You should have write permission in the uploads directory by default. So that wont be tough at all.

I hope you enjoyed this article 🙂

Displaying comments template when serving a single post via ajax in wordpress

I ran into this issue this morning, the comment form wasn’t showing up. I was using a custom comment template and I thought that there might be some issue with the custom template. So I tried with default template but the result was same. After googling for a while, I’ve found the workaround. Here is the solution for you

[sourcecode language=”php”]
//functions.php
add_action("wp_ajax_single", "get_single");
add_action("wp_ajax_nopriv_single", "get_single");

function get_single(){
error_reporting(0); //see later to understand why it is here
global $post;
$post_id = $_REQUEST[‘id’];
if($post_id){
$post = get_post( $post_id);
setup_postdata( $post );
get_template_part( "templates/single");
die();
}
}
[/sourcecode]

The code above registers an ajax callback for accepting GET/POST calls at “/wp-admin/admin-ajax.php?action=single&id=” and display the single post using the template file located at “templates/single.php” in your current theme.

Now, in the “templates/single.php” you must include the following code-block at the top to make sure the comments_template() function work

[sourcecode language=”php”]
global $withcomments;
$withcomments = true;
[/sourcecode]

Anyway, it was also mentioned in the codex like this, but I was confused as I thought it was actually inside the “single display” at first 🙂

Loads the comment template. For use in single Post and Page displays. Will not work outside of single displays unless $withcomments is set to 1.

By the way, that error_reporting(0) line is there to suppress a deprecated notice which says that your theme is missing “comments.php” even if it’s there.

Hope you enjoy this article

We are close to release Orchid, the new Framework

orchid framework

Am I talking about another framework? Well yeah. I thought it will be real fun for web application developers to use orchid to build their apps. Orchid is still in preview state and we are planning to release it by the mid of January. But if you are interested you can check the orchid blog and checkout the nightly build version from svn repository. Orchid is very fast and lightweight and really painless to kickstart the development.

URL : http://orchid.phpxperts.net

Some of the core features of Orchid which I think are really helpful to develop real world applications, are listed here

1. Caching Engine with support of Memcache, MySQL and SQLite as Storage
2. MVC
3. RoR like Layout and segregated template components.
4. Partial Caching in Template
5. Very efficient object loading and dispatching
6. DAL for MySQL (Both MySQL and MySQLi), SQLite, PostgreSQL and MSSQL
7. Support for PDO
8. Builtin Unit Testing Library where you can write unit tests inside the controller without extra pain.
9. Internationalization using Language files
10. Session Manager (Regular and DB Based)
11. Bundled Google Map Library
12. Bundled Google Chart Library
13. Bundled JSON Library
14. Bundled Prototype, jQuery, Scriptaculous and SWFObject Scripts with on-demand gzip support
15. On demand gzipping for javascripts
16. Active Record
17. Excellent Benchmarking and Profiling support which you can use to profile your application
18. CSS based Button Manager (What is this???? — checkout)
19. AJAX Library

Beside many other features it also comes with an exceptional feature which is hard to find elsewhere 🙂 which is the following one

20. Bundled “Colorful Moments”

🙂

Orchid is planned to release by mid januray, as I told. Currently some of us are working on documentation. But you can still check out the code and sample controllers.

Ifthese sounds interesting – you can visit the official blog of orchid at http://orchid.phpxperts.net

List of RSS Feeds I read almost everyday

I am sharing a list of RSS feeds that I read almost everyday. And which one is my favorites RSS reader? Well, I use GoogleReader because of it’s excellent features like star and feed history. also I like it’s feed sharing feature.

1. Ajaxian : http://www.ajaxian.com/index.xml
2. Cow’s Blog : http://cow.neondragon.net/xml.php
3. IBM Developer Works (Web) : http://www.ibm.com/developerworks/views/web/rss/libraryview.jsp
4. IBM Developer Works (Open Source) : http://www.ibm.com/developerworks/views/opensource/rss/libraryview.jsp
5. Designer Folio : http://feeds.feedburner.com/dezinerfolio
6. Digg Technology : http://digg.com/rss/containertechnology.xml
7. DZone Latest Front Page Links : http://www.dzone.com/feed/frontpage/rss.xml
8. Freelance Switch : http://feeds.feedburner.com/FreelanceSwitch
9. HacksZine : http://hackszine.com/index.xml
10. International PHP Magazine News : http://www.php-mag.net/magphpde/psecom,id,26,noeid,26,.html
11. JSLabs High Performance Web Apps : http://feeds.feedburner.com/jaslabs
12. LifeHack : http://www.lifehack.org/feed/
13. Mashable : http://feeds.feedburner.com/Mashable
14. Maxdesign : http://www.maxdesign.com.au/feed/
15. Newsvine (PHP) : http://www.newsvine.com/_feeds/rss2/tag?id=php&d=v
16. PHP Freaks : http://www.phpfreaks.com/feeds/articles.xml
17. PHP Magazine : http://www.phpmagazine.net/syndicate.xml
18. PHP Coding Practise: http://php-coding-practices.com/feed/
19. PHP Developer : http://phpdeveloper.org/phpdev.rdf
20. PHP Geek : http://www.phpgeek.com/wordpress/feed
21. PHP Architct News : http://www.phparch.com/phpa.rss
22. Planet Ajaxian : http://planet.ajaxian.com/index.xml
23. Planet PHP : http://planet-php.org/rdf/
24. Programmable Web : http://feeds.feedburner.com/ProgrammableWeb
25. ROScripts : http://feeds.feedburner.com/ArticlesAndProgrammingTutorials
26. Sitepoint Blogs : http://www.sitepoint.com/blogs/feed/
27. Sitepoint News : http://www.sitepoint.com/recent.rdf
28. Smashing Magazine : http://www.smashingmagazine.com/wp-rss.php
29. Jonathan Snooks Blog : http://snook.ca/jonathan/index.rdf
30. TechCrunch : http://feeds.feedburner.com/Techcrunch
31. Technorati Javascript Links : http://feeds.technorati.com/search/Javascript
32. Technorati PHP Links: http://feeds.technorati.com/search/PHP
33. Veerle’s Blog : http://feeds.feedburner.com/veerlesblog
34. Web2List : http://feeds.feedburner.com/Web2list
35. Zen Habits : http://feeds.feedburner.com/zenhabits
36. Del.icio.us PHP Tags : http://del.icio.us/rss/tag/php
37. PHPExperts Forum : http://rss.groups.yahoo.com/group/phpexperts/rss
38. 456 Berea Street : http://www.456bereastreet.com/feed.xml
39. Particle Tree : http://feeds.feedburner.com/particletree
40. Simple Bits : http://simplebits.com/xml/rss.xml

Javascript For Living?? Oh hell yeah….

I just came across this article in Ajaxaian where Dion Almaer rant what you need to do when you code JS for living!!! Some says that pure JS is nothing, some says that just JS cant take you anywhere. I agree partially with Dion’s thought and wants to add something by myself.

Well, you can do pure JS for living as I am doing right now. Beside lots other tasks in pageflakes, I write huge amount of JS everyweek to develop flakes as a development engineer. Beside that I also maintain the community, study JS in the user submitted flakes and support them to write efficient JS. If you neglect JS as a language, you are doing a big mistake. JS is extremely powerful and you can do things beyond your imagination with it.

I want to add some tips beside dion’s suggestions. You also need to do the following if you really want to live by coding JS.

1. DOM Scripting is a Must, but not all, simple Node operations will do.
2. Interacting with CSS is also a must.
3. Manipulating JSON is more important than XML becoz its much more flexible and lightweight to transfer your data as JSON object.
4. Choose some popular libraries and stick to them. Personally I suggest Prototype (Its a must), jQuery, mooTools and Scriptaculous. I dont like Dojo becoz it seems too heavier to me. (I dont agree with Dino in this issue, I suggest DRY, Dont Repeat Yourself. Why do you have to reinvent the wheel?)
5. AJAX is also a must.
6. Being able to write JS in Object Notation format (he he he, its JSON)
7. keep yourself uptodate by visiting sites which inform you what’s actually going on in this sector.
8. Be aware of browser compatibility issues (Its a must)

And Finally

9. Love JS

Just PHP will give you nothing… unless you upgrade yourself

I have been working with PHP for more than 3yrs (I believe still I am beginner in this category) – I was present in several interview board. Which things disappointed me most is the “lack of eagerness” to learn what comes new. Sometime developers thinks that learning Only PHP will help them to get lucrative jobs!! OMG

Specially in BD most of the time PHP developers plays multiple roles in the companies, they are developer, they are template designers, they are HTML coders, they are DBA, they are PMs….what the heck. Only few companies have different people for these roles.

How far you can go just learning PHP (RAW code, in ancient style, that means PHP+HTML together, yak!!)? You have to have knowledge in CSS, JS, Frameworks, Multiple DBS

When it comes the question of CSS, you should maintain a list of websites where from you can get updates. Dont learn the CSS from book, but goto websites and see what is happening… If you are still using Tables to design (more…)

A brand new day

Yesterday Dhaka was a hot city due to political strike of opposition party. I was in home with new idea and works. I wake up at 9PM and started writing the pending and last chapter of my wordpress book, “developing widgets and plugins”. Ayesha and Afif went to a relatives house so that I was all alone in home and my work ran on full throttle. I completed around 13 pages yesterday.

At night I started my long planned project “Golpo”, the Unicode based bangla group chat solution for netizens. I was working with the DAO and I almost finished it. I was planning for this project for a long time and DB schema was ready, just needed to start the work.

From now on, I will publish my upgrade regularly on this project. I know that I will be stuck with UI part because I am not a good designer.

Lets roll the project – It will be finished soon.

Creating Action Queue for AJAX Calls

In ajax, there are several cases where you need to call a bunch of actions synchronously. That means one action must finish before another one called. You can do it by checking the status of ajax request of previous calls and if that was in finished state, you can call next action. This process may be resource extensive if you dont care for checking. So here is a simple actionChain object which will help to put numbers of actions in a chain (or you better say, queue) and call them one of after one smartly. I just demonstrate how it works

<script>
var actionChain = {
curIndex: 0,
actions: new Array(),
fire: function()
{
if (this.curIndex<this.actions.length)
{
alert(this.actions[this.curIndex]);
this.callback();
}
else
{
alert("finished");
}
},
increase: function()
{
this.curIndex++;
},
addAction: function(actionName)
{
this.actions[this.actions.length] = actionName;
},
initialize: function()
{
this.curIndex=0;
this.actions = new Array();
},
callback: function(){}
}

actionChain.callback=checkVar;

function checkVar()
{
actionChain.increase();
actionChain.fire();
}

for(i=1;i<11;i++)
actionChain.addAction("hello"+i);
actionChain.fire();

actionChain.initialize();
for(i=1;i<4;i++)
actionChain.addAction("hello"+i);
actionChain.fire();
</script>

so here you see, an actionChain object is created and then we add some actions. Then we call the fire() method. This fire() method simply invoke callback function with current action in queue. And the call back function just increases the counter. So when the counter reaches at final offset, it will terminate.

Here I show a basic demo, just modifying it a bit you can create your full fledged ajax action chain object ( i mean a proper object which stores the action, their url, parameters and response callback etc…)

Thanks