Howto: AJAX for Blogger peek-a-boo content @ tk here on Sunday, February 05, 2006 5:33 PM
Google
You could also try tk Social Bookmarking Search or tk Video Search!

Sunday, February 05, 2006

Howto: AJAX for Blogger peek-a-boo content

Introduction: As part of my recent design changes earlier, I added AJAX functionality to this blog. More on this here. This is a howto on replicating this on your own blog @ Blogger. I'm assuming you have some knowledge of html, blogger template code and javascript. You may want to read up on AHAH here. I've split up the code into 3 parts.

Ok, I'm starting off with the last part of my code first, since it is easier to explain how everything works that way. First look at the template code below. Hopefully you understand what's happening here because it's basic html and blogger template codes.


<MainOrArchivePage>

<small onclick="javascript:toggler('<$BlogItemPermalinkUrl$>', this, '<$BlogItemNumber$>post')" style="cursor:hand;">Click to view</small>

</MainOrArchivePage>

<div class="post-body" <MainOrArchivePage>id="<$BlogItemNumber$>post" style="display:none;"</MainOrArchivePage>>

<ItemPage><$BlogItemBody$></ItemPage></div>


So everything starts when a user clicks on "Click to view". As you can see it calls the toggler function and from there, somehow the div class="post-body", which is the entire post appears. (The way it works for comments and backlinks are similar so I don't think an explanation is required.)

The below you see is the last part of my code, which is the toggler function. Notice that it accepts 3 variables - serverPage, linkobj and objID. Where do these variables come from? Look at "Click to view" again. Do you see '<$BlogItemPermalinkUrl$>', this, '<$BlogItemNumber$>post'? Yup those 3 are the 3 variables. The first variable, serverPage, contains '<$BlogItemPermalinkUrl$>', the post permalink url, also where you are gonna parse content from. The 2nd variable, linkobj, holds the link object itself. This is so that you can change "Click to view" to "Click to hide". The 3rd variable, objID, contains the post id, so that the script knows which post to show or hide.

Now you know how what these variables are. Let me briefly explain what the code is doing. First, it gets the element that is stored in objID and stores it in obj for later use. If objID (the post) is already shown, hide it. Then depending on whether objID contains post, blinks(backlinks) or comments, different actions will be taken. For comments, if there is no comment, the comment page will popup instead of trying to display 0 comments.

The next part does exactly the opposite. If objID is hidden, show it. The important part here is ahah(serverPage, obj, objID); that you see appearing 3 times, each for post, comments and blinks(backlinks). That is the AJAX function that requests the page from the server, which you will see later. It sends the 3 variables for processing.



function toggler(serverPage, linkobj, objID) {
var obj = getElement(objID);
if (isShown(objID)) {
obj.style.display = "none";
obj.innerHTML = "";
if (objID.indexOf("post") != -1) { linkobj.innerHTML = "Click to view"; }
else if (objID.indexOf("blinks") != -1) { linkobj.innerHTML = "Show Backlinks"; }
else if (objID.indexOf("comments") != -1) {
if (linkobj.innerHTML == "0 comments") {
window.open("http://www.blogger.com/comment.g?blogID=19630625&postID=" + objID.substring(0, objID.indexOf("comments")));
}
}
}
else {
if (objID.indexOf("post") != -1) {
obj.style.display = "block";
linkobj.innerHTML = "Click to hide";
ahah(serverPage, obj, objID);
}
else if (objID.indexOf("blinks") != -1) {
obj.style.display = "block";
linkobj.innerHTML = "Hide Backlinks";
ahah(serverPage, obj, objID);
}
else if (objID.indexOf("comments") != -1) {
if (linkobj.innerHTML == "0 comments") {
window.open("http://www.blogger.com/comment.g?blogID=19630625&postID=" + objID.substring(0, objID.indexOf("comments")));
}
else {
obj.style.display = "block";
ahah(serverPage, obj, objID);
}
}
}
}

function getElement(id) { return document.getElementById(id); }

function isShown(id) { return getElement(id).style.display != "none"; }

//-->
</script>
</MainOrArchivePage>


The code you see below is the main part of AJAX, which happens to be the first part of my code. It is where the magic gets done. Basically, when a user does something, the browser will request for some info from the server and update only the necessary elements. You'll see that it accepts 3 variables and these 3 variables came from the part above. What can be safely changed here is obj.innerHTML = 'Hang on...';. This is just a message telling the user to wait for changes. Next, notice this part ahahDone(obj, objID);. It sends 2 variables to the ahahDone function for processing.

The ahahDone function is just checking to see if everything is ok. If it is, well we're happy and it can send a variable to either getPost, getComments or getBlinks function, depending on what objID contains. These functions strip out the parts we want and throw the rest away. What you can change here is { obj.innerHTML="Status:\n" + xmlhttp.statusText; }. This is sort of like an error message informing the user when AJAX fails (here I left it as the status message returned instead).

<MainOrArchivePage>
<script type="text/javascript">
<!--
function ahah(serverPage, obj, objID) {
obj.innerHTML = 'Hang on...';
if (window.XMLHttpRequest) { xmlhttp = new XMLHttpRequest(); }
else if (window.ActiveXObject) { xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); }
if (xmlhttp) {
xmlhttp.onreadystatechange = function() { ahahDone(obj, objID); };
xmlhttp.open("GET", serverPage, true);
if (window.XMLHttpRequest) { xmlhttp.send(null); }
else if (window.ActiveXObject) { xmlhttp.send(); }
}
}

function ahahDone(obj, objID) {
if (xmlhttp.readyState == 4) {
if (xmlhttp.status == 200 req.status == 304) {
if (objID.indexOf("post") != -1) { getPost(obj); }
else if (objID.indexOf("blinks") != -1) { getBlinks(obj); }
else if (objID.indexOf("comments") != -1) { getComments(obj); }
}
else { obj.innerHTML="Status:\n" + xmlhttp.statusText; }
}
}



The code below is the 2nd part of my code. It appears last as it is the easiest to explain. Each function accepts a variable sent from ahahDone. This variable happens to contain a reference to the element where you want the content to appear. Next, resText = xmlhttp.responseText;, where resText contains the entire page retrieved from the server. Obviously, you only want to insert certain parts of the page inside, so you'll need to search for the things you want. The rest of the lines just do some careful searching (all those indexOf lines) and the very last line of each function does a substring to cut out the relevant parts out and stick it into the html of the post element (obj).



function getPost(obj) {
resText = xmlhttp.responseText;
start = resText.indexOf("<!-- Begin .post -->");
start1 = resText.indexOf('<h3 class="post-title">', start);
start2 = resText.indexOf('</h3>', start1) + 5;
end = resText.indexOf('<p class="post-footer">', start2);
obj.innerHTML = resText.substring(start2, end);
}

function getBlinks(obj) {
resText = xmlhttp.responseText;
start = resText.indexOf("<!-- Begin #comments -->");
start1 = resText.indexOf('<a name="links">', start);
end = resText.indexOf('<p class="comment-timestamp">', start1);
obj.innerHTML = resText.substring(start1, end);
}

function getComments(obj) {
resText = xmlhttp.responseText;
start = resText.indexOf("<!-- Begin #comments -->");
end = resText.indexOf('<a name="links">', start);
obj.innerHTML = resText.substring(start, end);
}


And that sums it up. With some luck, you should be able to do the same. Comments on this are welcome.

Edit: I added a line of code in the toggler function to fix a bug. That line is (obj.innerHTML = "";).

 

31 people had something to say! Why don't you join in? The more the merrier!

On 06 February, 2006 03:00, Craffter said...

Hey TK, that is a swell code. I will get back to you when i add this code a test blog. i will try to do some other things with it too. thanks and see you soon.

On 25 March, 2006 20:56, Craffter said...

i am actually messing with your code right about now, but i wanted to know if you could email me you template to no exaclty where each part of the code must go. i tried it on one go but i didn´t worked,so i must had messed somewhere.

TheCraffter@gmail.com

On 25 March, 2006 21:07, tk said...

craffter: ok i've sent the template code to your email :)

On 25 March, 2006 21:12, Craffter said...

got it, thanks TK.

On 27 March, 2006 02:35, andycjw said...

hi tk, hope you see this,
i just realize the show backlinks doesn't work behind with the AHAH loading since it doesn't execute javascript after extracting the content, for example, in this post, there's a backlink from my blog to you, it showed up perfectly in the individual post page, but not in the archive page when click on the 'show backlinks', i'll try to fix it with the eval() javascript, see if it works that way. thanks again for your amazing work.

On 28 March, 2006 03:54, tk said...

hi andy, i think u may have made a mistake. keep me posted if u find more bugs. :)

On 28 March, 2006 05:43, andycjw said...

but it doesn't work as you can see in both screenshot i made in FF and IE

backlinks in FF
backlinks in IE

btw, can you see the backlinks from my blog to you? even with the peek-a-book thing?

On 28 March, 2006 19:03, tk said...

andy: the reason u don't see any backlinks is because there aren't any backlinks listed. :) if u load the individual post page, which doesn't utilize any ajax, u will see that there are no backlinks listed. i'm not sure how long it takes a backlink to appear, or if blogspot pinging has some problems. however, if the individual post page shows backlinks and the main/archive pages don't, then that is a bug.

On 28 March, 2006 23:52, andycjw said...

seriously, i'm not that dumb enough to oversee that i don't see any backlinks because there aren't any listed, LOL.
the individual post page sure have backlinks, i saw it, see it yourself here, but i'm not sure why it didn't show up at your browser. but even so, if you open up and view the source you'll see and realize the backlinks are initiated by javascript onload, meaning it only go and find backlinks when the whole page finish loading, with javascript nonetheless, that is why with ajax loading individual post page from main page will not show any backlinks, even if there is backlinks listed, because it need javascript to write it in. if you're still in doubt, this is the javascript used by blogger http://www.blogger.com/js/backlink.js , you can see it processes tag like <$BlogBacklinkURL&> and etc in the blog template, these backlinks template tag are not pre-processed like others, they remain as it is, and is processed only when the page is loaded by visitors, which is very reasonable if you think about it, these backlinks cannot be pre-processed, since it may be posted and published long time ago, and many may have linked to it after it was published.

btw, this is the what loaded the data,
http://www.blogger.com/dyn-js/backlink.js?blogID=19630625&postID=113913323142279440 ,
it should show up like below if the backlinks search can find my blog linking to you, or else, it'll be blank.

var backlink;
backlink = new Array();
backlink["BlogBacklinkURL"] = "http://andycjw.blogspot.com/2006/03/site-redesign.html"; backlink["BlogBacklinkTitle"] = "Site Redesign";
backlink["BlogBacklinkSnippet"] = "This blog has undergone some serious revamping and improvement sprinkled with AJAX magic. The whole design may still look the same, that is because it hasn't changed much from the original template that I choosed from the available list ... ";
backlink["BlogBacklinkAuthor"] = "andycjw";
backlink["BlogBacklinkDateTime"] = "25 March, 2006 12:27";
BL_Backlinks[0] = backlink;


having this said, i still cannot figure out how to make this work with ajax, even with the eval() function, it doesn't work as i think it should be. hope you can shed some light on this. thank you.

On 29 March, 2006 15:27, tk said...

hi andy, u're right, backlinks do not show with ajax. it seems that backlinks don't display in opera either, that's why i thought there weren't any backlinks. currently i have not thought of how to make the backlinks appear, if i find a solution, i'll post it here. :)

On 05 April, 2006 23:29, andycjw said...

hi tk, hope you see this again, i've devised a way to execute javascript after ajax load, but too bad that backlinks still doesn't show up for some reason, i'm thinking of directly executing the js library provided by blogger to do the backlinks instead of using the defaults by blogger. anyway, did you found anyway to do this already? drop me a mail at andycjw@gmail.com, or just add me to msn instant messenger (if you use one, that is), i'm andycjw@hotmail.com thanks!

On 02 June, 2006 16:44, Steve said...

test comment! I wanna see this in action :)

On 29 June, 2006 15:01, Rakesh said...

another test comment

On 07 July, 2006 15:29, Estupidormitorian Neil said...

Test

On 04 October, 2006 11:33, Anonymous said...

test

On 17 November, 2006 05:56, Anonymous said...

test

On 17 November, 2006 05:58, Salman Siddiqui said...

can u pls mail me the tempelate code so that i can see where to implement the AJAX code???

am a little confused...

salmansiddiqui1234@rediffmail.com

On 21 January, 2007 16:19, Anonymous said...

Just testing around

On 18 March, 2007 21:17, Anonymous said...
This comment has been removed by a blog administrator.
On 21 March, 2007 13:51, Anonymous said...
This comment has been removed by a blog administrator.
On 21 March, 2007 13:54, Mike said...

I added your peek-a-boo ajax comment display to my blog at http://mike.creuzer.com and it works pretty well.
Thanks for your hard work and for sharing!

On 31 March, 2007 20:56, Anonymous said...

can u pls mail me the tempelate code so that i can see where to implement the AJAX code???

am a little confused...

techsatish@gmail.com

On 09 May, 2008 04:20, Raman said...

BEST WAY TO LEGALLLY OWN A RAPIDSHARE 1 year PREMIUM ACCOUNT.


Follow these steps:
1. Create a paypal PREMIUM Account at this address. It is free;

http://www.paypal.com

When asked for credit card details simply say cancel. You do not need to fill it.

2.Then go to the following link;
http://www.AWSurveys.com/HomeMain.cfm?RefID=suraj1986
Join this site. It is also free. You get paid for completing surveys over there 6$ to 4$ dollars per survey and 1.25$ per referral thats a lot u will get a
premium account of 1 year in weeks time ......i myself have a 1 year premium account and now i am collecting some exta cash .

4.. Another thing you can also use paypal money to buy stuff on ebay and other shopping sites.

5. Thats is it. So Simple and I swear it works.

On 28 September, 2008 14:31, Joe said...

Hello Tk,

Can you also send me the code.

this.true@gmail.com

Thanks.

On 04 October, 2008 06:08, Software Wikipedia said...

Hi, Would you be interested to exchange link with my blog at http://software-wikipedia.blogspot.com.
mail me at software.wikipedia@gmail.com if you are interested.

On 22 January, 2013 02:29, Anonymous said...

Специально для Вас друзья мы возвращаем наш отличный проект на котором можно скачать все с файлобменников бесплатно [url=http://kachaitut.ru/]Кино[/url] . Все для Вас друзья.
Уважаемые Админы приглашаем Вас обменяться ссылками.

С Уважением, Администрация КачайТУТ.

On 27 February, 2013 14:18, Anonymous said...

Всем привет если Вам нужно разнообразить свой фотошоп, найти что то новое и изумительное, Вам сюда [url=http://psdgif.ru/]Обои[/url]

On 13 March, 2013 21:33, Anonymous said...

Салон Секреты Красоты предлагает большой выбор классических салонных услуг: парикмахерские услуги, маникюр, педикюр, косметология, перманентный макияж. Мы работаем более 10 лет и придерживаемся принципа соотношения цены и качества обслуживания. Для постоянных клиентов действуют акции и бонусная система. Заходите на наш сайт [url=http://s-krasoti.ru/] салон красоты to be queen
[/url]

On 18 March, 2013 18:12, Anonymous said...

Хотите Скачать филмы быстро и бесплатно, Вам сюда [url=http://expresskino.ru/]Новые фильмы[/url]

On 07 April, 2013 03:03, Anonymous said...

Производственная компания «М-СЕТ» специализируется на производстве сварных сеток в рулонах, имеющих широкое применение в различных строительных работах.
Производство сварной сетки выполняется на многоточечных сварных машинах, методом контактно-точечной сварки крестообразных соединений. Все пересечения и стыки прутьев тщательно сварены, благодаря чему конструкция отличается превосходным качеством и является одной из самых прочных.
На нашем сайте Вы можете посмотреть образцы нашей продукции и связаться с нами
[url=http://setka-vlg.ru/]производство сетки сварной балки
[/url]

On 07 April, 2013 05:45, Anonymous said...

Производственная компания «М-СЕТ» специализируется на производстве сварных сеток в рулонах, имеющих широкое применение в различных строительных работах.
Производство сварной сетки выполняется на многоточечных сварных машинах, методом контактно-точечной сварки крестообразных соединений. Все пересечения и стыки прутьев тщательно сварены, благодаря чему конструкция отличается превосходным качеством и является одной из самых прочных.
На нашем сайте Вы можете посмотреть образцы нашей продукции и связаться с нами
[url=http://setka-vlg.ru/]производство сварной сетки fensys
[/url]

Google
You could also try tk Social Bookmarking Search or tk Video Search!