...

View Full Version : Toggle div, loading content externally on toggle



XYZ12345
09-01-2011, 11:49 AM
Hi there!

Okay, here is my scenario:

I have a link and a div on a webpage. With the link I want to toggle the content (HTML) of the div. On toggle, I want to load the content from a PHP-file and I want it to load on the toggle, not when the webpage originally loaded (to reduce loading time on the webpage itself).

The file that is loaded on toggle doesn't have to be PHP, but it would help a lot.

Does anybody know of a example of this or something similar to it? I have been looking for some time now, without any luck unfortunately.

Highly appreciate any help/answers/feedback!

Rowsdower!
09-01-2011, 05:28 PM
You are looking for "AJAX" to do this type of thing. Here is some very rough (and untested) code to get you started:

Javascript:

function ajax_content_switch(number){
var urls= new Array( "http://www.yoursite.com/page_to_load.php" , "http://www.yoursite.com/page_to_load_2.php" , "http://www.yoursite.com/page_to_load_3.php");
var ajax_run;
if (window.XMLHttpRequest){
// code for IE7+, Firefox, Chrome, Opera, Safari
ajax_run = new XMLHttpRequest();
}
else{
// code for IE6, IE5
ajax_run = new ActiveXObject("Microsoft.XMLHTTP");
}
ajax_run.onreadystatechange = function(){
if (ajax_run.readyState==4 && ajax_run.status==200){
//Page was found and whatever the server gave us has been loaded...
result = ajax_run.responseText;
if (result!=''){
//AJAX returned some content, so we process it...
update_content(result);
}
else{
//AJAX returned a blank page, show error alert...
alert('Content failed to load!');
}
}
else{
//Page not found or otherwise failed to load...
alert('Content failed to load!');
}
}
ajax_run.open("GET",urls[number],true);
ajax_run.send();
}
function update_content(contents){
//do whatever you need here in order to show the contents where you want them...
document.getElementById('target').innerHTML=contents;
}

Then you call the function onclick something like this:

HTML snippet:

<a onclick="ajax_content_switch(0);">Page 1</a> |
<a onclick="ajax_content_switch(1);">Page 2</a> |
<a onclick="ajax_content_switch(2);">Page 3</a>
<div id="target"></div>

So when you click on the first link it loads data in from the first URL in your array, the second link loads data from the second URL, and so on.

Note that all URLs being used must be on the same domain as the page you are on. This is a browser security feature and it cannot be overcome by javascript.

You can load anything you want there, be it PHP-driven or static HTML. The AJAX call doesn't know or care what the difference is.



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum