Ajax & PHP without using the XmlHttpRequest Object
(Page 2 out of 3)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:
// Get URL and div
if (!isset($_GET['url'])) { die(); } else { $url = $_GET['url']; }
if (!isset($_GET['el'])) { die(); } else { $el = $_GET['el']; }
// Make sure url starts with http
if (substr($url, 0, 4) != 'http') {
// Set error
echo 'alert(\'Security error; incorrect URL!\');';
die();
}
// Try and get contents
$data = @file_get_contents($url);
if ($data === false) {
// Set error
echo 'alert(\'Unable to retrieve "' . $url . '"\');';
die();
}
// Escape data
$data = str_replace("'", "\'", $data);
$data = str_replace('"', "'+String.fromCharCode(34)+'", $data);
$data = str_replace ("\r\n", '\n', $data);
$data = str_replace ("\r", '\n', $data);
$data = str_replace ("\n", '\n', $data);
?>
el = document.getElementById('');
el.innerHTML = '';
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:
// Has element been passed as object or id-string?
if (typeof(el) == 'string') {
el = document.getElementById(el);
}
// Valid el?
if (el == null) { return false; }
// Does URL begin with http?
if (url.substring(0, 4) != 'http') {
url = base_url + url;
}
// Create getfile URL
getfile_url = base_url + 'getfile.php?url=' + escape(url) + '&el=' + escape(el.id);
// Do Ajax
ajax_do (getfile_url);
return true;
}
What this function does is first check whether the element actually exists, then create the url to the getfile.php file, including the page to get the contents from and the id of the element, and then fires of the Ajax call using our previous ajax_do() function. Simply, easy and it just works! Click here to view a live demo of this in action.
November 21st, 2005 at 8:40 am
Cool! I like this way of AJAX’ing much more, then classic one! Thank you!!!!
November 22nd, 2005 at 5:47 am
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!
November 22nd, 2005 at 8:42 am
if thats ajax your on crack.
November 22nd, 2005 at 9:22 am
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!
November 22nd, 2005 at 9:27 am
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.
November 22nd, 2005 at 9:42 am
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 …
November 22nd, 2005 at 10:01 am
This is one ridiculously clever way of getting the same effect. Good job!
November 22nd, 2005 at 10:07 am
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.
November 22nd, 2005 at 10:07 am
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!!!!
November 22nd, 2005 at 10:09 am
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 ;)
November 22nd, 2005 at 10:15 am
There is no apostrophe in “The basics”. It’s a plural “s”. Please fix the headline, it’s making me sick. Thanks.
November 22nd, 2005 at 10:24 am
Hi, what about ajax memory leak? still present with this?
November 22nd, 2005 at 10:37 am
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.
November 22nd, 2005 at 10:39 am
Interesting and all, but:
http://www.angryflower.com/aposter3.jpg
November 22nd, 2005 at 10:50 am
[…] http://phpit.net/article/ajax-php-without-xmlhttprequest/ […]
November 22nd, 2005 at 11:32 am
“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.
November 22nd, 2005 at 11:49 am
It’s not AJAX anymore then, sounds more like AJAP (Asynchronious Javascript And PHP) :)
November 22nd, 2005 at 12:04 pm
This is awesome! WAY better than xmlhttprequest.
Thats always bugged me about current ajax architectures - security and usability of the site.
well done!
November 22nd, 2005 at 12:12 pm
Too bad that you can not POST back information :(
November 22nd, 2005 at 12:18 pm
This is a fantastic discovery!
Any chance of posting your source code as a zip for download?
excellent work :-)
November 22nd, 2005 at 1:32 pm
good work, sounds really interesting… how about performances?
November 22nd, 2005 at 2:19 pm
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.
November 22nd, 2005 at 2:19 pm
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’.
November 22nd, 2005 at 3:13 pm
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!
November 22nd, 2005 at 3:59 pm
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!
November 22nd, 2005 at 4:11 pm
This isn’t really remote scripting, either. It’s more a server-side include through javascript. There’s also nothing dynamic about it.
November 22nd, 2005 at 4:26 pm
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?
November 22nd, 2005 at 4:30 pm
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.
November 22nd, 2005 at 4:45 pm
You should really just call this article “Ajax with the x” as there is nothing that forces this solution to be PHP specific.
November 22nd, 2005 at 5:15 pm
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.
November 22nd, 2005 at 5:16 pm
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.
November 22nd, 2005 at 5:56 pm
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.
November 22nd, 2005 at 5:57 pm
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 …
November 22nd, 2005 at 6:28 pm
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/
November 22nd, 2005 at 6:41 pm
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-
November 22nd, 2005 at 8:29 pm
The fact that this technique allows cross-site scripting is cited as a virtue.
That is a *security risk*.
November 22nd, 2005 at 9:32 pm
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.
November 22nd, 2005 at 9:48 pm
It doesn’t seem to work via proxy…
November 22nd, 2005 at 11:52 pm
http://zingzoom.com/ajax/ajax_with_js.php
They also explain how to use an image or a stylesheet to achieve “AJAX”..
November 23rd, 2005 at 12:19 am
[…] AJAX And PHP Without XmlHttpRequest - bookmarked. Top […]
November 23rd, 2005 at 1:58 am
[…] 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] […]
November 23rd, 2005 at 6:44 pm
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.
November 23rd, 2005 at 10:30 pm
解读:Ajax without XmlHttpRequest?
Ajax & PHP without using the XmlHttpRequest Object,这样的一个标题足够吸引我去看个究竟。然而文章本身其实倒没有太多特别的东西,简而言之是介绍了如何利用动态加载js来实现页面的无刷新�…
November 24th, 2005 at 10:10 am
[…] 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) […]
November 25th, 2005 at 2:23 am
[…] read more | digg story […]
November 25th, 2005 at 3:16 am
Wow, that’s awesome, thanks for the info! This is a great script to just include from anywhere. :D
November 25th, 2005 at 4:07 am
按耐不住的我和AJAX
有个成语叫做“才华洋溢”,是用来描述聪明的人的。我不是聪明的人,想了很久也没有想到一个成语来描述自己。在Tim Horton‘s里面坐了一下午,又在办公室坐到现在。人是好好坐着,但是…
November 25th, 2005 at 4:09 am
[…] 通过上面这些技术AJAX能让无态的HTTP对话成为好像桌面程序那样的有态对话。我比较笨,不是很喜欢术语太多的定义,所以一般都是靠例子来理解新生事物的。这个例子很著名,应该很多人都接触过,就是Google Map。每一次进入Google Map,我们可以注意到在移动地图的时候,整个页面是没有重新刷新的。通过内部的JavaScript,图像数据可以迅速并完整地传输。假如用老的办法来实现这样的地图的话,页面上至少需要几个方向按钮和放大缩小按钮;而每次移动或者变换地图的时候,重新刷新页面的时间就相对来说很长。具体如何实现的,其实看一个实际简单的代码教程会很有帮助。除了传统的基于XMLHttpRequest的AJAX之外,还有一种不用XMLHttpRequest的AJAX方法可以参考一下。 […]
November 26th, 2005 at 8:24 pm
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
November 27th, 2005 at 4:24 am
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
November 27th, 2005 at 12:59 pm
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?
November 28th, 2005 at 5:07 am
[…] Learn AJAX […]
November 30th, 2005 at 10:18 am
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 ?
November 30th, 2005 at 10:19 pm
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?
December 3rd, 2005 at 11:36 am
@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…
December 4th, 2005 at 5:25 am
[…] 不使用XmlHttpRequest对象可以实现ajax的效果为我们在跨浏览器的web应用开发方面提供了一种思路; 四个示例文件engine.js , page1.php , getfile.php ,page1.html 分别如下 […]
December 9th, 2005 at 8:08 pm
I tried all three on Safari 1.0.3, none of them work.
Maybe the newer versions work?
December 12th, 2005 at 11:20 pm
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? ;)
December 15th, 2005 at 10:42 pm
[…] Ajax & PHP without using the XmlHttpRequest Object (tags: php ajax programming webdesign javascript) […]
December 16th, 2005 at 2:52 pm
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?
December 16th, 2005 at 4:38 pm
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
December 16th, 2005 at 8:24 pm
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.
December 16th, 2005 at 8:25 pm
Sorry, the link: ajaxextended.com
December 18th, 2005 at 10:55 pm
I have Mac OS X and XMLHttpRequest class works fine (in default Safari build).
December 20th, 2005 at 11:35 am
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.
December 28th, 2005 at 6:49 pm
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.
December 29th, 2005 at 9:29 pm
[…] read more | digg story […]
December 30th, 2005 at 4:21 am
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
January 1st, 2006 at 3:33 am
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.
January 3rd, 2006 at 6:34 am
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
January 9th, 2006 at 8:14 pm
The ‘A’ in AJAX stands for ‘Asynchronous’.
Sorry..but your solution is not Asynchronus.
January 14th, 2006 at 1:30 am
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.
January 25th, 2006 at 3:46 pm
Microsoft created XMLHTTPRequest — not the Ajax techniques that are commonly used today.
January 25th, 2006 at 7:36 pm
phpAjaxTags - a port to PHP of famous java tag library
January 29th, 2006 at 7:55 am
[…] 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”. […]
January 30th, 2006 at 7:01 pm
We had a problem.
This script made Asynchronious calls???
Do you test with various functions executing in the same time?
Thanks!
February 1st, 2006 at 6:52 am
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.
February 2nd, 2006 at 6:17 am
[…] 这是传统的思路,用的是最传统的XMLHttpRequest,因为这种办法我没有应用成功,后来我找到了另外一位仁兄的另一种办法,如下地址:http://phpit.net/article/ajax-php-without-xmlhttprequest […]
February 2nd, 2006 at 10:13 pm
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…
February 8th, 2006 at 10:58 am
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.
February 11th, 2006 at 11:01 pm
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?
February 12th, 2006 at 6:42 am
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…
February 12th, 2006 at 6:52 am
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.
February 12th, 2006 at 12:12 pm
very nice solution
February 14th, 2006 at 6:39 pm
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.
February 16th, 2006 at 4:05 am
Hi,
Message for critics: how about you shut up, this is remarkable… create something as good yourself!
Kind Regards,
Scoop
February 17th, 2006 at 4:13 am
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.
February 26th, 2006 at 7:11 pm
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?
February 27th, 2006 at 12:04 pm
This piece of code is SUPER.
Easy, compact, to-the-point, no hassle.
I’m gonna use this 4 sure….
THNX
February 28th, 2006 at 8:51 pm
[…] ajax Curiosidad: Ajax sin XHttpReques.t No related posts Posted in Web, Programar || 1 Views || Print This Post|| […]
March 13th, 2006 at 2:59 pm
[…] 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…” […]
March 15th, 2006 at 7:07 am
[…] 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. […]
March 20th, 2006 at 7:54 pm
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.
April 4th, 2006 at 4:07 pm
A Very intresting Way to implement AJAX. But the implementation can be done in the older browsers ussing the classic ActiveX Xhttp object.
April 5th, 2006 at 12:01 am
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)
April 10th, 2006 at 7:10 pm
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.
April 16th, 2006 at 1:44 am
[…] Всяка имплементация на AJAX има своята клиентска и сървърна част. От потребителска страна е нужена основно JavaScript поддържка в браузъра (каквато има в повечето инсталирани такива). И това всъщност е основното изискване. Останалото е технологията от сървърна страна, която може да бъде всякаква: от чист HTML, през CGIки на Perl, Python… до PHP, ASP.NET и т.н.. Попаднах на два примера за съвсем простичка реализация на AJAX без всякакви допълнителни щуротии: тук и там. Разбира се, описаните подходи са малко несериозни, макар че на много места биха свършили страхотна работа. След огъня, колелото и картофите, цивилизацията достигна до XML. И тъй като напоследък всичко е XML, логично бе заявките от браузъра да се подават до сървърното приложение (каквото и да е то) през XML, давайки възможност от страната да стои каквото и да е обработващо XML. За целта в JavaScript се появи обектът XMLHttpRequest. […]
April 18th, 2006 at 6:02 am
Who can make waiting effect? (loading image in ajax)
I cannot detect when page load done! :(
Thanks!
April 18th, 2006 at 6:50 am
Can I use:
if(el.readyState==’complete’){
//Content
}else{
//Loading image
}
April 19th, 2006 at 10:26 am
[…] http://phpit.net/article/ajax-php-without-xmlhttprequest/ […]
April 19th, 2006 at 10:33 pm
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.
April 19th, 2006 at 11:06 pm
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.
April 23rd, 2006 at 3:18 pm
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
April 24th, 2006 at 2:05 pm
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.
May 3rd, 2006 at 5:12 pm
Your method is a hack … but … where is the problem ?
It’s simple, efficient, fast and compatible … IT WORKS !
Great !
May 6th, 2006 at 10:37 pm
The scrip does not work… i copied exactly this script but on my pc i have some trouble… why?
May 10th, 2006 at 10:38 am
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.
May 10th, 2006 at 9:02 pm
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)
May 12th, 2006 at 7:08 pm
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
May 16th, 2006 at 2:00 pm
Good method, but i think this not flexible as using XMLHTTPRequest.
May 19th, 2006 at 10:05 am
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.
May 20th, 2006 at 4:21 am
[…] 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 […]
May 24th, 2006 at 9:36 am
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 ?
June 14th, 2006 at 5:28 am
[…] read more | digg story Explore posts in the same categories: coldcase […]
June 14th, 2006 at 9:34 am
How wil you deal with sessions?
June 14th, 2006 at 9:45 am
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.
June 14th, 2006 at 1:09 pm
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
June 14th, 2006 at 1:14 pm
What if i try to return lots of HTML from php.is using javascript to send data the only way to retrieve data?
June 14th, 2006 at 8:24 pm
How will i be able to POST,GET and HEAD data??
June 23rd, 2006 at 3:45 pm
Hello Sir,
Microsoft created XMLHTTPRequest — not the Ajax techniques that are commonly used today
June 23rd, 2006 at 7:31 pm
Italian Translation:
http://webdev.jacoz.net/articoli_php/ajax-e-php-senza-usare-xmlhttprequest_00079.html
Enjoy it ;)
June 29th, 2006 at 4:43 pm
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…
July 4th, 2006 at 11:23 am
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 ;)
July 12th, 2006 at 9:56 am
I’m going to jump on the AJAX bandwagon soon, however, what you describe uses javascript and PHP. Where is the XML in this?
July 16th, 2006 at 3:11 am
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/
July 21st, 2006 at 5:30 pm
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!
July 22nd, 2006 at 6:41 pm
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/
July 24th, 2006 at 11:48 am
Good.., Cool Performance.that is what Ajax compained with the PHP i feel., thanks for the code
August 2nd, 2006 at 8:02 pm
This is very nice.
Here with this AJAX,I think no more secure in if our Data has more importance
August 22nd, 2006 at 5:37 am
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 :).
August 22nd, 2006 at 5:53 am
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.
August 29th, 2006 at 12:56 am
?? 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…
September 17th, 2006 at 4:03 am
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.
September 17th, 2006 at 4:09 am
BTW, I think they also introduced the innerHTML property, which I think was a great contribution as well.
October 23rd, 2006 at 3:43 pm
In IE there is a way to tell when the new script is done loading:
http://www.phpied.com/javascript-include-ready/