ASPit - Totally ASP
Search PHPit

Use this textbox to search for articles on PHPit. Seperate keywords with a space.


Ajax & PHP without using the XmlHttpRequest Object

(Page 3 out of 3)

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:

                </span>Form Demo - Showing an Ajax Form<span class="sc2"><span class="kw2">

                type="text/javascript" src="engine.js">       

                function submit_form() {
                                // Get form values
                                var name = document.getElementById('name').value;
                                var email = document.getElementById('email').value;
                                var website = document.getElementById('website').value; 
                                // Construct URL
                                url = 'handle_form.php?name=' + escape(name) + '&email=' + escape(email) + '&website=' + escape(website);

                                ajax_get (url, 'result');





                Name: type="text" name="name" id="name" />
                Email: type="text" name="email" id="email" />
                Website: type="text" name="website" id="website" />

                type="button" onclick="submit_form();" value="Send Form" />

And my form handler script looks like this:

// Check variables
if (empty($_GET['name'])) {
        die ('Please fill in your name!');

if (empty($_GET['email'])) {
        die ('Please fill in your email address!');

if (empty($_GET['website'])) {
        die ('Please fill in your website!');

echo 'Success! Your form has been submitted!';


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.


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!

« Previous: Getting a page's content

64 Responses to “Ajax & PHP without using the XmlHttpRequest Object”

  1. Renny Says:

    Cool! I like this way of AJAX’ing much more, then classic one! Thank you!!!!

  2. Stoyan Says:


    If somebody is interested in reading another article on this way of making remote requests -
    There are also interesting user contributed comments.

    Keep it up!

  3. blah Says:

    if thats ajax your on crack.

  4. Ahmed Says:

    You mention a warning,… WHAT warning? IE6 only shows a warning if you are running the Site Localy, but as long as its on a distant domain, there are no problems!

    A good example is GMail, I’ve never seen any warning generated by IE when visiting GMail!

  5. James Says:

    This is very clever. But please, learn some history:

    “Heck, even Microsoft has gotten wind of the Ajax buzz, and is actually moving towards web-based applications as well.”

    Microsoft invented AJAX, and has been offering Web-based apps since ‘98. Unfashionable, I know, to credit them with anything, but there you go.

  6. Ajax Blog Says:

    Ajax without the X? - Good article about combining a generic Javascript new script engine with some PHP to deliver simple AJAX interactions

    If you’ve wrestled with the whole XMLHttpRequest part of AJAX you should read this article. It clearly explains the technique of appending a new Javascript SCRIPT tag into the body and using the results to display new or updated content.

    But …

  7. Pat Says:

    This is one ridiculously clever way of getting the same effect. Good job!

  8. Vodstock Says:

    Coincidentally, I just found this while taking a break from trying my hand at some ‘traditional’ AJAX for the first time. I like your method a lot - it’s small and effective.
    One change I’m making (to your first example) is to hide the linked URL from the status bar by hardcoding it into the JavaScript and then passing a variable to it using ajax_do(’variable’).

    E.g. I replaced:
    if (url.substring(0, 4) != ‘http’) {
    url = base_url + url;

    var url = ‘page1.php?id=’ + id;

    Great work - thank you for sharing this tutorial.

  9. Mumblez Says:

    Very cool, you should name it before someone else does :), its bound to happen, how about PHPaJax, or PhyJapjax, or …..Hangs to the left and is a bit wonkey!!!!

  10. stefan Says:

    quote from your second example page: “This content came from our Ajax Engine, without having to use any JS!”

    Uhm. Hate to break it to you, but you *are* using JS! ;)

    That said, I definitely like this solution. It’s good to write backwards-compatible AJAX-stuff. And this is actually a much easier approach than the regular AJAX approach. Only downside is the (current?) lack of nice effects ;)

  11. peculiar Says:

    There is no apostrophe in “The basics”. It’s a plural “s”. Please fix the headline, it’s making me sick. Thanks.

  12. IpNextGen Says:

    Hi, what about ajax memory leak? still present with this?

  13. Lon Says:

    That’s just not true…

    XmlHttpRequest has been in IE since version 5.0. It is a safe (or whatever) control that will not confront the visitor with any warning if the browser is configured normally.

    You can call IE6 an old browser, but IE has had the XmlHttpRequest object now for 5 years or so! Where ‘newer’ browsers have just started supporting it.

  14. Luke Says:

    Interesting and all, but:

  15. Buri’s blog » Ajax & PHP without using the XmlHttpRequest Object Says:

    […] […]

  16. HeroreV Says:

    “This content came from our Ajax Engine, without having to use any JS!”

    Without any JS? Interesting. I guess JS must not stand for JavaScript.

  17. Tomas Varaneckas Says:

    It’s not AJAX anymore then, sounds more like AJAP (Asynchronious Javascript And PHP) :)

  18. Joe Says:

    This is awesome! WAY better than xmlhttprequest.

    Thats always bugged me about current ajax architectures - security and usability of the site.

    well done!

  19. dizz Says:

    Too bad that you can not POST back information :(

  20. David Says:

    This is a fantastic discovery!

    Any chance of posting your source code as a zip for download?

    excellent work :-)

  21. hyle Says:

    good work, sounds really interesting… how about performances?

  22. l.m.orchard Says:

    Another method to consider versus this and using the XmlHttpRequest object, is a hidden iframe. With one or more of those, you can trigger request from a pool of them, and get both fresh JavaScript code from the server, as well as browser-DOM-parsed HTML data that the JS can copy/inject over into the parent page.

  23. Scott Says:

    Ajax is not new technology, essentially it is nothing more than an evolution (xmlHttpRequest being the new bit) of old DHTML IE4+ NS4+ web technology. The concept described above has been around for eons, under it’s old names of ‘Dynamic HTML’ and ‘JavaScript Remote Scripting’.

  24. Budda Magoo Says:

    You forgot to mention that Microsoft actually invented AJAX. Maybe they should have kept that one a secret, because now it’s coming back around to bite them in the tail!

  25. Dennis Pallett Says:

    Hi all,

    Thanks for the many great comments and possitive feedback. I’m really happy with it. Just to address a few issues:

    “You mention a warning,… WHAT warning? IE6 only shows a warning if you are running the Site Localy, but as long as its on a distant domain, there are no problems!”

    Actually, this depends on your security settings. I’ve got my ActiveX settings on ‘Prompt’, which means I must click ‘yes’ before any Ajax works. If I don’t allow it, Ajax doesn’t work at all, and my method does still work (no ActiveX). If you have ActiveX completely disabled, you won’t even get a prompt, but the Ajax simply doesn’t work.

    If the XmlHttpRequest object was built in natively (like it will be in IE 7), there wouldn’t be any problem. My method is simple another way of doing it, which does work fine IE6.

    “Microsoft invented AJAX, and has been offering Web-based apps since ‘98. Unfashionable, I know, to credit them with anything, but there you go.”

    I knew I was going to get called on this. I know that Microsoft invented it, and has been using it for years, but until recently, they didn’t really pay much attention to it, nor did anyone else for that matter. Only since GMail has Ajax really been gaining ground, and now even Microsoft is fully heading for the web-based apps. Remember the leaked memo’s a few days ago?

    “Any chance of posting your source code as a zip for download?”

    No problem, I’ve uploaded them at

    “Without any JS? Interesting. I guess JS must not stand for JavaScript.”

    What I meant was that the ‘content’ page didn’t have to use JS itself, unlike example 1 where the content page had to set the innerHTML of the content div. In the second example this is actually done by ‘getfile.php’, and the content page doesn’t have to do anything special.

    To those asking about performances and memory leaks; unfortunately I haven’t done any real testing, or ran any benchmarks, so I haven’t got any data. Maybe someone else would like to do that? (I’m not so good at that).

    Keep up the great comments and feedback!

  26. Jason Says:

    This isn’t really remote scripting, either. It’s more a server-side include through javascript. There’s also nothing dynamic about it.

  27. Hans Says:

    Isn’t the benefit of using AJAX is the ability to access the states of which the called page is in? Without this, and if the called page is a long query, the user will have no idea what is going on. Am I missing something?

  28. Advanced Says:

    This article is trash. Gmail, Google Local, OWA, flickr, et. al. all work fine in IE 6. MS invented Ajax, but google made it sexy.

  29. Peter Says:

    You should really just call this article “Ajax with the x” as there is nothing that forces this solution to be PHP specific.

  30. Ryan Smith Says:

    This is an interesting use of DHTML to create some AJAXy Type effects, but it doesn’t really address some of the issues that the does XmlHttpRequest object does. Still, I think this is a very nice article.

  31. Joe Says:

    This is not Ajax. First of all, there’s nothing “Asynchronous” about it, which is what the A in Ajax stands for. Second, you can only do GET-style requests with this approach. If you have data that you want to pass back to the server, you can’t perform a POST operation.

  32. CodeWhorrior Says:

    Would this work with a periodic, polling style update? So you add the script tag and it loads the file. When you remove the script tag do you have any guarantees that the file will unload? If not, there’s your memory leak.

    Also, it’s not capable of doing a post request for large data.

  33. Out of Hanwell Says:

    A New Ajax?

    This morning Ajax Blog had a link to an article entitled Ajax & PHP without using the XmlHttpRequest Object. The article simply describes a means of downloading JavaScript code (generated by PHP) to modify your webpage. I have no problem with this …

  34. dotvoid Says:

    The technique described above have for a long time been called remote scripting and now people argue if it is ajax or not. It doesn’t really matter as the ajax word is used in so many weird ways now. The js inclusion technique is good for certain things, especially including modules/extensions in javascript libraries and frameworks. I have even used in a content management system for almost four years and have had very little problems apart from browser and proxy caching that needs to be handled.

    However, the XmlHttpRequest is a lot better suited for client server communication in web applications and I am converting my applications from the js inclusion technique to the XHR technique except in js libraries where static js functionality is loaded runtime. You should use POST where changes are made serverside. With XHR you also have much better error handling. If problems occur with the js inclusion technique you can get really weird errors as they are really hard to catch in the client.

    As a side note I wrote an article on this technique in 2002. (This article explains it better though as I skipped explaining the server part.)

    The most wellknown old school remote scripting solution though should also be mentioned:

  35. zajako Says:

    Yeah, that isnt AJAX, thats just using javascript to use a div tag over an iframe.

    Ajax’s usage is not meant to be loading a page in the middle of a page or anything like that the true purpose and benifit of AJAX is running serverside processes to update a page without reload. A perfectly good example woudl be a messenger script of sorts that uses ajax to run a query checking for new messages then updates the div tag.
    But your advice is right. AJAX technology is often used in places where it shoulnt be, and should be used as you have it here.


  36. mollusc Says:

    The fact that this technique allows cross-site scripting is cited as a virtue.
    That is a *security risk*.

  37. Sideral Says:

    Good technique, thanks.

    But I think its a little limited for one reason: The browser cache the script, which means that you cannot perform various request to the same script and get distinct results depending on the server’s state. Maybe a workaround to this problem would be to generate a unique id to every request and pass it along with the url.

  38. sid Says:

    It doesn’t seem to work via proxy…

  39. Billy Says:

    They also explain how to use an image or a stylesheet to achieve “AJAX”..

  40. Pig Pen » AJAX And PHP Without XmlHttpRequest - its an adventure Says:

    […] AJAX And PHP Without XmlHttpRequest - bookmarked. Top […]

  41. Full(o)bloG » Blog Archive » Ajax senza XmlHttpRequest Says:

    […] pare che si possa fare, ancora non ho letto l’articolo e non commento… lo pubblico solo per ricordarmi di dargli un occhio… [via] […]

  42. Paul Spencer Says:

    it IS asynchronous … adding a script tag to the page does not block the currently running script (the one that adds the tag) and the contents of the script (generated by PHP in this case) get executed when they finish loading. Your web-app would continue to be fully functional while waiting for the server side piece to create the necessary javascript.

    This technique is analogous to using XmlHttpRequest and eval’ing the responseText (which also removes the X from AJAX) rather than using the DOM object exposed through responseXML.

    The strongest argument in favour of the script technique has to do with security issues. Both AJAX and the iframe technique suffer from restrictions in browsers that are supposed to prevent cross-browser (?) scripting attacks. XmlHttpRequest will refuse to open any URL that does not come from the same domain as page. Iframes can open pages from other domains, but you cannot access their contents through the DOM … really, you can’t!

    This means that you cannot load a page from your domain and load an XML document from another domain (for instance, an earthquake feed). The standard way to resolve this is to place a small script on your server that proxies the request for you. However, this is tricky in one particular case (which happened to be mine ;)) … I have a commercial mapping service API (ala google) which exposes a geocoding and routing capability. Clients embed the API through a script tag that loads it from my server. The geocoding and routing pieces are both on my server as well. XmlHttpRequest and iframes cannot be used to contact the geocoding and routing pieces due to the security problems. The only solution I could use was the script tag injection stuff. The script tag URL points to my geocoding or routing PHP script and the result is returned as javascript rather than XML. Small change, but it works great.

    Note that I could have provided a small proxy script to my clients but that would require that they install something on their server. Note also that it doesn’t solve the problem of loading arbitrary documents (like the earthquake XML feed) because they aren’t valid javascript.

  43. 泽欧里 - Says:

    解读:Ajax without XmlHttpRequest?

      Ajax & PHP without using the XmlHttpRequest Object,这样的一个标题足够吸引我去看个究竟。然而文章本身其实倒没有太多特别的东西,简而言之是介绍了如何利用动态加载js来实现页面的无刷新�…

  44. Sri’s Blog » links for 2005-11-22 Says:

    […] PHPit - Totally PHP » Ajax & PHP without using the XmlHttpRequest Object “In this tutorial, I will show you how to use Ajax without even having to use the XmlHttpRequest object.” (tags: ajax PHP) […]

  45. The Monkey Cage » Ajax & PHP without using the XmlHttpRequest Object Says:

    […] read more | digg story   […]

  46. mck Says:

    Wow, that’s awesome, thanks for the info! This is a great script to just include from anywhere. :D

  47. His Story Says:


    有个成语叫做“才华洋溢”,是用来描述聪明的人的。我不是聪明的人,想了很久也没有想到一个成语来描述自己。在Tim Horton‘s里面坐了一下午,又在办公室坐到现在。人是好好坐着,但是…

  48. His Story » Blog Archive » 按耐不住的我和AJAX Says:

    […] 通过上面这些技术AJAX能让无态的HTTP对话成为好像桌面程序那样的有态对话。我比较笨,不是很喜欢术语太多的定义,所以一般都是靠例子来理解新生事物的。这个例子很著名,应该很多人都接触过,就是Google Map。每一次进入Google Map,我们可以注意到在移动地图的时候,整个页面是没有重新刷新的。通过内部的JavaScript,图像数据可以迅速并完整地传输。假如用老的办法来实现这样的地图的话,页面上至少需要几个方向按钮和放大缩小按钮;而每次移动或者变换地图的时候,重新刷新页面的时间就相对来说很长。具体如何实现的,其实看一个实际简单的代码教程会很有帮助。除了传统的基于XMLHttpRequest的AJAX之外,还有一种不用XMLHttpRequest的AJAX方法可以参考一下。 […]

  49. amit Says:

    I Like u r artical and also try it. It works excelent. But i have made some changes (simply i want to get dyanamic value of $html variable).
    But each time when i click Button the previous value of $ html variable lost . I want that previous value remains on same page even though i click Submit button.
    In simple words when first time i click button i get value of $html = “This Is My first Message”. But when next time i click on button
    previous value of $html variable get lost and instaed of that i get REPLACED value $html=”This is my second message”. So I want out put when i click button second time as follows :->

    This is my first message.
    This is my second message.

    Please Help me. My mail id is

  50. Eugene Says:

    I am curious…
    Dont really know much about this stuff yet but I would like to populate form fields by grabbing the data dynamically and without page refresh, like this.
    I tried this and other code and am able to get content to display but how would I go about making the results fill in a form… even just one form field, like a textarea.


  51. Andre Richardson Says:

    James, don’t be such a whiny Microsoft fanboy. MS may have invented AJAX (sort of) but they haven’t really used it for anything noteworthy or done anything worthwhile with it. The author of this article wrote: “Heck, even Microsoft has gotten wind of the Ajax buzz, and is actually moving towards web-based applications as well.” You quoted that line yourself but you assume the author doesn’t know who invented it? How much is Bill Gates paying you for that jerky knee of yours?

  52. Sangent - The Daily Ramblings » Blog Archive » Learn AJAX Says:

    […] Learn AJAX […]

  53. Logically Genius Says:

    What I dont undrestand is IF XMLHttpRequest is gona work on FireFox then whats the Fuss About ? Although I have no idea how XMLHttpRequest works or will it work on Apache + PHP on Linux web server ?

    How does a web server handel XMLHttpRequest ? what to code in PHP ?

  54. bongobongo Says:

    Thanks for a cool technique.

    Have tested this with some modifications to suit my needs.

    Works like a charm in FF, IE, NE and OP.

    Anybody out there with any experience using this from Safari browser?

  55. Jelle Says:

    @Andre Richardson: “MS may have invented AJAX (sort of) but they haven’t really used it for anything noteworthy or done anything worthwhile with it. ”
    I wouldn’t call the web-interface to Outlook/Exchange not noteworthy nor worthwhile…

  56. IT快餐 » Blog Archive » 不使用XmlHttpRequest对象也可以ajax Says:

    […] 不使用XmlHttpRequest对象可以实现ajax的效果为我们在跨浏览器的web应用开发方面提供了一种思路; 四个示例文件engine.js , page1.php , getfile.php ,page1.html 分别如下 […]

  57. drslinky1500 Says:

    I tried all three on Safari 1.0.3, none of them work.

    Maybe the newer versions work?

  58. Leandro Vieira Pinho Says:


    First, congratulations for this tutorial, it perfect.

    I´m wait to discuss a little question, that is it:

    I´m getting the content of page, but this page display content only for authorized users, accessing the page direct all occurs normally, but if I try with this metod (apresented for you) it isnt´s funciton.

    Note. I´m trying loged in the system.

    Some ideias? ;)

  59. pinanti is pinanti » Blog Archive » links for 2005-11-22 Says:

    […] Ajax & PHP without using the XmlHttpRequest Object (tags: php ajax programming webdesign javascript) […]

  60. Naveed Says:

    I am sorry to say but I dont see anything dynamic with this approach. And I also dont see any disadvantage using XMLHttpRequest. I personally like to use a javascript function connect to a PHP script on the server using an instance of XMLHttpRequest. I feel this is better… any comments?

  61. Ray Says:

    Microsoft invented AJAX???? So you are telling me that they invented JavaScript (which was developed at Netscape) and XML (wich is an open standard, not invented by Microsoft)? What are you going to tell me next? Microsoft invented sliced bread?


  62. Silver Says:

    I came up with another JS solution with a PHP backend for cross-domain XMLHttpRequests. The greatest feature is that it has the same syntax as the native objects: so you don’t have to rewrite your code.

  63. Silver Says:

    Sorry, the link:

  64. Me Says:

    I have Mac OS X and XMLHttpRequest class works fine (in default Safari build).

Leave a Reply

Article Index
  1. Introduction & Basics
  2. Getting a page's content
  3. An Example & Conclusion
About the author
Dennis Pallett is the main contributor to PHPit. He owns several websites, including ASPit and Chill2Music. He is currently still studying.