Ajax & PHP without using the XmlHttpRequest Object

Introduction

Ajax is one of the biggest 'discoveries' in the past year, and it has become a real buzzword, just like Web 2.0. Admittedly, Ajax can be used for a lot of things, and it really does speed up web applications. Already Ajax is used by many highly popular websites, most notably GMail, but other's like Ta-da List or Flickr also use it. Heck, even Microsoft has gotten wind of the Ajax buzz, and is actually moving towards web-based applications as well.

But there is one problem with most of the current implementations of Ajax: it has one dependency, and that is the XmlHttpRequest object. Most modern browser, like Firefox, have inbuilt support for this object, but older browsers, like Internet Explorer 6, don't have native support for this object. Luckily, IE 6 does support it, but it's built in as an ActiveX control, which means your visitors get an ugly warning message about the possible danger of an ActiveX control, or in some cases it just doesn't work at all.

In this tutorial, I will show you how to use Ajax without even having to use the XmlHttpRequest object.

The basics

If we can't use the XmlHttpRequest object, we must find some other way to include content from another page, without having to resort to other objects or non-standard things. A great candidate for this would be the <script> tag, which is used to include external JavaScript files. What if, instead of using a regular JS file, we point that tag to a PHP file, which outputs JavaScript. A PHP file which looks something like this:
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. <?php
  2.     $html = '<b>This content came from our Ajax Engine</b>';
  3. ?>
  4. div = document.getElementById('contentdiv');
  5. div.innerHTML = '<?php echo $html; ?>';
<script type="text/javascript">document.write('
');</script>

When this file is used referenced in a script tag, it will try to set the innerHTML of a div with ID 'contentdiv'. But there's one problem; this file shouldn't be included when the page loads, but only when a button is clicked or some other action. To do this, we must somehow dynamically add a new script tag, which is possible using JavaScript. Something like the following would do the trick:
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. // Get base url
  2. url = document.location.href;
  3. xend = url.lastIndexOf("/") + 1;
  4. var base_url = url.substring(0, xend);
  5.  
  6. function ajax_do (url) {
  7.     // Does URL begin with http?
  8.     if (url.substring(0, 4) != 'http') {
  9.         url = base_url + url;
  10.     }
  11.  
  12.     // Create new JS element
  13.     var jsel = document.createElement('SCRIPT');
  14.     jsel.type = 'text/javascript';
  15.     jsel.src = url;
  16.  
  17.     // Append JS element (therefore executing the 'AJAX' call)
  18.     document.body.appendChild (jsel);
  19. }
<script type="text/javascript">document.write('
');</script>

This code first gets the current directory of the url, so we have a base url. The 'ajax_do' function is the thing that does all the work. It first checks whether the url passed to the function points to another domain, or is a relative file.

It then creates a new script element, using the createElement() function. After that it sets the src attribute of the script element, and adds the script element to the body, effectively 'loading' the file that is referenced by the script element.

All we need now is a simple page that triggers the Ajax call, i.e.
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. <html>
  2.     <head>
  3.         <title>Demo 1 - The Basic's</title>
  4.         <script type="text/javascript" src="engine.js"></script>
  5.     </head>
  6.  
  7.     <body>
  8.         <div id="contentdiv">
  9.  
  10.         </div>
  11.         <input type="button" onclick="ajax_do ('page1.php');" value="Get content" />
  12.     </body>
  13. </html>
<script type="text/javascript">document.write('
');</script>

(View Live Demo)
If you view the live demo, or setup it up yourself, you will notice that it works just like Ajax, and probably even better in IE (no more ActiveX warnings).

Please note that for this to work in IE, the security level can't be at 'High'. It must be at 'Medium' or lower.

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: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. <?php
  2. // Get URL and div
  3. if (!isset($_GET['url'])) { die(); } else { $url = $_GET['url']; }
  4. if (!isset($_GET['el'])) { die(); } else { $el = $_GET['el']; }
  5.  
  6. // Make sure url starts with http
  7. if (substr($url, 0, 4) != 'http') {
  8.     // Set error
  9.     echo 'alert(/'Security error; incorrect URL!/');';
  10.     die();
  11. }
  12.  
  13. // Try and get contents
  14. $data = @file_get_contents($url);
  15. if ($data === false) {
  16.     // Set error
  17.     echo 'alert(/'Unable to retrieve "' . $url . '"/');';
  18.     die();
  19. }
  20. // Escape data
  21. $data = str_replace("'", "/'", $data);
  22. $data = str_replace('"', "'+String.fromCharCode(34)+'", $data);
  23. $data = str_replace ("/r/n", '/n', $data);
  24. $data = str_replace ("/r", '/n', $data);
  25. $data = str_replace ("/n", '/n', $data);
  26. ?>
  27. el = document.getElementById('<?php echo $el; ?>');
  28. el.innerHTML = '<?php echo $data; ?>';
<script type="text/javascript">document.write('
');</script>

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:
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. function ajax_get (url, el) {
  2.     // Has element been passed as object or id-string?
  3.     if (typeof(el) == 'string') {
  4.         el = document.getElementById(el);
  5.     }
  6.  
  7.     // Valid el?
  8.     if (el == null) { return false; }
  9.  
  10.     // Does URL begin with http?
  11.     if (url.substring(0, 4) != 'http') {
  12.         url = base_url + url;
  13.     }
  14.  
  15.     // Create getfile URL
  16.     getfile_url = base_url + 'getfile.php?url=' + escape(url) + '&el=' + escape(el.id);
  17.  
  18.     // Do Ajax
  19.     ajax_do (getfile_url);
  20.  
  21.     return true;
  22. }
<script type="text/javascript">document.write('
');</script>

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.

An Example: Ajax-based Form
Let's use our Ajax Engine to create a simple form, and automatically validate all the fields on the server-side. My form looks something like this:
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. <html>
  2.     <head>
  3.         <title>Form Demo - Showing an Ajax Form</title>
  4.         <script type="text/javascript" src="engine.js"></script>
  5.     </head>
  6.     <script type="text/javascript">
  7.         function submit_form() {
  8.             // Get form values
  9.             var name = document.getElementById('name').value;
  10.             var email = document.getElementById('email').value;
  11.             var website = document.getElementById('website').value;
  12.  
  13.             // Construct URL
  14.             url = 'handle_form.php?name=' + escape(name) + '&email=' + escape(email) + '&website=' + escape(website);
  15.  
  16.             ajax_get (url, 'result');
  17.         }
  18.     </script>
  19.     <body>
  20.         <div id="result">
  21.  
  22.         </div>
  23.         <b>Name: </b><input type="text" name="name" id="name" />
  24.         <b>Email: </b><input type="text" name="email" id="email" />
  25.         <b>Website: </b><input type="text" name="website" id="website" />
  26.  
  27.         <input type="button" onclick="submit_form();" value="Send Form" />
  28.     </body>
  29. </html>
<script type="text/javascript">document.write('
');</script>

And my form handler script looks like this:
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. <?php
  2. // Check variables
  3. if (empty($_GET['name'])) {
  4.     die ('<span style="color:red;">Please fill in your name!</span>');
  5. }
  6. if (empty($_GET['email'])) {
  7.     die ('<span style="color:red;">Please fill in your email address!</span>');
  8. }
  9. if (empty($_GET['website'])) {
  10.     die ('<span style="color:red;">Please fill in your website!</span>');
  11. }
  12. echo 'Success! Your form has been submitted!';
  13. ?>
<script type="text/javascript">document.write('
');</script>

And that's all it takes. Click here to view the script in action, and leave one of the fields empty to get some result back.

Conclusion

In this tutorial I have shown you a different method of remote scripting, also known as Ajax. This method doesn't have the same disadvantage as the XmlHttpRequest object, which is great, but it does have a few disadvantages of its own. For example, it isn't possible to do a POST request using this method; only GET requests are possible. Another "disadvantage" is that you can't simply get the content of a page, and use it, but as I've shown you, it's possible to work around this with a little help from PHP.

Another great advantage of this method is that it's possible to use cross-domain remote scripting. Unlike the XmlHttpRequest object, which blocks this, you can point your Ajax calls to scripts and pages on other domains. This is often a (big) disadvantage of the XML object.

You can easily extend the Ajax Engine in this tutorial to a full engine that can handle almost any case, and works in every browser. I've tested the engine in Firefox, IE6 and Opera 7.1, and it worked in Firefox and IE6, but not Opera 7.1, although I'm sure that it's fairly easy to have it working in Opera as well.

If you want to discuss this article further, or want my feedback on anything, leave a comment below, or join the fantastic PHPit Forums!

engine.js
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. // Get base url
  2. url = document.location.href;
  3. xend = url.lastIndexOf("/") + 1;
  4. var base_url = url.substring(0, xend);
  5. var ajax_get_error = false;
  6. function ajax_do (url) {
  7.     // Does URL begin with http?
  8.     if (url.substring(0, 4) != 'http') {
  9.         url = base_url + url;
  10.     }
  11.     // Create new JS element
  12.     var jsel = document.createElement('SCRIPT');
  13.     jsel.type = 'text/javascript';
  14.     jsel.src = url;
  15.     // Append JS element (therefore executing the 'AJAX' call)
  16.     document.body.appendChild (jsel);
  17.     return true;
  18. }
  19. function ajax_get (url, el) {
  20.     // Has element been passed as object or id-string?
  21.     if (typeof(el) == 'string') {
  22.         el = document.getElementById(el);
  23.     }
  24.     // Valid el?
  25.     if (el == null) { return false; }
  26.     // Does URL begin with http?
  27.     if (url.substring(0, 4) != 'http') {
  28.         url = base_url + url;
  29.     }
  30.     // Create getfile URL
  31.     getfile_url = base_url + 'getfile.php?url=' + escape(url) + '&el=' + escape(el.id);
  32.     // Do Ajax
  33.     ajax_do (getfile_url);
  34.     return true;
  35. }
<script type="text/javascript">document.write('
');</script>

handle_form.php
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. <?php
  2. // Check variables
  3. if (empty($_GET['name'])) {
  4.     die ('<span style="color:red;">Please fill in your name!</span>');
  5. }
  6. if (empty($_GET['email'])) {
  7.     die ('<span style="color:red;">Please fill in your email address!</span>');
  8. }
  9. if (empty($_GET['website'])) {
  10.     die ('<span style="color:red;">Please fill in your website!</span>');
  11. }
  12. echo 'Success! Your form has been submitted!';
  13. ?>
<script type="text/javascript">document.write('
');</script>

getfile.php
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1.  
  2. <?php
  3. // Get URL and div
  4. if (!isset($_GET['url'])) { die(); } else { $url = $_GET['url']; }
  5. if (!isset($_GET['el'])) { die(); } else { $el = $_GET['el']; }
  6. // Make sure url starts with http
  7. if (substr($url, 0, 4) != 'http') {
  8.     // Set error
  9.     echo 'alert(/'Security error; incorrect URL!/');';
  10.     die();
  11. }
  12. // Try and get contents
  13. $data = @file_get_contents($url);
  14. if ($data === false) {
  15.     // Set error
  16.     echo 'alert(/'Unable to retrieve "' . $url . '"/');';
  17.     die();
  18. }
  19. // Escape data
  20. $data = str_replace("'", "/'", $data);
  21. $data = str_replace('"', "'+String.fromCharCode(34)+'", $data);
  22. $data = str_replace ("/r/n", '/n', $data);
  23. $data = str_replace ("/r", '/n', $data);
  24. $data = str_replace ("/n", '/n', $data);
  25. ?>
  26. el = document.getElementById('<?php echo $el; ?>');
  27. el.innerHTML = '<?php echo $data; ?>';
<script type="text/javascript">document.write('
');</script>

page1.php
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. <?php
  2. $html = '<b>This content came from our Ajax Engine</b>';
  3. ?>
  4. div = document.getElementById('contentdiv');
  5. div.innerHTML = '<?php echo $html; ?>';
<script type="text/javascript">document.write('
');</script>

page1.html
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. <html>
  2.     <head>
  3.         <title>Demo 1 - The Basic's</title>
  4.         <script type="text/javascript" src="engine.js"></script>
  5.     </head>
  6.     <body>
  7.         <div id="contentdiv">
  8.         </div>
  9.         <input type="button" onclick="ajax_do ('page1.php');" value="Get content" />
  10.     </body>
  11. </html>
<script type="text/javascript">document.write('
');</script>

page2.php
PHP: <script type="text/javascript"> </script> 选择 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. <?php
  2. echo '<b>This content came from our Ajax Engine, without having to use any JS!</b>';
  3. ?>
<script type="text/javascript">document.write('
');</script>

page2.html
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. <html>
  2.     <head>
  3.         <title>Demo 2 - Getting a page's content</title>
  4.         <script type="text/javascript" src="engine.js"></script>
  5.     </head>
  6.     <body>
  7.         <div id="contentdiv">
  8.         </div>
  9.         <input type="button" onclick="ajax_get ('page2.php', 'contentdiv');" value="Get content" />
  10.     </body>
  11. </html>
<script type="text/javascript">document.write('
');</script>

form.html
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. <html>
  2.     <head>
  3.         <title>Form Demo - Showing an Ajax Form</title>
  4.         <script type="text/javascript" src="engine.js"></script>
  5.     </head>
  6.     <script type="text/javascript">
  7.         function submit_form() {
  8.             // Get form values
  9.             var name = document.getElementById('name').value;
  10.             var email = document.getElementById('email').value;
  11.             var website = document.getElementById('website').value;
  12.             // Construct URL
  13.             url = 'handle_form.php?name=' + escape(name) + '&email=' + escape(email) + '&website=' + escape(website);
  14.             ajax_get (url, 'result');
  15.         }
  16.     </script>
  17.     <body>
  18.         <div id="result">
  19.         </div>
  20.         <br />
  21.         <b>Name: </b><input type="text" name="name" id="name" /><br />
  22.         <b>Email: </b><input type="text" name="email" id="email" /><br />
  23.         <b>Website: </b><input type="text" name="website" id="website" /><br />
  24.         <input type="button" onclick="submit_form();" value="Send Form" />
  25.     </body>
  26. </html>
<script type="text/javascript">document.write('
');</script>


Total Files:http://www.phpit.net/demo/php and ajax remix/demos.zip
Article From: PHPit

Another Article:AJAX without XMLHttpRequest, frame, iframe, Java or Flash
PHP: <script type="text/javascript"> </script> 选择 缩进 <script type="text/javascript">AK47[id].writeDiv();</script>
  1. <?php
  2. //================================================================
  3. // Client-server communication (AJAX) using only a stylesheet and
  4. // some javascript.
  5. // Feel free to use and modify this code as you want.
  6. // Credits are appreciated though.
  7. //
  8. // Communication client-serveur (AJAX) utilisant
  9. // uniquement du javascript et une feuille de style.
  10. // Utilisez ou modifiez le script comme bon vous plaira!
  11. // Les crédits sont appréciés.
  12. //
  13. // Julien Lamarre, ogregras@gmail.com
  14. // 2005/09/20
  15. //================================================================
  16. //================================
  17. // Méthode à effectuer
  18. //================================
  19. if(isset($_GET['method']))
  20. {
  21.     $method = $_GET['method'] ;
  22. }
  23. else
  24. {
  25.     outputStylesheet(' ') ;
  26.     exit() ;
  27. }
  28. //================================
  29. // Addition de deux nombres
  30. //================================
  31. if(strcmp($method, 'add') == 0)
  32. {
  33.     if(isset($_GET['valone']) && is_numeric($_GET['valone']))
  34.     {
  35.         $valOne = $_GET['valone'] + 0 ;
  36.     }
  37.     else
  38.     {
  39.         $valOne = 0 ;
  40.     }
  41.     if(isset($_GET['valtwo']) && is_numeric($_GET['valtwo']))
  42.     {
  43.         $valTwo = $_GET['valtwo'] + 0 ;
  44.     }
  45.     else
  46.     {
  47.         $valTwo = 0 ;
  48.     }
  49.     $answer = $valOne + $valTwo ;
  50.     $answerStr = $answer . '' ;
  51.     outputStylesheet($answerStr) ;
  52. }
  53. //================================
  54. // Retourne "Hello World!"
  55. //================================
  56. else if(strcmp($method, 'helloworld') == 0)
  57. {
  58.     $answer = "Hello World!" ;
  59.     // génère le stylesheet avec la réponse
  60.     outputStylesheet($answer) ;
  61. }
  62. //================================
  63. // Qu'est-ce qui est spécial avec ce nombre?
  64. //================================
  65. else if(strcmp($method, 'special') == 0)
  66. {
  67.     if(isset($_GET['number']))
  68.     {
  69.         $valOne = intval($_GET['number']) ;
  70.     }
  71.     else
  72.     {
  73.         $valOne = 0 ;
  74.     }
  75.     if($valOne < 0 || $valOne > 9999)
  76.     {
  77.         $answer = "Nothing special" ;
  78.     }
  79.     else
  80.     {
  81.         $content = file_get_contents('numbers.txt') ;
  82.         $pos = strpos($content, '=' . $valOne . '=') ;
  83.         if($pos === false)
  84.         {
  85.             $answer = "Nothing special" ;
  86.         }
  87.         else
  88.         {
  89.             $pos = $pos + strlen('=' . $valOne . '=') ;
  90.             $pos2 = strpos($content, "/n", $pos) ;
  91.             // ($pos2 - $pos) > 255 : si jamais il y a un bug dans mon fichier de nombres
  92.             if($pos2 === false || ($pos2 - $pos) > 255)
  93.             {
  94.                 $answer = "Nothing special" ;
  95.             }
  96.             else
  97.             {
  98.                 $answer = $valOne . ' ' . substr($content, $pos, $pos2 - $pos) ;
  99.             }
  100.         }
  101.     }
  102.     outputStylesheet($answer) ;
  103. }
  104. else
  105. {
  106.     outputStylesheet(' ') ;
  107.     exit() ;
  108. }
  109. //================================
  110. // Génère la feuille de style avec la réponse du serveur insérée
  111. // dans la propriété "background-image" du div utilisé pour la communication
  112. //================================
  113. function outputStylesheet($msg)
  114. {
  115.     header("Expires: Sun, 1 Jan 2000 12:00:00 GMT");
  116.     header("Last-Modified: " . gmdate("D, d M Y H:i:s") . "GMT");
  117.     header("Cache-Control: no-store, no-cache, must-revalidate");
  118.     header("Cache-Control: post-check=0, pre-check=0", false);
  119.     header("Pragma: no-cache");
  120.     header("Content-Type: text/css");
  121.     $msg = '==' . urlencode($msg) . '==';
  122.     echo
  123.     "
  124.         #divforajax
  125.         {
  126.             background-imageurl($msg) ;
  127.         }
  128.     " ;
  129.     exit() ;
  130. }
  131. ?>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值