Here's one way to change the content of your page without reloading the page. This uses AJAX.
AJAX is a fancy name for a combination of javascript and php. Someone will probably tell me that's a bad defintion, but I think it's good enough. Basically, the javascript sends a variable to a php page, gets a response from the php page and then acts on that response.
Of course, one small drawback of this is that, being javascript, it requires the user's browser to have javascript enabled in order to see your content. While most do have javascript enabled, some don't, so there may be a problem.
To get around that, you can have an 'a' tag which will do the javascript thing if javascript is enabled or just follow the link as normal if it isn't. By following the link, we can use the same php script to include the same content. The only difference is that the page refreshes.
So, here are some links. Underneath them is the added content.
two
The html looks like this:
HTML
<ul id="options">
<li><a href="br.php?page=ajaxswitch&content=one">one</a></li>
<li><a href="br.php?page=ajaxswitch&content=two">two</a></li>
<li><a href="br.php?page=ajaxswitch&content=three">three</a></li>
</ul>
<div id="ajaxcontent">
<?php include 'ajaxcontent.php'; echo $show; ?>
</div>
There is a javascript function that assigns an onclick event to each of the links so that the browser executes another javascript function rather than follow the link.
javascript
function showIt() {
var aTags=document.getElementById('options').getElementsByTagName('a');
for (i=0; i<aTags.length; i++) {
aTags[i].onclick=function() {
var show=this.href.split('content=')[1];
ajaxSwitch(show);
return false;
}
}
}
window.onload=showIt;
The included php file looks like this:
php
<?php
function doIt($it) {
switch ($it) {
case "one":
return "<p>one</p>";
break;
case "two":
return "<p>two</p>";
break;
case "three":
return "<p>three</p>";
break;
}
}
if (isset($_GET['content'])) {
$content=$_GET['content'];
$show=doIt($content);
}
elseif (isset($_GET['showit'])) {
$showit=$_GET['showit'];
echo doIt($showit);
}
else {
echo doIt('one');
}
?>
It will check to see if the variable 'content' has been sent via the URL (which will happen if javascript is disabled and one of the links has been followed) and print the appropriate content. The 'else' clause tells it to show the first bit of content by default.
If javascript is enabled, as it usually is, this function will be called when a link is clicked:
javascript
var request = false;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
request = new ActiveXObject("Msxml2.XMLHTTP");
} catch (e) {
try {
request = new ActiveXObject("Microsoft.XMLHTTP");
} catch (e2) {
request = false;
}
}
@end @*/
if (!request && typeof XMLHttpRequest != 'undefined') {
request = new XMLHttpRequest();
}
function ajaxSwitch(content) {
/*the name of your page with the content goes here */
var url = "ajaxcontent.php?showit=" + escape(content);
request.open("GET", url, true);
request.onreadystatechange = go;
request.send(null);
}
Well, the first part of that is not actually a function, but that's not really important here. The bit up there before the function sets up the XMLHttpRequest(), which is the thing that lets us get information from the php page.
The function just sends the variable to the php page and then starts another function when it's received a response.
The other function looks like this:
javascript
function go() {
if (request.readyState == 4) {
if (request.status == 200) {
var response = request.responseText;
/* 'ajaxcontent' is the name of my div that will contain the info */
document.getElementById("ajaxcontent").innerHTML = response;
}
}
}
That kind of double-checks that it has a response from the php page and then fills the div 'ajaxcontent' with the appropriate content.
It seems quite complicated, but there are only a few places that you need to change to make it work on your site.
Here are some files that show a simple example.
very useful article on introducing and explaining how ajax works.. Thanx a lot!
I cant get it to switch data that requires a database connection.
Does anyone know how this can be linked up with a database???
Martin,
That should be no problem at all. AJAX is often used because it get results from a database. There's a php file involved in this page. Just put your database connection and query in that and have it return the result.
Thanks BonRogue,
Yep, I tried again and I got it going. I figured out what was wrong, pretty much just my bad coding.
You can have a look at www.anythingclose.com
BTW. The site I've got there at the moment is just filling in for something else.. hence the url not having anything to do with the site.
Keep up the good work with the site. IMO it's about the best css resource out!
Hello. If anyone wants to have this ajax switcher display "Loading...." while the content switch is in progress you add this line :
document.getElementById("ajaxcontent").innerHTML = '<span class="ajax_loading">LOADING...</span>';
directly after this line:
/*the name of your page with the content goes here */
Update on the previous post. The problem I was having was that the XMLHttpRequest in the ajaxswitcher doesn't send the session cookie. If anyone knows how to add this feature to the switcher javascript please let me know.
else {
echo doIt('one');
}
I am trying to write code to extend this example in my application. It all works great with one exception. I would like to have a default image displayed. This else is hard coded. Is it possible on the first time in the code (since you do not have onClick) to display a parameter for the image.
Arthurine,
You could add this to the switch arguments: case "first":
return "<p><img src="defaultimage.jpg" alt="img" /></p>";
break;
then use else {
echo doIt('first');
}
Is there a way to make something other than "one" show in the source code? I am trying to get the php to show in the source code while all the rest of this is happening. Thanks!
Amy,
Not really sure what you mean. You can have anything you like show. The 'one', 'two' and 'three' are just examples. You say you're trying to get the php to show... what php exactly? Can you explain your problem a little more?
Can you tell me what is on the page when its working? Don't see that anywhere and in trying it, thanks.
Nevermind I got it, very, very cool. Curious though why one is always the first to appear even when I move things around in the js and the php, encluding the echo"one." Any idea why it still shows on the page first? Thanks.
Brenda,
The last part of the php says this:else {
echo doIt('one');
}
That's why.
Its working now. If anyone else has this problem. I had to complete delete the echo one, from the content file, then upload it empty. Then I uploaded it again replacing it with something new. Don't ask me why. Whatever works.
Anyone know how I can use a form on ajaxswitch.php and when a link is clicked, form information is sent to an e-mail?
This is a great method, except Im having one problem. in the page where there are links to the content switch I have a url parameter which I would like to carry over to the ajaxswitch.js page.
JT,
You'll need a simple script to get the values of the text fields. Then, you add them to the URL in the ajaxSwitch() function. The values will go the page you send them to. On that page you can have something like this:$name=$_GET['name'];
$email=$_GET['email'];
$message=$_GET['message'];
mail( "me@myaddress.com", "Message From $name <$email>", $message, "From: $email" );
echo "Message sent";
That should do it.
mkosmosports,
That doesn't sound like a problem. Do you want to show me exactly what you mean?
Hey Bon,
I solved my issue!
Thanks
first of all wonderful article great work . I got a question ok in firefox when you click on any of the three buttons the "url" in the "address bar" does not change. But in IE it changes to whatever button was clicked. Does that mean that this example does not work in IE???
IE question,
This does work in IE. What your situation suggests to me is that you have javascript disabled in IE.
Crazy name by the way.
i've got IE7 and javascript is definately not disabled ... it still changes the url when i click on any button .. hmmm
IE question,
I've checked IE7 and it works fine.
hmm, this is very strange <li><a href="#" onclick="ajaxSwitch('one'); return false">one</a></li>
if i use this then it works perfectly, but as soon as I put the link back it screws up. IE is taking revenge coz i've moved to Firefox
Not bad at all!
I love the script, simple and clean. I was wondering, do you have any ideas on how to incorporate a url in for each piece of content, and/or enable back button usage? There are some guides online, but most are above my head at this point.
Eric J,
This script is actually written with urls to the content in mind. If the javascript fails, the link will refresh the page and show the appropriate content.
Here's an example: http://bonrouge.com/br.php?page=ajaxswitch&content=two
As for the back button... I've never thought about it very much to be honest. I've just had a quick search and you're right - it does look quite complicated. When I have some free time, I'll see if I can get my head around it.
mkosmosports,
I think I have an answer for you. I tested it and it worked for me...
Use utf8_encode() on whatever the php is echoing. That's to say, in the example on this page, do this:elseif (isset($_GET['showit'])) {
$showit=$_GET['showit'];
echo utf8_encode(doIt($showit));
}
else {
echo utf8_encode(doIt('one'));
}
I hope that helps.
Hmm. That didnt seem to have any effect bon. I think the XMLHttpRequest() needs to be somehow modified to preserve the utf8 encoding. Ive got another question however, is there a way I can communicate with the url that represents the switching content from the 'parent url'. I want to write a condition saying if url parameter 'mon' is set in the switching content, clear certain session variables....
Thanks Bon.
Ahh..damn..nevermind Bon, I solved the above problem. Sessions are indeed a beautiful feature of php. I gotta get a secure handle on them. Ill kepp on investigating the corrupted character problem, and post my solution once one is available.
Will this work with onMouseover?
misterK,
Yes.
Thanks, this is the first AJAX example that I have actually understood whisky
Not to be "pedantic" but Ajax isnt really concerned with just PHP, you could have perl/asp.net or any other server side lang. Ajax just makes it possible to do something that would have otherwise cost you a click/page reload
Oh btw excellent site here i keep forgetting to say that..
Alright, this is pretty cool, but I'm having a problem, I have it set up and it works, but it doesn't show the address in the address bar, I think this is the reason that when it get flooded with requests, for example: If you click the links to fast it ends up just showing ajaxswitch.php in a blank page. This only affects firefox.
A better way to show a default value is to use the "default" switch case.
default:
return "your default value here";
break;
just before the "break;" so that it looks like the above. Then go down to the else statement near he end and change the "one" to "default". Now you have code that is a little more solid.
I think this is what Amy was asking about. Hope this helps someone.
quick follow up on my last post. The else statement line I was referring to is: echo doIt('one');
just change that to...
echo doIt('default');
Is possible to set the last selected option from cookies?
Hi there,
nice cofe, easy to follow for non ejax enabled folhs like me
Question, I want to use this with a select list and not use urls, basically changing entire form contents following on from a select.
Can i use onChange and if so hwo ?
Hello is there a way to keep the link highlighted to show which content your on. Also i get a '1' in the corner how do i get rid of it?
Quote <b>"var show=this.href.split('content=')[1];"</b>
Quote <b>"var url = "ajaxcontent.php?showit=" + escape(content);"</b?
i don't understand what [1] means.. and escape (content).. Can someone explain those quote thx.. this tutorial really good..
I'm not sure if you'll get this since the last time you posted on this thread was like 3 years ago... but anyways. I'm having a problem trying to get this code to work.
It started working when I put onClick="showIt(); return false" in the a tag, but only if I do that... And I also have to click the link twice the first time.
What do you think it could be?
LexieGreene,
Could you maybe post a link to your test page so that I could have a look? (Or send it to me via the 'contact me' thing on the left).
This a long shot if I get a reply I ge this error:
Notice: Undefined variable: show in C:\wamp\www\AJAX Switch\ajaxswitch.php on line 26
Location: ..\ajaxswitch.php:0
It works but this shows on the 1st load.
Using WAMP Server 2.2
I am trying to write code to extend this example in my application. It all works great with one exception. I would like to have a default image displayed. This else is hard coded. Is it possible on the first time in the code (since you do not have onClick) to display a parameter for the image.
research paper thesis generator <a href="https://thesismethod.com/ ">argumentative thesis statement</a> thesis statment example
metformin hydrochloride preparation <a href="https://metforminynd.com/ ">metformin pco kinderwunsch</a> mГҐ metformin knuses
thanks a lot! I love this!