View Full Version : [Script] Ajax Page Load
Mentor
17-04-2007, 03:19 PM
Ok, theres been a few people asking for this lately so i thought id provide a script ive written. What an ajax load normaly is, is a method where an xmlhttp request is made via javascript and the content of a page is dynamically loaded in to a div of your choice.
Currently im going to provide a very basic script, which just takes a page and displays the contents in a div, via ajax.
I may later add an advanced version which will support additional function, to work with a php navigation meaning search engines can still crawl the content, the back button and favorites still works.
Basic script
Features:
> Shows page is loading
> dynamically loads page to a div.
<script>
//Set up variables
var xmlhttp ;
var thediv;
function LoadPage(page,usediv) {
// Set up request varible
try {xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");} catch (e) { alert("Error: Could not load page.");}
//Show page is loading
document.getElementById(usediv).innerHTML = 'Loading Page...';
//scroll to top
scroll(0,0);
//Store div in use
thediv = usediv;
//send data
xmlhttp.onreadystatechange = ShowPage;
xmlhttp.open("GET", page);
xmlhttp.send(null);
//Stop any link loading normaly
return false;
}
function ShowPage(){
//Check page is completed and there were no problems.
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
//Write data returned to page
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
</script>
This function can now be called via creating a link like this.
<a href="mypage.htm" onclick="return LoadPage('mypage.htm','mydiv');">
The above would place the contents of "mypage.htm" in to a div with the id "mydiv" such as could be written '<div id="mydiv"></div>'
The parts of the link in bold being what need editing.
I wrote the script on the go so its completely untested but should hopefully work. If it doesnt post back with the problem and ill sort it out for you.
Edit: phew noticed just in time, id forgotten to store the div id in the function independents variable, which would have stopped it from working, should be fixed now.
Recursion
17-04-2007, 03:24 PM
Very Usefull and very kind :) +REP if i can :)
redtom
17-04-2007, 03:40 PM
Great now watch all the habbo site change from iframes to this, thats why no one was giving it out, but it's your code you can do what you want with it, + rep anyway.
Mentor
17-04-2007, 04:00 PM
Great now watch all the habbo site change from iframes to this, thats why no one was giving it out, but it's your code you can do what you want with it, + rep anyway.
Whats wrong with them doing that o.0 The scripts simplistic anyway, its not even close to being functionally equivalent to a proper ajax loading system (such as i wrote for thybag) it cant really do anything above or beyond what an Iframe can, it just looks a bit better.
Mr Macro
17-04-2007, 04:42 PM
REP+ I was going to post the tutorial written on DynamicDrive, but someone was saying somthing about fnasites will be ripping it.So i left it, nice one though :)
omgDAN!
17-04-2007, 04:44 PM
Nice thanks +rep
can I ask you, how do you do that "not using firefox" thing on your site?
Thanks
Invent
17-04-2007, 04:49 PM
Why not just use a simple preg_match function checking for say MSIE against $_SERVER['HTTP_USER_AGENT'] for internet explorer?
If your host supports it:
http://us.php.net/manual/en/function.get-browser.php
Mr.OSH
17-04-2007, 05:15 PM
Ok, theres been a few people asking for this lately so i thought id provide a script ive written. What an ajax load normaly is, is a method where an xmlhttp request is made via javascript and the content of a page is dynamically loaded in to a div of your choice.
Currently im going to provide a very basic script, which just takes a page and displays the contents in a div, via ajax.
I may later add an advanced version which will support additional function, to work with a php navigation meaning search engines can still crawl the content, the back button and favorites still works.
Basic script
Features:
> Shows page is loading
> dynamically loads page to a div.
<script>
//Set up variables
var xmlhttp ;
var thediv;
function LoadPage(page,usediv) {
// Set up request varible
try {xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");} catch (e) { alert("Error: Could not load page.");}
//Show page is loading
document.getElementById(usediv).innerHTML = 'Loading Page...';
//scroll to top
scroll(0,0);
//Store div in use
thediv = usediv;
//send data
xmlhttp.onreadystatechange = ShowPage;
xmlhttp.open("GET", page);
xmlhttp.send(null);
//Stop any link loading normaly
return false;
}
function ShowPage(){
//Check page is completed and there were no problems.
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
//Write data returned to page
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
</script>
This function can now be called via creating a link like this.
<a href="mypage.htm" onclick="return LoadPage('mypage.htm','mydiv');">
The above would place the contents of "mypage.htm" in to a div with the id "mydiv" such as could be written '<div id="mydiv"></div>'
The parts of the link in bold being what need editing.
I wrote the script on the go so its completely untested but should hopefully work. If it doesnt post back with the problem and ill sort it out for you.
Edit: phew noticed just in time, id forgotten to store the div id in the function independents variable, which would have stopped it from working, should be fixed now.
Thanks for that Carl, this could come in useful at some point. + rep. Well done. :)
ScottDiamond
17-04-2007, 06:07 PM
Why did you just quote the whole post? And Carl, thanks for explaining every line to me in MSN lol.
Mr.OSH
17-04-2007, 06:09 PM
Why did you just quote the whole post? And Carl, thanks for explaining every line to me in MSN lol.
Ooops, sorry I'm used to quoting things. :(
ScottDiamond
17-04-2007, 06:11 PM
=D =D =D =D
Mentor
17-04-2007, 06:13 PM
Why not just use a simple preg_match function checking for say MSIE against $_SERVER['HTTP_USER_AGENT'] for internet explorer?
Thats how mine works :p
Great now watch all the habbo site change from iframes to this, thats why no one was giving it out, but it's your code you can do what you want with it, + rep anyway.
That's a bit selfish don't you think?
Code is out there to be used; not allowing someone to use it in such a way is denying people of the privledge to use it?
It was on DD for the record.
Mentor
17-04-2007, 06:29 PM
That's a bit selfish don't you think?
Code is out there to be used; not allowing someone to use it in such a way is denying people of the privledge to use it?
It was on DD for the record.
Mine has less crap in it than DD's.
DD's stuff always seems to be incredibly long winded and inefficient for no real reason "/
On the topic of including to much crap i combined it in to a single function, i think it will still work, i haven't tested again, main differences is i put the second function in the first.
function LoadPage(page,usediv) {
// Set up request varible
try {xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");} catch (e) { alert("Error: Could not load page.");}
//Show page is loading
document.getElementById(usediv).innerHTML = 'Loading Page...';
//scroll to top
scroll(0,0);
//send data
xmlhttp.onreadystatechange = function(){
//Check page is completed and there were no problems.
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
//Write data returned to page
document.getElementById(usediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", page);
xmlhttp.send(null);
//Stop any link loading normaly
return false;
}
Im working on the assumption formating like this means i dont need to define a globally scoped variable (which cases problems if your actually useing the asynchronous part of ajax), and that i used the inline function syntax right.
Colin-Roberts
17-04-2007, 08:20 PM
anway to make the content load so many pixels to the rite of the beginning of the content box? and thanks mentor
do i still have news privladges on your site?
Mentor
17-04-2007, 09:36 PM
anway to make the content load so many pixels to the rite of the beginning of the content box? and thanks mentor
do i still have news privladges on your site?
not sure why you would want to, but if your asking what i think you are, easyst way would just be add a margin or padding in CSS to the div your loading the content in to ?
Also just for the hell of it, even smaller version
function LoadPage(p,d) {
try {xh = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");} catch (e) { alert("Error: Could not load page.");}
pd = document.getElementById(d); pd.innerHTML = 'Loading Page...'; scroll(0,0);
xh.onreadystatechange = function(){if ((xh.readyState == 4) && (xh.status == 200)) {pd.innerHTML = xh.responseText;}}
xh.open("GET", p); xh.send(null); return false;
}
:Edzy
18-04-2007, 07:37 AM
Ok, theres been a few people asking for this lately so i thought id provide a script ive written. What an ajax load normaly is, is a method where an xmlhttp request is made via javascript and the content of a page is dynamically loaded in to a div of your choice.
Currently im going to provide a very basic script, which just takes a page and displays the contents in a div, via ajax.
I may later add an advanced version which will support additional function, to work with a php navigation meaning search engines can still crawl the content, the back button and favorites still works.
Basic script
Features:
> Shows page is loading
> dynamically loads page to a div.
<script>
//Set up variables
var xmlhttp ;
var thediv;
function LoadPage(page,usediv) {
// Set up request varible
try {xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");} catch (e) { alert("Error: Could not load page.");}
//Show page is loading
document.getElementById(usediv).innerHTML = 'Loading Page...';
//scroll to top
scroll(0,0);
//Store div in use
thediv = usediv;
//send data
xmlhttp.onreadystatechange = ShowPage;
xmlhttp.open("GET", page);
xmlhttp.send(null);
//Stop any link loading normaly
return false;
}
function ShowPage(){
//Check page is completed and there were no problems.
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
//Write data returned to page
document.getElementById(thediv).innerHTML = xmlhttp.responseText;
}
}
</script>
This function can now be called via creating a link like this.
<a href="mypage.htm" onclick="return LoadPage('mypage.htm','mydiv');">
The above would place the contents of "mypage.htm" in to a div with the id "mydiv" such as could be written '<div id="mydiv"></div>'
The parts of the link in bold being what need editing.
I wrote the script on the go so its completely untested but should hopefully work. If it doesnt post back with the problem and ill sort it out for you.
Edit: phew noticed just in time, id forgotten to store the div id in the function independents variable, which would have stopped it from working, should be fixed now.
FIT ily - +rep
Mentor
18-04-2007, 02:22 PM
As an exspantion, an updated version which now allows people to bookmark pages loaded via ajax. And Allows the backbutton to function correctly in firefox (not IE as that doesnt change the URI when a new hash is set)
Long version
var CurrentPage;
function LoadPage(page,usediv) {
// Set up request varible
try {xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");} catch (e) { alert("Error: Could not load page.");}
//Show page is loading
document.getElementById(usediv).innerHTML = 'Loading Page...';
//scroll to top
scroll(0,0);
//Change loaction hash.
document.location.hash = page;
//Store current page.
CurrentPage = document.location.hash;
//send data
xmlhttp.onreadystatechange = function(){
//Check page is completed and there were no problems.
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
//Write data returned to page
document.getElementById(usediv).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", page);
xmlhttp.send(null);
//Stop any link loading normaly
return false;
}
//Poll hash to see if back button has been pressed
setInterval(CheckBack, 500);
function CheckBack(){
// if the hash has changed from what was set in the script reload page.
if(CurrentPage !== document.location.hash){
LoadPage(document.location.hash);
}
}
Short version
var cp;
function LoadPage(p,d){
try {xh=window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");} catch (e){alert("Error: Could not load page.");}
pd=document.getElementById(d);h=document.location. hash;pd.innerHTML='Loading Page...';scroll(0,0);h=p;cp=h;
xh.onreadystatechange=function(){if((xh.readyState ==4)&&(xh.status==200)){pd.innerHTML=xh.responseText;}}
xh.open("GET",p);xh.send(null);return false; }
function CheckBack(){if(cp!==document.location.hash){LoadPa ge(document.location.hash);}} setInterval(CheckBack,500);
Again both are completely untested but should work just fine
Luckyrare
18-04-2007, 03:14 PM
Nice one, very interesting ;]
Great now watch all the habbo site change from iframes to this, thats why no one was giving it out, but it's your code you can do what you want with it, + rep anyway.
mmm, if you search on google for 30 seconds you will find a number of libs/tutorials.
UnderGROUND
21-04-2007, 11:11 PM
Hey, sorry to bump a little, but would this be possible to load a page, showing how many users online (I have the .php with the code), then an ajax reload that reloads every 30 seconds?
Mentor
21-04-2007, 11:29 PM
Yup very easy.
youd want somthing along these lines
//Calls function every 30 seconds. (function takes time in miliseconds)
setInterval(Getstats, 30000);
//id of div to put stats in to
var divname = "Mydiv";
var statpage ="stats.php";
function Getstats() {
// Set up request varible
try {xmlhttp = window.XMLHttpRequest?new XMLHttpRequest(): new ActiveXObject("Microsoft.XMLHTTP");} catch (e) {}
//send Request
xmlhttp.onreadystatechange = function(){
//Check page is completed and there were no problems.
if ((xmlhttp.readyState == 4) && (xmlhttp.status == 200)) {
//Write data returned to div
document.getElementById(divname).innerHTML = xmlhttp.responseText;
}
}
xmlhttp.open("GET", statpage);
xmlhttp.send(null);
}
What the above will do is write the contentes of "stats.php" to a div by the name of "Mydiv" every 30 seconds.
Stats.php just needs to change its contence so the stats are correct every time it is loaded, that will then be shown in the div.
You change the div being used or the page being loaded via the two varibles:
var divname = "Mydiv";
var statpage ="stats.php";
Again, i havent tested it works so there could be a problem in it, hopefuly theres not, but if there is feel free to ask for help with it.
Also it may be a good idea to add some headers in the php of the page stats are loaded from to stop the brower cacheing that page.
hope that helps :)
ps. if theres an error and it doesnt load, the script just wont right anything, as opposed to alerting theres a problem as with the page load scripts.
UnderGROUND
21-04-2007, 11:34 PM
Ah man, you are awesome. I shall test now, thanks very much!
Mentor
21-04-2007, 11:40 PM
ok, hope it all works :)
UnderGROUND
21-04-2007, 11:55 PM
I think my mysql databases are down - what a bad time for that to happen eh? I'll have to wait untill they're back up to see if it works.
As it shows the User online: 1 but it doesnt update even when my friends on (but its not your code, its actually the stats script). So I will post here when its back up! =)
thanks again! :D
EDIT: its not my mysql databases, must be my code. hmm, ill fix it and post back thanks!
UnderGROUND
22-04-2007, 12:12 AM
I cant edit, so here we goooo. I fixed my script.
I have the div for where I want it to be show as <div name="online"></div> and the part in your code is: var divname = "online";
yet it doesn't work, I think im doing something wrong xD It just displays 1 user online. and doesnt go up.
Mentor
22-04-2007, 12:23 AM
Can you pm me a link to the page your useing it on? that way i can check to see whats going wrong with it :)
UnderGROUND
22-04-2007, 12:27 AM
Sure, I have done ^^
Want to hide these adverts? Register an account for free!
Powered by vBulletin® Version 4.2.5 Copyright © 2025 vBulletin Solutions Inc. All rights reserved.