I’m going to assume that we all know, or have atleast heard of Prototype and script.aculo.us the two combine to form one powerful javascript library enabling developers to become designers (well, kind of).
– Example and code at the bottom –
I have created a ZIP file to get you up and running right away: Download it now!
I was showing a friend a few days ago something i made for a university module, Multimedia Applications Desgn (a mouthful i know). Basically we had to create a website promoting our group as a duo, thats all your getting about the project as its not really relevant and a tad embarrassing should anyone find the site!
There was a part of the site that my friend really liked and wanted to incorporate into his final year project… after sketching it out for him on paper i reconed that other people could benefit.
This has probably been splashed everywhere, but i havent seen anything that incorporates all the same characteristics on Digg.
So here is a quick, hopefully easy to understand, tutorial of how its done.
Abstract
We are trying to achieve loading content into a ‘div’ element without refreshing the page, as well as showing a cool loading window inplace of the content as it is loading.
Method
1 HTML page and 1 PHP page are required.
You dont need to follow my method exactly as there are probably many many more out there, this is just my simple approach that seems to work.
The HTML Page
This page will be the one we want the user to stay on with the ‘div’ element in it for loading the content into.
Firstly we need to include the script.aculo.us javascript files.
I just unzipped the script.aculo.us javascript files into my own folder called ‘js’.
Next we need to create a few functions to make our life easier.
The reason for this is it makes them reuseable and therfore we dont need to make our code look messy, im a little anal about code being correctly formatted and using the same chunks of code over and over again when they could simply be made into functions.
function finishLoading() {
// First we want to show the content are, then toggle the loading window so it fades away.
Element.show(‘mainAreaInternel’);
// This happens 1 second after the mainAreaInternal is shown incase the content is still loading.
setTimeout("Effect.toggle(’mainAreaLoading’);", 1000);
}
function loadContent(id) {
// We make use of the Ajax.Updater function to load the external data from our file.
// Start the loading window first by calling the function we made previously.
startLoading();
// Request the content and update the ‘div’ area (i’ll explain this in more detail later).
new Ajax.Updater(‘mainAreaInternal’, ‘rpc.php’, {method: ‘post’, postBody:‘content=’+ id +”});
// Now finish the loading.
finishLoading();
}
Next we have to make our ‘RPC file’ (probably the wrong phrase to use, but it works for me).
Whatever you ‘echo’ out to from this script will be what appears on the screen, html tags et-all, although i have found that outputting certain types of Javascript, like entire functions does not seem to work.
// The content to show is determined by the $content integer we send through from the javascript.
switch($content) {
case 1:
echo ‘This is the content for the FIRST case statement!’;
break;
case 2:
echo ‘Congratulations, you have loaded the second bit of content!’;
break;
default:
// This default case catches any $content value that does not have a case. I’m giving a nice error message so you can work out what went wrong.
echo ‘Whoops, there was a problem in the switch.You passed: <em>’. $content .‘</em> to the switch statement in rpc.php.’;
} // end Content Switch.
?>
Here is the CSS Stylesheet to make all this possible
overflow: auto;
z-index: 0;
}
.mainAreaLoading {
position: absolute;
top: 40px;
left: 0px;
width: 500px;
height: 300px;
z-index: 1;
}
Ok, now that the backend is all there, we need to do the difficult part (probably the easy bit for everyone else!), making the HTML page.
<span style="cursor: pointer" onclick="loadContent(1);">Load Content 1</span>
<span style="cursor: pointer" onclick="loadContent(2);">Load Content 2</span>
<!– Navigation End –>
<p id="mainArea"> </p>
<p id="mainAreaInternal" class="mainAreaInternal">
This is the content that will be visible at the very beginning.
<!– End Main Area Internal –>
<p id="mainAreaLoading" class="mainAreaLoading" style="display: none">
<span style="position: relative; top: 100px; left: 100px">
Loading Please Wait…
</span>
<!– End Main Area –>
Now for the little explaination
Basically the loading ‘div’ area is always there, it is just hidden from view, so when you call the ’startLoading()’ function it shows it, then hides it after the allotted time.
Adding new ‘cases’ to the rpc.php file will allow more content to be loaded
Example and Code
Content Loading Example
RPC.php Source Code
Get the Full Code in a ZIP Here.
– If you are using this script, i would greatly appreciate it if you referenced http://nodstrum.com in your sourcecode
–
91 Responses for "AJAX/PHP - the beginners guide to loading external content"
To make the code more re-usable would you not be best to pass the url and the div as variables to the loadContent function like so?
function loadContent(id,div,url) {
startLoading();
new Ajax.Updater(div, url, {method: ‘post’, postBody:‘content=’+ id +â€});
finishLoading();
}
Great stuff though. Keep it up. I’m just starting to use prototype and scriptaculous myself. Slow progress to be sure but that’s only due to lack of fantastic articles like this which don’t expect you to be up to date on the inside workings of prototype and scriptaculous.
Nice tutorial, thanks.
Prototype and scriptaculous are great, but a bit heavyweight for a task like this? The following tutorial:
http://www.crackajax.net/tabs.php
and some others on the site show how to do this without installing big libraries.
Graham,
Yes doing it that way would make it alot more reuseable.
I will post up the SQL version of this, you can probably work it out already, but best to just let people see how the code works.
Phil,
The two libraries i am using are very heavy-weight, i make use of alot of their other features, and therfore see it as the best to use as a ’spring-board’ to the rest of the libraries.
I’m interested in looking at the ‘Moo’ library as it seems to have even more functions.
Cheers for the comments.
Jamie.
thanks so much, will be using this on http://www.greenlush.com very soon, bookmarked your site. thanks alot
Its very usefull tutorial,
You can add this script http://www.bestajaxscripts.com/m-submit.html
Thank you for your comments
I was trying to use this for my new site redesign and when I tested it on a page the tabs never switched over. Can you tell me what I did wrong. A downloaded the proptype and scripta files. I copied the source from your demo page, I added a little content and html. And I copied the rpc.php code. What am I missing? Here’s the page http://www.section8hudhomes.com/ajax_test.htm
Thanks.
Hi BJ,
it says forbidden area, i cant see the page.
Can you email me the code to:
jamie [at] blue44.com
Jamie.
kirtyuo
Good Ajax/PHP example. THKS.
I am getting a “You don’t have permission to access /rpc.php on this server.” Does anybody have any idea why?
Hi Mike..
Try chmodding the rpc.php file to 777.
Thats the only thing i can think of…
Oh, also if there is a forward slash infront of of a file eg: ‘/rpc.php’ it thinks that the file is in the root directory, try removing that aswell.
Let me know what happens
Jamie.
hi I’d need to load three different divs I tried inserting into the “This is the content that will be visible at the very beginning.”
part but it won’t switch the div out when flippin to a next one (background remains)..
Is there a way (ofcourse) but something simple I could do which would make it possible? thanks
I was wondering if you need to have an a linux server to use AJAX+PHP…When I try it on my server, it doesn’t do anything…Doesn’t even give me the message:|
Hi Tom,
Yes PHP needs to be installed…
Ajax is not a program, it is just javascript, with a jazzed up name, therefore no program needs to be installed….
Of course you need Apache (web-server, *nix) or IIS (web-server windows).
If you dont have these, i would recommend http://www.easyphp.org, it is an Apache webserver, MySQL serve, PHP engine and is ready to go after installation on a windows box
Hope it works for you
Jamie
wow
Hi, this is great.
I was wondering if there’s any possible way of using jquery libraries instead, and if there is, is anyone up for the task. (I would give it a try myself but i’m just a designer and not to good with code).
Once again GREAT WORK!!
Sérgio
Sergio,
I always thought jQuery was Java (pure) it looks nice and lightweight and is probably alot more suited to this script!
I will give it a go later this-morning and keep you posted.
Jamie
Hi Jamie,
Thats great to hear, just hope u can do it. I’ll be rooting for you
Good Luck!!
Sérgio
[…] In response to Sérgio of estudio5.orgthis morning, i have created a jQuery script that does the same as the Prototype script i created a few weeks ago Ajax Content Load […]
There we go!
jQuery style script!
http://nodstrum.com/2007/03/20/jquery-content-loading/
Jamie.
I was wondering if you know a way to have an external file be linked in html, i have a news website and would like to have the make the least amount of work to update it and am looking for somthing like just opening one file making all the news changes and having all my html files change if you can help me with this email me at duskbmegaman@gmail.com thanks.
Hello
Great script. Love it. Do have a little problem though.
I implemented it, and made some extra content and just named them case 4,5,6 etc. in the rpc.php
But when i came to use case 10 and onwards it gives my an error:
Whoops, there was a problem in the switch. You passed: 10 to the switch statement in rpc.php.
The page is showing, but the error message is at the bottom.
Any know how to fix this? Please email me at: ca@printline.dk
I Already emailed Carsten the fix, so here it is for everyone else.
switch($content){
case ‘1′:
echo ‘This is case 1′:
break;
case ‘10′:
echo ‘this is case 10′;
break;
}
All i have done is to add apostrophies around the case numbers…
Worked for him
This does not work with IE7 the content does not update if value have html tags with it.
Hi Robert,
Thanks for the heads up…
I’ll take a look at it on IE 7.
[…] a block element, without needing to reload the entire page, using a PHP backend and javascript. [go] Related resources MODx: CMS and PHP Application Framework. LightWindow v1.1A web 2.0 Ajax […]
Any idea why it does not work with IE when passing html tags?
Nice Tutorial
Hi.
I have the same problem as BJ.
It does only show:
“Loading Please Wait…”
IE 7 error msg says: Error: ‘Effect’ is undefined.
What can be wrong?
It looks like this:
http://www.renault-traff.se/test/
What can be wrong?
i want ajax ebooks
With the people having the problem that the content doesn’t load and:
“Loading Please Wait…†remains forever. What is actually happening is the content is loading, but the ‘ setTimeout(”Effect.toggle(’mainAreaLoading’);”, 1000);’ code isn’t working. I believe what Johan says about ‘IE 7 error msg says: Error: ‘Effect’ is undefined.’ is correct. So the problem lies in prototype.js.
Ok fixed the problem. Change:
setTimeout(”Effect.toggle(’mainAreaLoading’);”, 1000);
to:
setTimeout(”Element.toggle(’mainAreaLoading’);”, 1000);
Weird, that fix did not work either.
IE 7 says: “Error: Object exected”
Firefox does not even show the “Loading Please Wait…†text.
It perfectly works in IE7 and FF, maybe you got it installed wrong Johan.
dunno how I can “install” it wrong?
wow… this is really amazing!
Now it works. Thanks Matt
Does it?
When we can expect sql version of script.
I’m new to php programming so i can’t do it on my own. Thanks!
Hi Neven.
I am finishing up my uni exams tomorrow (thursday), so expect to see it at the weekend. I’ll post up a link to it from here to anyone subscribed to this particular feed!
Jamie.
I must say that this script is great. This is first script for manipulating div content from outside on the internet i think. Keep up the good work. And good luck with exams.
Neven
very interessting. thanx for this example.
1. It seems that it removes the cleartyped font aliasing from the content text when fading…
2. Does anybody now how to let it morph from one content to another without the loading screen?
Hello, usable article, thanks!
Is it possible to check when content has been loaded? Currently we have some timeout, I have tested it on my server and noticed that sometime the time not enough. Of course we can prolonger, but I am looking for right way
Thanks.
Hi again, can’t sit and wait.
Check my previous comment!
I made some changes in function loadContent(id):
Ajax.Updater(‘mainAreaInternal’, ‘rpc.php’, {method: ‘post’, postBody:‘content=’+ id +”},onComplete:finishLoading());
// Now finish the loading.
// finishLoading();
And sample still work after this changes
Does any one know, “onComplete” that is what I am think? To check uploading or no?
Thanks!!!
About the “You don’t have permission to access”-error I think it has do it with script believing your php file to be in the same directory as the js file. What to do is either put it in the same directory or give the right path, easiest way might be to give the full path.
As for the file permission idea I think this is wrong because it is not the user requesting the file and so setting permission to 777 for the user to access those files is not very good unless you want someone prying into them.
Hello…
I am using the script, and it’s great. Have one issue though, that someone could perhaps help me with.
I am building up a web portal for the company i’m working at using this script. I have a lot of sites on it.
When people have surfed around the site, perhaps clicking on three or four menu links and they hit their browsers back button, they don’t go one step back, they go to whatever site they came from earlier.
This makes sense to me, as the entire site lies in on file/page. What i need is a sort of back button i can place on my site, that when clicking it, it takes the user one step back, instead of away from the site when he hits the browser back button……
Heads up: feel free to post this app on http://www.redajax.com...
I’m trying to create a hub for all things Ajax.
Thanks.
[…] paremtas” programavimas(angl. Behaviour Driven Development). III dalis. (Ruby On Rails) AJAX/PHP - the beginners guide to loading external content (ajax) Objects, Applications & Applets […]
Cool stuff, Thank you
thanks really nice tutorial planning to include it in a project i’m starting
A really great piece of software… I joined only today your blog but please keep up the good work!
awesome example thanks for sharing
I can not get this to work with Internet Explorer. Nothing shows up at all. I noticed an issue with HTML tags and I took all the tags out and that still didn’t do anything. It works just fine Firefox, wonderfully actually. I was just wondering if anyone came up with a fix for the IE issues.
I have been meaning to write you. This is a great bit of code and it works on my site. However, the extra long content runs over. Any ideas what the problem is?
I tried out your code and it works for the most part. The long content overruns the box and there are no scroll bars. Any ideas as to what is going wrong?
The long content overruns the box and has no scroll bars. Any ideas?
Hi Compassman,
Thanks for your comments, if you have a look at the CSS, mainAreaInternal has an ‘overflow: auto;’ tag, make sure that this is in your version, i cannot see any CSS/Javascript code on your site so cannot confirm.
Let me know what is happening with it.
Jamie.
Hi Gina,
I have had a look at it in IE6 and IE7 and all looks fine, can you email a link to a demo on your site and i’ll take a look,
email: jamie[at]blue44.com
Thanks,
Jamie.
http://members.tripod.co.uk/compassman/ajaxPHPContent/index.html
I tried mine in IE7 and the tabs don’t work. The code works in FF 2, but there is the overflow. The style section does have overflow: auto. I suspect there is a problem with the versions of prototype and scriptalicous.
PS: Sorry for the multiple posts. It appeared that the message wasn’t taking. It wasn’t until I checked the posts that I saw what I had written.
Jamie,
Did you get the email with the link to my test site? I’m desperate for help.
OK, I got it figured out. It is the HTML. You can’t have any HTML markup even in the “mainAreaInternal”, where the content is initially shown. Do we have a fix for this yet? I’m really getting annoyed with IE!!! This is such a cool script. I hate to not be able to use it just because of IE.
Jamie,
Did you get a chance to look at my page to see why the overflow problem exists?
Hello,
i have found a bug in the Code.
If you click two times fastly at the link, the Loading Box doesn’t dissapear. So I wrote this action for the Updater:
delete the functions in loadContent and paste this:
new Ajax.Updater(’mainAreaInternal’, ‘../rpc.php’, {method: ‘post’, postBody:’content=’+ id +”, onStart: startLoading(), onComplete: finishLoading()});
onStart wil load only on beginning end onComplete if the content is loaded.
Greetz Meliboo
[…] Firstly we need to include the script.aculo.us javascript files. I just unzipped the script.aculo.us javascript files into my own folder called ‘js’. Visit Website […]
sry, but i cant use this script…
i add all codes in same page…but dont work..
i download the script.aculo.us, and post…
anybody can make this example and zip it ??
thanks !!
Hi Dante,
Can you provide a URL to the script so we can have a look at the code??
Jamie.
Ok Jamie, the online script is here..
http://ragnacrazy.net/teste/teste.php
the sources is here…
http://nopaste.php-quake.net/4803
thanks Jamie for help-me !!
Dante,
I can see what you have done…
you have not copied in the ‘rpc.php’ file which is the basis of the script.
This file has to be seperate from the main page as it uses an AJAX call and it cannot be printing anything to the screen because that will be displayed.
Copy the ‘rpc.php’ file from the zip and put it into the same directory as the teste.php file and it should work.
If not, repost your link and code and i’ll look again.
Jamie
I again..
i make a new rpc.php file and i put it in same directory of teste.php, but now i have a question…
i need to use “include” in rpc.php to put “teste.php” ??
or some to put in same directory ??
Hi again Dante,
I see the problem, it looks like because i have a font ‘Arial’ being shown when displaying the code in the post it messes up the formatting of the characters.
I have posted links above and in the demo to a ZIP file that’ll get you up and running straight away
Let me know if that helps.
Jamie.
This is a real neat tutorial. The aauthor explained it pretty well.
i have a problem… the info is loading before the loading.gif is showing… so i see the new page, later the loading and the again the page that i loads.
why??
there is also a large and comprehensive database of 500 ajax scripts available with over at ajaxflakes’s ajax scripts compound
thought i should add it might be helpful to others…
http://scripts.ajaxflakes.com
wow ! just the code i was looking for ..
thanks .
Also, is there a way to fetch an external php page w.o having to echo it
nice script…hey checkout http://www.blogoria.com ..its a community for bloggers
I am sure alotta developers out there would love this script
Thank you.
I am newbe to ajax and i searched a lot to find the code to do such a simple script.
Thank you.
New to AJAX. Thank you for such nice post. It is very helful. It’s a complete tutorial.
Courtney Love download…
Nice Post… do you know what is the first? i`ve the new album at my blog http://sumpit.info...
thankyou,
i’ve just started learning ajax,adv javascript and i find it is helpful to me.
again thanks.
I would like a version that could perform a timer ajax load and no need a Loading message. Can you provide something fit my need ?
wow it’s so cool tutorial, I can’t say anything. THANKS !
hi Jaime nice tutorial, im having one small problem though.. its messing up on some pages of my site.. click jokes then any of the categories..
it works correctly on http://mykickspot.com/index.php
but not on:
http://mykickspot.com/forum
notice how it just adds the ajax content on top of the original content instead of completely replacing it.. do you know what the problem is? thanks
Thanks indeed, busy with a holiday planner website, sure gonna need this, thanks again.
Amazing Script but I have a simple problem. All things working fine but at the status bar the yellow triangle thing appears and when i open the log it is saying “id” is null or not an oblect.
Please help. I have exactly follow your example that you have included in the zip file.
Thanks in advance.
dsfsdfsdf
Hey,
Great script, thanks.
I was wondering, how do I remove the numbers on the list items?
thanks
oh #@#@!
must be me
sorry forget that
Jamie, thanks a million- your tutorial and demo files were all it took me to take my first step into AJAX and prototype.js
Having a lot of fun, been bouncing back and forth to your site over the last week. Nice work sunshine.
- Callum.
@ blogulate:
in rpc.php, try something like :
case 1:
include ("http://www.mysite.com/wordpress/index.php");
break;
for example… this will grab the php file from index.php and execute it within the div.
Leave a reply