Switching content (with AJAX)

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.

three

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.

Comments

#1
2006-09-19 manoj says :

thanks a lot! I love this!

#2
2006-10-07 &lt;h1&gt; says :

very useful article on introducing and explaining how ajax works.. Thanx a lot!

#3
2006-10-08 Martin says :

I cant get it to switch data that requires a database connection. frown
Does anyone know how this can be linked up with a database???

#4
2006-10-08 BonRouge says :

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.

#5
2006-10-10 Martin says :

Thanks BonRogue,
Yep, I tried again and I got it going. I figured out what was wrong, pretty much just my bad coding. smile

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!

#6
2006-10-12 Martin says :

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.

#7
2006-10-17 Arthurine says :

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.

#8
2006-10-17 BonRouge says :

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');
}

#9
2006-11-23 Amy says :

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!

#10
2006-11-24 BonRouge says :

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?

#11
2006-12-05 Brenda says :

Can you tell me what is on the page when its working? Don't see that anywhere and in trying it, thanks.

#12
2006-12-05 Brenda says :

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.

#13
2006-12-05 BonRouge says :

Brenda,
The last part of the php says this:else {
echo doIt('one');
}

That's why.

#14
2006-12-07 Brenda says :

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.

#15
2006-12-20 JT says :

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?

#16
2006-12-22 mkosmosports says :

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.

#17
2006-12-22 BonRouge says :

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.

#18
2006-12-22 BonRouge says :

mkosmosports,
That doesn't sound like a problem. Do you want to show me exactly what you mean?

#19
2006-12-22 mkosmosports says :

Hey Bon,

I solved my issue!

Thanks

#20
2006-12-26 IE question says :

first of all wonderful article great work smile. 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???

#21
2006-12-26 BonRouge says :

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.

#22
2006-12-27 IE question says :

i've got IE7 and javascript is definately not disabled ... it still changes the url when i click on any button .. hmmm

#23
2006-12-27 BonRouge says :

IE question,
I've checked IE7 and it works fine.

#24
2006-12-27 IE question says :

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. frown IE is taking revenge coz i've moved to Firefox

#25
2006-12-30 None says :

Not bad at all!

#26
2007-01-08 Eric J. says :

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.

#27
2007-01-09 BonRouge says :

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.

#28
2007-02-03 mkosmosports says :

#29
2007-02-04 BonRouge says :

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.

#30
2007-02-05 mkosmosports says :

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.

#31
2007-02-05 mkosmosports says :

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.

#32
2007-02-06 BonRouge says :

mkosmosports,
Try these files. As I said, it works for me.

#33
2007-02-27 misterK says :

Will this work with onMouseover?

#34
2007-02-27 BonRouge says :

misterK,
Yes.

#35
2007-04-04 Dave says :

Thanks, this is the first AJAX example that I have actually understood whisky

#36
2008-02-01 shez says :

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..

#37
2008-06-04 Neo says :

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.

#38
2008-11-03 Abdi says :

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.

#39
2008-11-03 Abdi says :

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');

#40
2009-07-31 Brooster says :

Is possible to set the last selected option from cookies?

#41
2009-11-23 robs says :

Hi there,
nice cofe, easy to follow for non ejax enabled folhs like me smile
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 smile ?

#42
2010-08-25 Jade says :

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?

#43
2010-10-23 Ocky says :

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..



#44
2011-06-16 LexieGreene says :

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?

#45
2011-06-18 BonRouge says :

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).

#46
2012-01-15 Mitka says :

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

#47
2012-10-31 Patrick says :

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.

#48
2022-08-27 NbfyBossy says :

research paper thesis generator <a href="https://thesismethod.com/ ">argumentative thesis statement</a> thesis statment example

#49
2022-09-27 Jynmntheossemn says :

metformin hydrochloride preparation <a href="https://metforminynd.com/ ">metformin pco kinderwunsch</a> mГҐ metformin knuses

Comment form

Please type the word 'Firefox' here:

BB code available :

  • [b]...[/b] : bold
  • [it]...[/it] : italic
  • [q]...[/q] : quote
  • [c]...[/c] : code
  • [url=...]...[/url] : url