ASPit - Totally ASP JSit - Totally JavaScript
Search PHPit

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

Advertisements

Ajax & PHP without using the XmlHttpRequest Object

(Page 1 out of 3)

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        
       

       
                id="contentdiv">

               

                type="button" onclick="ajax_do ('page1.php');" value="Get content" />
       

(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.

Next: Getting a page's content »



135 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:

    Nice!

    If somebody is interested in reading another article on this way of making remote requests - http://www.phpied.com/javascript-include/
    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;
    }

    with:
    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:
    http://www.angryflower.com/aposter3.jpg

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

    […] http://phpit.net/article/ajax-php-without-xmlhttprequest/ […]

  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 http://phpit.net/demo/php%20and%20ajax%20remix/demos.zip

    “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.) http://www.dotvoid.com/view.php?id=13

    The most wellknown old school remote scripting solution though should also be mentioned: http://www.ashleyit.com/rs/

  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.

    -Zaj-

  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:

    http://zingzoom.com/ajax/ajax_with_js.php

    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 del.icio.us] […]

  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. 泽欧里 - ZeaLi.net 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:

    按耐不住的我和AJAX

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

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

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

  49. amit Says:

    Hi
    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.
    Suggestions?

    Thanks,
    Eugene

  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:

    Hi,

    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?

    Ray

  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: ajaxextended.com

  64. Me Says:

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

  65. Robert Says:

    Kudos to you Dennis, for publishing such a great article, and code example.

    For those of you who don’t see anything “dynamic”, it’s because the examples given here are quite basic, and are only to demonstrate the underlying remote-scripting functionality. If you want to see something happen _dynamically_, create an input field, and use “onkeyup” on the input field, instead of onclick on the button.

    Next, setup the submit_form() function to handle the input, and send a query to a database courtesy of the form_handler.php script.

    In the form_handler, instead of outputing an error, send the request/get/post variable to a dynamic database query.

    This works like a “google suggest” app which should display matching results as you type!

    Its not about the XMLHTTPRequest, its really about Javascript / DHTML guys and gals! Learn Javascript event handling and DOM, and you’ll get a whole new perspective on this stuff.

  66. Kent Brewster Says:

    Yahoo!’s new JSON option opens up quite a few XMLHTTPRequest-free interactions; see their JSON tutorial and JavaScript developer page. Examples are trickling slowly into view; see my SpiffY!Search prototype and Dan Theurer’s Dump Your Proxy.

  67. GeekEnabled Development Notes » Ajax & PHP without using the XmlHttpRequest Object Says:

    […] read more | digg story […]

  68. anonymous Says:

    Nice tutorial.
    Actually, microsoft was the first to create ajax, it was first made as an activeX object, because they needed a way for outlook to update itself without refreshing (in the good old days), since then programmers have implemented that into javascript and thus we have ajax

  69. Syntax-Error Says:

    Well this is fine for some things. But, it doesn’t have all the features of the XHR! I think I’ll stick with “traditional” AJAX methods.

  70. Jason Jones Says:

    There is an open source, cross-browser php/javascript library, using a hidden iframe to perform database/server requests without refreshing the page, at

    http://simpletutorials.com/tutorials/jsrs/index.php

  71. Alerter Says:

    The ‘A’ in AJAX stands for ‘Asynchronous’.
    Sorry..but your solution is not Asynchronus.

  72. Rerum Varium Says:

    AJAX para integración de socios de negocios en Monografias.com

    Alivianamos la carga del servidor y mejoramos la experiencia del usuario gracias a un script asíncrono.

  73. billy Says:

    Microsoft created XMLHTTPRequest — not the Ajax techniques that are commonly used today.

  74. mb Says:

    phpAjaxTags - a port to PHP of famous java tag library

  75. Vômito Blog » phpAjaxTags Says:

    […] Eu num seio ingres, mas mesmo assim inventei de ficar lendo os comentários desse artigo sobre PHP com AJAX sem utilizar XMLHttpRequest. Estava visitando os links. Achei muita coisa interessante, mas eu acho que nada supera isso, phpAjaxTags. E esse link tava no último comentário, hehehe, tinha só 74. phpAjaxTags is a port to PHP from java tag library “AjaxTags”. […]

  76. Daniel Golgher Says:

    We had a problem.

    This script made Asynchronious calls???

    Do you test with various functions executing in the same time?

    Thanks!

  77. narayan thapa Says:

    Hi, I have just looked AJAX and this script.But what I need is, i have a page like http://www.cprforthesoul.net/price.Now on this page, number increase on every refresh and on every minute (using cron).I need this number automatically need increase without refresh in millisecond.Means if you open this page, number will increase on everymillisecond. I need this without refresh on meta tag.

    Please let me know, is this possible using AJAX,

    Thanking all of you.

  78. Kingmax Yang’s Blog Land » Blog Archive » 谈谈Ajax Says:

    […] 这是传统的思路,用的是最传统的XMLHttpRequest,因为这种办法我没有应用成功,后来我找到了另外一位仁兄的另一种办法,如下地址:http://phpit.net/article/ajax-php-without-xmlhttprequest […]

  79. Ed Purkiss Says:

    This is a nice trick, but really isn’t asynchronous and it certainly isn’t AJAX. We run large applications that stay on the same page for hours (if not days) at a time and the leakage posed by this method is inescapable. The only benefit I see here is in one-shot requests that need to violate the AJAX standard of not communicating with any source other than the original domain ( I realize that this is worthy of a flame from the security minded, but it *is* a viable workaround… ). Another profound difference is being unable to ship large blocks of data back up to the server - and segmented or decision tree requests would seem very problematic with this method.

    Narayan - this is exactly what “traditional” AJAX is for - light & quick communication that doesn’t require a full page-pull from the domain server. Very creative though, and worthy of sticking in the toolchest just in case…

  80. Geert Tjeerdsma Says:

    Rather then trying this solution out right now, does anybody has an idea if it is possible with this solution to run a dynamic script once in a while (in the “background” as in complete ajax) and then update a part of the page the user is looking at ?

    Like in this example:
    http://www.modernmethod.com/sajax/sajax-0.12/php/example_wall.php
    You don’t have to enter anything, the script will just keep checking if there is anybody else who wrote something new.

  81. Bradley Says:

    So I’m trying to do this on my site and I’ve ran into a problem. If I run exactly what he has it works fine, if my html string in the PHP file doesn’t contain line breaks it works fine, but as soon as I do something like

    It no longer works. Anyone have an idea why?

  82. Haydur Says:

    Tjeerdsma: That is very very simple. You need to use JavaScript and create a function that calls an AJAX function every x seconds/minutes whatever… if you didn’t know that already, you really need to learn some JavaScript basics before you start getting into this stuff…

  83. Haydur Says:

    To the Author:

    Enough of your MS bashing already… “older browsers like Internet Explorer 6″ do natively support this method, because as you have already been told by a million people that IE was the first browser to introduce XMLHttpRequest… albeit it calls it something else. The earlier name was only popularized because geek-lust Firefox/Mozilla called it that when they copied it from MS, and Opera and Safari (naturally) followed Mozilla in naming the same function. But thankfully for AJAX developers like myself, MS is playing nice and moving to the Mozilla given name in IE7.

    And btw, you method is neither Asynchronous nor Dynamic. And unless you can prove that it’s superior over ‘traditional’ AJAX, this nothing more than a proof of concept and not very useful.

  84. Mihir Says:

    very nice solution

  85. Dennis Pallett Says:

    Haydur:

    Internet Explorer does NOT natively support the XmlHttpRequest object, as it’s implemented as an ActiveX object. If you have ActiveX disabled or very high security settings, Ajax doesn’t work. Even the IE Team has admitted this, and that’s why XmlHttpRequest *is* implemented natively in IE 7.

    I’m aware this method isn’t asynchronous, but it is dynamic. The advantage of this method is that it’s possible to do cross-domain requests, unlike XmlHttpRequest.

  86. Scoop Says:

    Hi,

    Message for critics: how about you shut up, this is remarkable… create something as good yourself!

    Kind Regards,
    Scoop

  87. Tom Says:

    Actualy this article has nothing to do with ajax. Asynchronous activity that you state you have created does not exist. I found this out by a test page that took me less then a minute to create…

    For a live demo of what I have done go to -> 69.194.38.44/ajax%20test/

    I called 2 functions one after another that loop for a 100 iterations. Now if this was true ajax the two sets of numbers should be displayed intertwined with each other. BUT! They are not!!!

    So my conclusion is that you have discovered a way to use ‘JAX’ without the XMLHttpRequest Object. So basicaly you are dynamicaly updating the page through javascript and that is old technology.

  88. deMo Says:

    Surely a very cool way. But if my server doesn’t support fopen() what will happen? As you can see here, this method doesn’t work.
    Any suggestions? I tried to make $url without the first 4 letters (’http’), but I didn’t have success (I really don’t know how to do. It would be terrible not to be able to use this method on server with no fopen()!). Who can help me?

  89. Thim Says:

    This piece of code is SUPER.

    Easy, compact, to-the-point, no hassle.

    I’m gonna use this 4 sure….

    THNX

  90. Notas y Apuntes Says:

    […] ajax Curiosidad: Ajax sin XHttpReques.t No related posts Posted in Web, Programar || 1 Views || Print This Post|| […]

  91. Mental Wandering continues… » Blog Archive » Ajax & PHP without the XmlHttpRequest Object Says:

    […] He starts off with a pretty basic introduction and shows you how to get the data into the current page (through the use of some PHP outputting Javascript). Then, with the help of pseudo-ajax functionality, it can poll this data to present dynamic information to the user of the site…” […]

  92. Blackburn’s Bombast » phajax - PHP class to do Ajax without the XmlHttpRequest object. Says:

    […] Inspired by the article by Dennis Pallett. I threw together a static PHP class to help with Ajax - PHP development. All you have to do is write your PHP ‘view’ script to display the HTML, and your PHP ‘model’ script to process and retrieve dynamic HTML from the server. Make the Ajax calls using this class and you are ready to go. […]

  93. Thomas Says:

    an interesting way to get around XML.

    this function would work great if you want to use “AJAX” for some form asynchronous processing without much data being passed from client to server. thanks for the suggestion.

  94. Saumendra Says:

    A Very intresting Way to implement AJAX. But the implementation can be done in the older browsers ussing the classic ActiveX Xhttp object.

  95. Eric Fehrenbacher Says:

    how many newbs does it take to rewrite a script ?

    you guys are talking like this is some brand new idea. hate to break it to you but if this is impressive to you then you need to give up coding and get a job at a gas station. this technique has been around for years and there are tons of articles about this and similar ways of loading external content(hidden iframes).

    AJAX is a fad…a name for something that caught on because the name was cool. the concept and POC have been there long before ‘Jesse James Garrett’ pushed his article out that made everyone go AWWW.

    and once again this does not work in Safari(not that I use it)

  96. Joe Says:

    Mr. Fehrenbacher is suffering from a faux-superiority complex, like many experienced (and threatened) developers. His point, nonetheless is true. Ajax is a buzzword, when things like SOAP and REST architecture have been around for years. But, in all revolutions, the groundwork is laid years in advance. There are a thousand ways to do everything, and this implementation is interesting, but not necessary. Mozilla-based browsers support the XMLHttpRequest, just not using the MSFT ActiveX component. Here’s a good example: http://developer.apple.com/internet/webcontent/xmlhttpreq.html

    The point of Ajax (Asynchronous Javascript and XML) is using the Javascript to speak to a (platform/language agnostic) server-side script that returns XML that can than be consumed client-side. Your client-side code should be designed to interface with any server-side script of any language, without the knowledge of that language. That is where the true portability comes into play, and is defeated by this example since it relies on PHP, a server-side technology, to render the frontend.

    So, as someone said earlier, this is not Ajax, but….. nice job anyway.

  97. Valery’s Mlog » PHP: AJAX Says:

    […] Всяка имплементация на AJAX има своята клиентска и сървърна част. От потребителска страна е нужена основно JavaScript поддържка в браузъра (каквато има в повечето инсталирани такива). И това всъщност е основното изискване. Останалото е технологията от сървърна страна, която може да бъде всякаква: от чист HTML, през CGIки на Perl, Python… до PHP, ASP.NET и т.н.. Попаднах на два примера за съвсем простичка реализация на AJAX без всякакви допълнителни щуротии: тук и там. Разбира се, описаните подходи са малко несериозни, макар че на много места биха свършили страхотна работа. След огъня, колелото и картофите, цивилизацията достигна до XML. И тъй като напоследък всичко е XML, логично бе заявките от браузъра да се подават до сървърното приложение (каквото и да е то) през XML, давайки възможност от страната да стои каквото и да е обработващо XML. За целта в JavaScript се появи обектът XMLHttpRequest. […]

  98. john nguyen Says:

    Who can make waiting effect? (loading image in ajax)
    I cannot detect when page load done! :(
    Thanks!

  99. john nguyen Says:

    Can I use:

    if(el.readyState==’complete’){
    //Content
    }else{
    //Loading image
    }

  100. Brain Basement » Blog Archive » Curl, Ajax and sooo much fun Says:

    […] http://phpit.net/article/ajax-php-without-xmlhttprequest/ […]

  101. Sridhar Says:

    This is very cool ! Thanks for sharing. However, it is not AJAX by any stretch of imagination. AJAX refers to the asynchronous nature of XMLHttpRequest between a client and server. This technique is not asynchronous. That said, it is a neat way of dynamically updating a web page.

  102. Dennis Pallett Says:

    Indeed Sridhar, you are absolute right, and since writing this article (a good 6 months ago) I’ve learnt much more about Ajax, and this technique is hardly anything like Ajax, but still, it’s a pretty cool way of doing dynamic scripts.

  103. Le Khac Nhu Says:

    Hi jonh nguyen, you can code:

    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);
    //———————–LOADING IMAGE ———————-//
    el.innerHTML = ‘Loading…’;
    //——————————————————————//
    // Do Ajax
    ajax_do (getfile_url);

    return true;
    }

    Good luck

  104. waggy Says:

    frnz i hv to use ajax on a part of svg image. actaully i have a track and a small ball is moving on it, now i just want to refresh the position of this ball without refreshing the whole tack. the ball and track both are coded in svg. is it possible somehow using ajax or any other technology. pleaze help, i need it dearly.

  105. MaxPiano Says:

    Your method is a hack … but … where is the problem ?
    It’s simple, efficient, fast and compatible … IT WORKS !
    Great !

  106. Dany Says:

    The scrip does not work… i copied exactly this script but on my pc i have some trouble… why?

  107. Ashok Gogia Says:

    Otherwise very nice way to partially update a web page, but I am not able to propagate PHP session to the updated element. I tried by including SID in the query string of URL of ajax_get function, but that does not work. Can somebody suggest a solution.

  108. Haplo Says:

    This method is a good one, why somebody, and in the contrary of what has been told : you can do everything with this start point, POST method and dynamic changement are possible since you are loading a javascript file, so you can do every changement you want. However there is just a big difference with pure ajax : this is not asynchrnous and couldn’t be anyway. But this is a good way to do stuff that does not require asynchronous update (and most of time this is the case for AJAX examples)

  109. Amy Says:

    Not bad, If you want to see an example of XmlHttpRequest with PHP go to www.sslbridge.com. If uses samba and php to create a VPN network neighborhood via a browser

  110. Prudnikov Says:

    Good method, but i think this not flexible as using XMLHTTPRequest.

  111. golanhall Says:

    Great find!

    However it requires the imported data to be in javascript format, use of serverside scripts is almost a must.

    therefore I went exploring ways to import other data :

    // Create a XML DataIsland (requires a xml js parser to access the xml contents)
    var xsel = document.createElement(’XML’);
    xsel.id = ‘xmlObj’;
    xsel.src = url;
    document.body.appendChild (xsel);

    // Load a different StyleSheet
    var csel = document.createElement(’LINK’);
    csel.rel = ‘StyleSheet’;
    csel.type= ‘text/css’;
    csel.href = url;
    document.body.appendChild (csel);

    // Load an object element
    var osel = document.createElement(’OBJECT’);
    osel.width = ‘100%’;
    osel.height= ‘100%’;
    osel.data = url;
    document.body.appendChild (osel);

    This object example is nice to import different media types without reloading. This includes pure html pages. No more JS document.writes.

    Actually anything with a URL/SRC/HREF reference can be used to load pagecontents without a page-refresh.

  112. NC PHP Developers » Ajax php - TeenCoderz - Articles Section - [Part 1] AJAX/PHP Instant MySQL Search Says:

    […] PHPit - Totally PHP Ajax & PHP without using the XmlHttpRequest … - [ Translate this page ] http://phpit.net/article/ajax-php-without-xmlhttprequest/ [ ] … I threw together a static PHP class to help with Ajax - PHP development. …Source: phpit.net […]

  113. tolteci Says:

    Your examples are very usefull !
    … can you give an axample how to pass a variable (a selection from a dropdown box - variable selected on onchange) from the first page to the php file where to be used for a conection to a database ?

  114. COLD CASE » Blog Archive » Ajax & PHP without using the XmlHttpRequest Object Says:

    […] read more | digg story Explore posts in the same categories: coldcase […]

  115. Adnan Siddiqi Says:

    How wil you deal with sessions?

  116. Adnan Siddiqi Says:

    To the posted who said Gmail works with High securty;i tried that and it didnt load the page.As soon as i changed it back to medium.everythng worked fine because in High Security Mode,javascript is disabled.

  117. 3WaySoftware Says:

    I have beentrying to figure something out with session but have not succeeded here, each call creates a new session!

    does the same problem rise when using the xmlhttprequest?

    ps: to adnan siddigi: Why should you set your browser security to high. No fun in browsing the internet then… these days there arn’t much sites that do alot when security is set to high…

    but i might be wrong here, this is just my experience

  118. Adnan Siddiqi Says:

    What if i try to return lots of HTML from php.is using javascript to send data the only way to retrieve data?

  119. Adnan Siddiqi Says:

    How will i be able to POST,GET and HEAD data??

  120. Mohideen Says:

    Hello Sir,

    Microsoft created XMLHTTPRequest — not the Ajax techniques that are commonly used today

  121. Jacopo Nuzzi Says:

    Italian Translation:
    http://webdev.jacoz.net/articoli_php/ajax-e-php-senza-usare-xmlhttprequest_00079.html

    Enjoy it ;)

  122. CerealBoy Says:

    Damn… Just found this article, and I just finished redoing my site using traditional AJAX! Oh well, if I have enough time to redo it again I think I might use this as a base point for getting it going…

    Thanx for another great tutorial!

    Cheers…

  123. dn41year Says:

    In ur sample 2: If we want to ‘get a page content’, we have to call a ‘middle-man’ script on the server (that’s getfile.php). Does that slow down the performance?
    I’ve done this with a script that streams out an image (I’m using jpgraph library), so I have to capture the whole ‘page content’. I notice it is a little bit slower than traditional XmlHttpRequest.
    Coz we simple don’t need such a thing with XmlHttpRequest.
    Anyway, this was really cool invention ;)

  124. Matt Says:

    I’m going to jump on the AJAX bandwagon soon, however, what you describe uses javascript and PHP. Where is the XML in this?

  125. Jeff Says:

    One huge problem. Safari, ie, and opera will only accept the first call unless you make the call unique each time. This took me a loooong time to figure out. Thanks Stoyan for the link that led me there and thank you especially to the folks at phpied.com.

    The part you need is something like this:

    call += ‘?’ + Math.random(0, 1000) + ‘=’ + Math.random(0, 1000);

    if (call.substring(0, 4) != ‘http’) {
    call = base_url + call + ‘&action=’ + escape(action);
    }

    And here is the article again, just in case you want to see if there is anything else you need.
    http://www.phpied.com/javascript-include/

  126. R. Mullen Says:

    Awesome, can’t wait to test it out.

    Anyhoo, I think that AJAX *thinking* is much more important than whether or not XML is used. I spent hours on XML back in 1995, thinking it was the greatest thing since sliced bread and haven’t used it other than to play around.

    Even though folks in big companies use it, I suspect MOST php programmers don’t code XML any more than they use regular expressions: they leave it to the experts and only want to know what gets exposed to their PHP code.

    I use MySQL, and love it, but I also think there’s a use for integrating something totally free like Firebird into an application…in smaller apps, therefore, techniques like this may be more useful than XML. To me, that’s still WAMP or open source *thinking*.

    So, I appreciate this article because it focuses on asynchronicity,–i.e. the user experience, rather than being doctrinaire about the geek tools used to achieve it.

    Thank goodness the JavaScript Bible is still on the shelf!

  127. Irken SSJ4 Goku Says:

    hello, everybody. that’s a working example of ajax javascript code without XmlHttpRequest… and ready to go! (copy, paste, personalization, plug and play). it’s under development… Version 0.9.1. See at http://ajaxextended.com/

  128. Amjith PS Says:

    Good.., Cool Performance.that is what Ajax compained with the PHP i feel., thanks for the code

  129. James Says:

    This is very nice.

    Here with this AJAX,I think no more secure in if our Data has more importance

  130. Kris Zyp Says:

    I have been using this technique for remote calls in my own project for some time now (www.authenteo.com), and another big advantage of using script tags is that if your data returned from the server is JSON form and includes actual JavaScript functions, the script tag automatically does the JSON parsing and your debugger can properly debug the functions (show errors and set breakpoints).
    Of course, JSON is also becoming increasingly popular as a format for AJAx, and it also strips the x of the AJAX :).

  131. Kris Zyp Says:

    Also, one warning about script tag remote loading. If the remote call fails (because of a connection timeout or server error), there is no way to be notified of the error, whereas the XMLHttpRequest will still call the callback function on failure to notify that it failed.

  132. Dimitris Anogiatis Says:

    ?? Microsoft invented Ajax? OK you guys… if you do wanna believe so… go ahead… the way I remember things is a little bit different… and I could be wrong… but I remember Netscape launching Livescript… which actually became Javascript… Microsoft’s Answer was VBScript and JScript… as for XML it’s been brewing by the W3C a long time before Microsoft pushed it out with their MSXML controls… thing is… AJAX is another tool in our arsenal… the point is… not to get grappled by the hype… but use this to create better websites… move the internet forward… not get stuck to who made what… that’s my humble oppinion…

  133. Kris Zyp Says:

    When we say that Microsoft invented AJAX, we mean Microsoft introduced the XMLHttpRequest object, which was really key to the popularization of AJAX. Obviously this article highlights the other techniques for AJAX, but generally AJAX is based around the XMLHttpRequest as it is the most straightforward way of doing AJAX. While it is more fashionable to always criticize MS, we should be thankful for their contribution to this technology.

  134. Kris Zyp Says:

    BTW, I think they also introduced the innerHTML property, which I think was a great contribution as well.

  135. Stoyan Says:

    In IE there is a way to tell when the new script is done loading:
    http://www.phpied.com/javascript-include-ready/

Leave a Reply

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