Code example: Search Engine, Bookmark & Usability Friendly Ajax
An big problem with loading content in your page with javascript, is that this content can’t be seen by search-engines.
But this problem can be overcome, see this little code example I wrote.
What can this do?
- All pages can be used with Javascript disable
- You can bookmark a page that was loaded with javascript, thanks to RHS
- The back and forward buttons of the browser are still functional
To write this, I used the jQuery javascript framework and the RHS library
You can test the example online. Or download it.
ajaxsite.php
class Page
{
public $link, $title, $content;
public function __construct($link, $title, $content)
{
$this->link = $link;
$this->title = $title;
$this->content = $content;
}
}
class AjaxSite
{
/**
* All pages of the site
*
* @var array
*/
private $pages = array();
/**
* Holds the current page to display
*
* @var Page
*/
private $currentPage;
/**
* The default page
*
* @var string
*/
private $defaultLink;
/**
* Contructor, set example pages
*
* @param $default_link
*/
public function __construct($default_link)
{
$this->defaultLink = $default_link;
//some placeholder text
$lorum = <<<LOR
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Maecenas faucibus malesuada elit. Nulla et ipsum. In sed lacus. Donec eleifend neque. Nullam et tellus et dui tincidunt rhoncus.</p><p> Donec imperdiet ante eget massa. Nunc eu urna sit amet nisl pellentesque faucibus. Pellentesque suscipit porta elit. Praesent ac tellus ut quam pellentesque faucibus.</p>
LOR;
//create a couple of pages
$p1 = new Page(“page1″, “Page 1″,“<h3>This is page 1</h3>” . $lorum);
$p2 = new Page(“page2″, “Page 2″,“<h3>This is page 2</h3>” . $lorum);
$p3 = new Page(“page3″, “Page 3″,“<h3>This is page 3</h3>” . $lorum);
//put the pages in an array, use the page link as key for easier searching
$pages = array
(
$p1->link => $p1,
$p2->link => $p2,
$p3->link => $p3
);
$this->setPages($pages);
}
/**
* Set all Pages
*
* @param array $pages
*/
public function setPages(array $pages)
{
$this->pages = $pages;
}
/**
* Get all Pages
*
* @return array
*/
public function getPages()
{
return $this->pages;
}
/**
* Get the current page to show
*
* @return Page
*/
public function getCurrentPage()
{
//if currentPage is already set, return it
if($this->currentPage != null) return $this->currentPage;
//get page link for page to show
$link = $_GET[“p”];
if($link != null)
{
//if link exists in the array of pages, use it, otherwise use the default
$link = array_key_exists($link,$this->pages)? $link : $this->defaultLink;
//set the current page
$this->currentPage = $this->pages[$link];
}
else
{
//if the link is not set, use the default
$this->currentPage = $this->pages[$this->defaultLink];
}
return $this->currentPage;
}
/**
* Get default link for this page
*
* @return string
*/
public function getDefaultLink()
{
return $this->defaultLink;
}
/**
* Check if this page is not an ajax request
*
* @return bool
*/
public function notAjaxRequest()
{
//default return value
$notAjaxRequest = true;
//get type of request
$request = $_GET[“r”];
//if request type is ajax, only echo partial content
if($request != null && $request == “ajax”)
{
echo “<h2>” . $this->getCurrentPage()->title . “</h2>”;
echo $this->getCurrentPage()->content;
$notAjaxRequest = false;
}
return $notAjaxRequest;
}
}
index.php
require_once “ajaxsite.php”;
// create new site
$app = new AjaxSite(‘page1′);
//only show full page when this page is not an ajax request
if($app->
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns=“http://www.w3.org/1999/xhtml”>
<head>
<meta http-equiv=“Content-Type” content=“text/html; charset=iso-8859-1″ />
<title>Search Engine & Usability friendly Ajax</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="json2007.js"></script>
<script type="text/javascript" src="rsh.js"></script>
<script type="text/javascript">
<!–
//set default page, used in main.js
var defaultpage="<?php echo $app->getDefaultLink() ?>";
//–>
</script>
<script type=“text/javascript” src=“main.js”></script>
</head>
<body>
<div id=“container”>
<div>
<h1>Search Engine & Usability Friendly Ajax</h1>
<div style=“height:10px;”>
<img id=“loader” src=“ajax-loader.gif” alt=“Loading…” style=“display:none;” /></div>
</div>
<div id=“nav”>
<ul>
<?php foreach($app->getPages() as $link=>$page): ?>
<li>
<a id=“_<?php echo $link ?>" href="<?php echo ‘index.php?p=’ . $link ?>"><?php echo $page->title ?></a>
</li>
<?php endforeach; ?>
</ul>
</div>
<div id=”content“>
<?php echo $app->getCurrentPage()->content ?>
</div>
</div>
</body>
</html>
<?php endif; //And that’s it
main.js
//create dhtmlHistory, so we can store the browser history for this site
window.dhtmlHistory.create();
//event when browser history buttons are clicked
var yourListener = function(newLocation, historyData)
{
//newLocation contains the current page location (for example "page1")
//historyData contains the html for the current page that I saved with dhtmlHistory.add(loc,content)
$(“#content”).html(historyData);
}
//executed when DOM is ready
$(document).ready(function()
{
//initialize dhtml history and set the event for all history changes
dhtmlHistory.initialize();
dhtmlHistory.addListener(yourListener);
//set location of current page in global var, so it can be used in all events
loc = “” + window.location;
var lastIndex = loc.lastIndexOf(“#”);
loc = (lastIndex != -1)?(loc.substring(lastIndex + 1)):defaultpage;
//load the content for the first page based on the current location
//for example "page3", this makes bookmarking an "ajax" page possible
$(“#content”).load(“index.php?p=” + loc + “&r=ajax”, null, function()
{
var content = $(“#content”).html();
dhtmlHistory.add(loc,content);
});
//Everytime and ajax request starts, we show the loading animation and hide the old content
$(“#content”).ajaxStart(function()
{
$(“#loader”).show();
$(this).hide();
});
//Everytime and ajax request is succesfull, we hide the loading animation again
//and show the new content with a fade in animation
$(“#content”).ajaxSuccess(function(evt, request, settings)
{
$(“#loader”).hide();
$(this).fadeIn();
});
//we set a click event for all link in the navigation
$(“#nav li a”).click(function()
{
//I saved the page link in the id of the hyperlink
//though I could also just parse the src and get it from there
loc = $(this).attr(“id”).substring(1);
//load the new content in the content div
$(“#content”).load($(this).attr(“href”) + “&r=ajax”,null, function()
{
//everytime we load new content with ajax
//we put it in the dhtmlHistory object, so we can recover it later
dhtmlHistory.add(loc,$(this).html());
});
//return false when the hyperlink is clicked, to disable
//the default behavior of the hyperlink
return false;
});
});
January 26th, 2008 at 17:03 #senn
geene zever, maar das pro!
merci ward
February 3rd, 2008 at 15:13 #Dejan
Great Example. Thank you very much.
Is it possible to load external pages. Such example would be excellent and very useful, I am sure of it.
Cheers
May 22nd, 2008 at 17:55 #Rob
This script is exactly what I’ve been looking for. Unfortunately, I’ve downloaded it, uploaded to my webserver and I get an error in index.php - see http://ecowebhosting.co.uk/newsite/friendlyajax/index.php. I haven’t changed the code at all - just uploaded it. Is there anything I need to do to the code to make it work?
Thanks!
Rob
March 3rd, 2009 at 12:34 #Alexwebmaster
Hello webmaster
I would like to share with you a link to your site
write me here preonrelt@mail.ru
March 8th, 2009 at 1:43 #BitTooppY
продам Форд-Фокус 2008 года за 200 тр. торг возможет. срочно!!!
+7 960 200 9209
July 31st, 2009 at 14:17 #Установка CMS
Выполняю установку и настройку различных CMS систем.
Предоплата 50% стоимость работы от 400р.
Оплата Web Main или Яndex деньги.
Информация для связи ISQ 429606266 Александр.
September 10th, 2009 at 15:17 #sandrar
Hi! I was surfing and found your blog post… nice! I love your blog.
Cheers! Sandra. R.
September 10th, 2009 at 17:19 #angelina jolie
I love your site.
Love design!!! I just came across your blog and wanted to say that I
September 11th, 2009 at 16:47 #megan fox
Sign: umsun Hello!!! rcuwwymhyw and 2401ssgfhphzye and 8342Sorry, what did you mean?? A??
October 25th, 2009 at 19:40 #pictures of miley cyrus
Sign: rmpvp Hello!!! crksk and 7160tcpayfvygg and 2953 : I like your blog. cool post!
October 29th, 2009 at 20:49 #kino-klad
свежие кинофильмы смотреть в хорошем качестве
August 24th, 2010 at 19:26 #celebrity fuck you
Sign: zdbrw Hello!!! ssaxx and 6709nsnmgrmmpf and 2471 : I love your blog.
I just came across your blog.
October 12th, 2010 at 13:35 #LuisachkaIV
Просматривая эротика манга парень татарином изнасилование жесть лесби расказы бесплатно скачать порно кино скачать порно видео трансов marie порно free porn anal где можно скачать порно хентай мультики porno студент анальный секс боль фото может ли анальный секс привестив геморрою анальный секс как не получить травму анальный секс мужчинам shemale heaven русское любительское порно онлайн смотреть жесткое порно фото german porn фотки эмо парней секс порно офис изнасилование зрелых порно 3gp порнуха скачать бесплатно секс бузова госпожа бдсм страпон форумы про анальный секс dvd фильмы анальный секс Вот такие вот дела
December 1st, 2010 at 11:41 #徵信公司
I think AJAX is at its best for two main types of tasks ,Fetching data that needs to be regularly refreshed, without the need for manual reloads or meta refreshing and Submitting forms which don’t need to send you to a 4 new URL
December 7th, 2010 at 9:06 #Darrel Pendola
RGB to CMYK mode may make drawings. I do not want to get a print error. Can you help
December 29th, 2010 at 12:28 #Заборы из профнастила купить
Хорошо! Все бы так писали
January 8th, 2011 at 8:52 #Stanford Haddix
Nice article. I love the work you put into your site.
May 7th, 2011 at 23:17 #frenky
N8j0Us http://gdjI3b7VaWpU1m0dGpvjRrcu9Fk.com
June 9th, 2011 at 5:06 #Berry Rieland
Play push game and get your little man to the gold coin by pushing other obstacles out of his way by creating bubbles with your mouse, try not to squish your man against the other pushed obstacles.
July 15th, 2011 at 10:24 #draft
Be watchful when consuming way too much beer because it may end up in alcohol addiction. Ofcourse if you are an enjoyer of life just like i am then you may not care!
July 17th, 2011 at 8:36 #Rocco Maurizio
On occasion individuals are layered that adheres to that. There’s a thing totally different beneath than what’s on top. Nonetheless sometimes, there’s one third, even deeper level, and the one is similar to the highest surface one.
July 19th, 2011 at 0:24 #Pozycjonowanie
An impressive share, I simply given this onto a colleague who was doing a bit analysis on this. And he in truth purchased me breakfast as a result of I discovered it for him.. smile. So let me reword that: Thnx for the treat! However yeah Thnkx for spending the time to discuss this, I feel strongly about it and love studying more on this topic. If attainable, as you turn out to be expertise, would you mind updating your weblog with extra particulars? It is extremely helpful for me. Big thumb up for this weblog submit!
July 20th, 2011 at 13:39 #du hoc nhat ban
I like this article. I search it from yahoo. Can I copy to my site? . thanks
July 28th, 2011 at 6:23 #cpa nyc
An interesting blog is worth a good remark. You made it so clear and easy to understand. Great creation. Waiting to see more stuff from you to post here. Thank you so much.
July 30th, 2011 at 23:26 #Dexter Megavideo
There are some fascinating points in time on this article however I don’t know if I see all of them heart to heart. There is some validity however I will take hold opinion till I look into it further. Good article , thanks and we wish more! Added to FeedBurner as effectively
August 4th, 2011 at 3:46 #nyc oak
very good! you have given a good example,its helpful!
August 8th, 2011 at 15:10 #http://www.care2.com/c2c/people/profile.html?pid=283694939
where to find immigration advice…
[...]while the sites we link to below are completely unrelated to ours, we think they are worth a read, so have a look[...]…
August 17th, 2011 at 8:29 #daily deals mumbai
Wonderful work! This is the type of info that are supposed to be shared across the internet. Shame on the seek for not positioning this post higher! Come on over and talk over with my site . Thank you =)
September 5th, 2011 at 7:26 #Rptrczog
Could I have , please? 12yo preteen girls 604
September 7th, 2011 at 16:47 #Jfujhyjn
this is be cool
underage toplist
378096
September 23rd, 2011 at 0:04 #Wwythnnb
I read a lot Nude Loli 4067
December 14th, 2011 at 11:23 #Okifivxx
I like watching TV Pthc Hussyfan Lolita
451126
December 15th, 2011 at 7:30 #Vrozsyvl
Get a job Lolita Bbs Pics
2155
December 15th, 2011 at 7:48 #Puxtfouq
very best job Preteen Model
5282
December 15th, 2011 at 10:45 #Gzoutceu
The line’s engaged Lolita Hardcore
xnvqty
December 15th, 2011 at 10:46 #Wkvdtswv
I love this site Nn Models Preteen
fgqvaa
December 15th, 2011 at 19:00 #Dpexlkuu
The United States Lolita Top Bbs
kgfue
December 16th, 2011 at 0:05 #Krissy Mumaugh
Hey there I am so thrilled I found your blog, I really found you by accident, while I was searching on Aol for something else, Anyhow I am here now and would just like to say kudos for a fantastic post and a all round interesting blog (I also love the theme/design), I don’t have time to read through it all at the minute but I have book-marked it and also added your RSS feeds, so when I have time I will be back to read more, Please do keep up the superb job.
December 17th, 2011 at 15:38 #Lance Lebahn
Energy Force Bands are superior to all power bands on the market! Use code EF50 for 50% discount!
January 3rd, 2012 at 19:09 #NickWallII
[url=http://tvsector.com/] check freed Shows online [/url]
January 3rd, 2012 at 19:09 #Kcxwhyfn
I’m sorry, I’m not interested teen bikinis porn 1969
April 26th, 2012 at 6:56 #oborudmysklaР
Hack again?!
May 2nd, 2012 at 5:32 #Scgzqupq
This site is crazy
http://caqylarygop.blog.free.fr/ nympho bbs I’m so wet for real. i need one more Sasha just to be mine lol. she can fuck real nice and hard.
May 2nd, 2012 at 20:57 #Fruhyjuk
What line of work are you in? http://ibibyhasiat.de.tl japan models nudes Double anal is always impressive to me. I didn’t know this girl did one too. But I’m glad she did!
May 2nd, 2012 at 23:48 #Eyjrihsx
I’ve got a full-time job http://oujoiyd.de.tl alexa young model That’s totally how a filipina really grinds, no doubt. Looks just like the real thing, in my view. Everyday thing, lol.
May 3rd, 2012 at 2:07 #Cbrurqrf
Sorry, I ran out of credit http://igihipusu.de.tl kds porn bbs vombat Great! Some of the best pussy licking on the net. Very, very sexy. It was great to see a girl gettting her pussy rubbed from another woman with her panties just slighly pulled down. I really love that look.
May 4th, 2012 at 3:27 #Mihssjqq
I’m a trainee http://ysycaceleb.de.tl ethanol model structure Would life be different if you had another job? Not for Cytherea, seems like she’d be constantly having hot sex even if she were a policewoman!
May 4th, 2012 at 11:51 #Cezbuyop
A jiffy bag http://edeboteler.de.tl sex nymphet video i have sexy land{dick} for u,,who want to fuck,,come on,,,,,i am fucking now my wife friend and watching,,,,,next one may be u,,,,,
May 4th, 2012 at 17:41 #Etcrsabx
I went to http://cumosapibok.de.tl nymphettes porn gallery That’s the kind of guy that inevitably winds up unconscious on the floor after someone gets tired of his yapping.
May 4th, 2012 at 20:27 #Sfmccoji
What’s the current interest rate for personal loans? http://safadogahyced.de.tl nymphets teens 13 years Great to see this video. I fucked a milf last week that looked just like her. The milf had bigger natural tits though and was amazingly tighter. She was the best woman I ever had.
May 8th, 2012 at 1:15 #Vmhzxsof
The United States http://yenomupaj.de.tl loli petite model binaries agreed, the way she moans is very hot and she has a sexy body, i’d like to see her in more positions.