Getting a page's content
In the previous example, I had to use some JavaScript in page1.php to set the innerHTML of the content div. But what if you don't want to do that, and simply want to include the content of another page?
That's also possible with our method, except we need to create a PHP script that can help us slightly. This PHP script needs to get the contents of a page, and then output the correct JavaScript to set the innerHTML of an element. My 'getfile.php' looks like this:
|
<?php
// Get URL and div if (!isset($_GET['url'])) { die(); } else { $url = $_GET['url']; } if (!isset($_GET['el'])) { die(); } else { $el = $_GET['el']; }
// Make sure url starts with http
if (substr($url, 0, 4) != 'http') { // Set error echo 'alert(\'Security error; incorrect URL!\');'; die(); }
// Try and get contents $data = @file_get_contents($url);
if ($data === false) { // Set error echo 'alert(\'Unable to retrieve "' . $url . '"\');'; die(); }
// Escape data $data = str_replace("'", "\'", $data); $data = str_replace('"', "'+String.fromCharCode(34)+'", $data); $data = str_replace ("\r\n", '\n', $data); $data = str_replace ("\r", '\n', $data); $data = str_replace ("\n", '\n', $data); ?> el = document.getElementById('<?php echo $el; ?>'); el.innerHTML = '<?php echo $data; ?>'; |
As you can see it first gets the contents of a page, using the file_get_contents() function, and then outputs the right javascript to set the innerHTML of the element.
The Ajax Engine function that works together with this PHP script is the following:
|
function ajax_get (url, el) { // Has element been passed as object or id-string? if (typeof(el) == 'string') { el = document.getElementById(el); }
// Valid el? if (el == null) { return false; }
// Does URL begin with http? if (url.substring(0, 4) != 'http') { url = base_url + url; }
// Create getfile URL getfile_url = base_url + 'getfile.php?url=' + escape(url) + '&el=' + escape(el.id);
// Do Ajax ajax_do (getfile_url);
return true; } |
What this function does is first check whether the element actually exists, then create the url to the getfile.php file, including the page to get the contents from and the id of the element, and then fires of the Ajax call using our previous ajax_do() function. Simply, easy and it just works! Click here to view a live demo of this in action.