Dynamic Links

From Wiki openElement
Jump to: navigation, search

This script allows users to load a new content zone on a page without reloading the page itself. This is done using a database of page titles.

Note: All pages of the website must be in the PHP format, and not in HTM or HTML.


STEP 1:

Create the page "ajax.php". This page will contain all the IDs and access paths for the project's pages.
In this page (ajax.php), paste the following code, changing the PAGE names with the actual names of the pages of your site.

Place this page at the root of the website.

<?php
 
$page=$_GET['page'];
$php='.php';
     if($page==0)require 'DefaultPage'.$php;
else if($page==1)require 'PAGE1'.$php;
else if($page==2)require 'PAGE2'.$php;
else if($page==3)require 'PAGE3'.$php;
else if($page==4)require 'PAGE4'.$php;
else if($page==105)require 'SubFolder/PAGE5'.$php;
else if($page==106)require 'SubFolder/PAGE6'.$php;
else if($page==107)require 'SubFolder/PAGE7'.$php;
else require 'DefaultPage.php';
 
?>

STEP 2:

In page "index.php", insert the following code between the <head> </head> tags.


<!-- START AJAX -->
<script type='text/JavaScript'>
var xhr = null; 
function getXhr()
{
     if(window.XMLHttpRequest)xhr = new XMLHttpRequest(); 
else if(window.ActiveXObject)
  { 
  try{
     xhr = new ActiveXObject("Msxml2.XMLHTTP");
     } catch (e) 
     {
     xhr = new ActiveXObject("Microsoft.XMLHTTP");
     }
  }
else 
  {
  alert("Your web browser does not support XMLHTTPRequest objects..."); 
  xhr = false; 
  } 
}
 
function ShowPage(page)
{
getXhr();
xhr.onreadystatechange = function()
    {
     if(xhr.readyState == 4 && xhr.status == 200)
     {
     document.getElementById('page').innerHTML=xhr.responseText;
     }
    }
xhr.open("GET","ajax.php?page="+page,true);
xhr.send(null);
}
</script>

STEP 3:

This code goes wherever the pages are displayed.

<!-- START display of AJAX pages -->	  
    <div id="page">
     <!--AJAX pages will appear between these two tags-->	
    </div>
<!-- END display of AJAX pages -->

STEP 4:

Then, create the dynamic links as shown below:

<!-- First Link -->
<a href="#" onClick="ShowPage(2)">Display page 2</a>
<!-- Second Link -->
<a href="#" onClick="ShowPage(107)">Display page 7</a>

Explanation:

onClick="ShowPage(2)" ---> The "2" is the ID given to the page in "ajax.php" and corresponds in this example to: "page2.php"

To display "page2.php", enter: onClick="ShowPage(2)"
To display "page5.php", entere: onClick="ShowPage(105)"
etc...


Big thanks to MicroVinc on the forum for providing this script.

Personal tools
Namespaces

Variants
Views
Actions
openElement
Community
Toolbox