I was reading through the mails in the php-general mailing list and came across this mail by Rasmus about AJAX
I find a lot of this AJAX stuff a bit of a hype. Lots of people have been using similar things long before it became "AJAX". And it really isn't as complicated as a lot of people make it out to be. Here is a simple example from one of my apps. First the Javascript: function createRequestObject() { var ro; var browser = navigator.appName; if(browser == "Microsoft Internet Explorer"){ ro = new ActiveXObject("Microsoft.XMLHTTP"); }else{ ro = new XMLHttpRequest(); } return ro; } var http = createRequestObject(); function sndReq(action) { http.open('get', 'rpc.php?action='+action); http.onreadystatechange = handleResponse; http.send(null); } function handleResponse() { if(http.readyState == 4){ var response = http.responseText; var update = new Array(); if(response.indexOf('|' != -1)) { update = response.split('|'); document.getElementById(update[0]).innerHTML = update[1]; } } } This creates a request object along with a send request and handle response function. So to actually use it, you could include this js in your page. Then to make one of these backend requests you would tie it to something. Like an onclick event or a straight href like this: <a href="javascript:sndReq('foo')">[foo]</a> That means that when someone clicks on that link what actually happens is that a backend request to rpc.php?action=foo will be sent. In rpc.php you might have something like this: switch($_REQUEST['action']) { case 'foo': / do something / echo "foo|foo done"; break; ... } Now, look at handleResponse. It parses the "foo|foo done" string and splits it on the '|' and uses whatever is before the '|' as the dom element id in your page and the part after as the new innerHTML of that element. That means if you have a div tag like this in your page: <div id="foo"> </div> Once you click on that link, that will dynamically be changed to: <div id="foo"> foo done </div> That's all there is to it. Everything else is just building on top of this. Replacing my simple response "id|text" syntax with a richer XML format and makine the request much more complicated as well. Before you blindly install large "AJAX" libraries, have a go at rolling your own functionality so you know exactly how it works and you only make it as complicated as you need. Often you don't need much more than what I have shown here. Expanding this approach a bit to send multiple parameters in the request, for example, would be really simple. Something like: function sndReqArg(action,arg) { http.open('get', 'rpc.php?action='+action+'&arg='+arg); http.onreadystatechange = handleResponse; http.send(null); } And your handleResponse can easily be expanded to do much more interesting things than just replacing the contents of a div. -Rasmus
Defined tags for this entry: programming
Comments
thanks
var responseNode = http.responseXML.getElementsByTagName("response")[0];
Which will take anything below in the response XML (I just happen to use in my code) and then you can walk the child elements etc. I would also alter the way Rasum detects which object to use to establish the http connection, since there are also two types of ActiveX object for IE.
But I don't like the browser detection code , I'd rather use something like
if(window.XMLHttpRequest) {
try {
var req = new XMLHttpRequest();
} catch(e) {
var req = false;
}
} else if (window.ActiveXObject)
and so on ...
Three days of searching... ugh!
Has anyone else noticed things like this?
p
I was impressed on your article at the first eyes on that.
It helped me very much.I was finding something about AJAX everywhere on the Internet.Thank you very much.
Now I'm a java programmer only able to develop easy web component.Your article makes my eyes open.
Wish you good health
http://www.voidgate.org/~jcolson/ajax-hello-world.zip
You'll need a webserver that can run PHP. Just unzip the file into a directory that will execute the PHP and you're off.
HTH
File: pajax-2005-08-16.tar.gz
Size: 10877
Detailed description:
This class can be used to make the browser invoke actions executed on the server side without reloading the current page.
It sends what is known as AJAX requests that consist in Javascript calls that sends HTTP requests to the server encapsulate the eventual parameters of the requested actions.
The class generates Javascript code with a behavior that can be customized by the developer using event handler functions also in Javascript.
On the server side the class can handle the requests dispatching the invoked function and passing eventual parameters.
The class supports requests done using both GET and POST methods.
- Nathan
There is similar tutorial up but in my opinion much better (uses object detection not browser detection for cross browser compatibility and has better validation):
http://aleembawany.com/weblog/webdev/000051_ajax_instant_tutorial.html
Still, having standards isn't a bad thing, as long as they serve a useful purpose. I think AJAX is a good way of standardising and unifying a fairly basic mish-mash of methodologies for creating truly dynamic web pages. I'll be keeping an eye on AJAX for sure.
Thanks again, keep up the great posts on your blog, Nader
var ro;
ro = window.XMLHttpRequest ? new XMLHttpRequest() : new ActiveXObject("Microsoft.XMLHTTP");
return ro;
http.open('GET', 'process.asp?rnd=' + Math.random()*4 +'action='+action);
Works great! Take care,
Steve
header("Cache-Control: no-cache");
header("Pragma: nocache");
I think this is perhaps more in line with "official" HTTP methodology, but your fix is pretty clever!
if(response.indexOf('|' != -1))
should be
if(response.indexOf('|') != -1)
.
But personally I see the AJAX is more than a dynamic method to communicate with server. When you have a more complicated application, the "X" in AJAX will be very important, which is using XML to handle complicated client/server data exchange.
To me, overhyping and over-simplified are both not good.
THE GREATEST TUTORIAL EVER!! THANKS
It turns out that apparently Javascript expects a newline at the end of the response, otherwise responseText will not contain the response (not sure if it drops the whole response, or just the last line, I'm only sending one line) (both IE and Moz appear to require this). With the script shown, it doesn't matter, when PHP reaches the end of the script it adds a newline for you.
I added exit(); to the PHP script which is what triggered the problem. If you use _exit();_, you must print the newline yourself.
fish Mysterious as an example ?
I'm trying to parse the responseXML property of some "Microsoft.XMLHTTP" ActiveXObject after sending a request using DOM, but I find it empty (no tags). I mean, the following JavaScript code alerts an xml string for responseText but 0 (zero) for responseXML.
var xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
xmlhttp.Open("GET", myUrl, false);
xmlhttp.send();
alert(xmlhttp.responseText ); // Ok!!
alert(xmlhttp.responseXML.getElementsByTagName('*').length); // Zero :-((
Any idea why?
Thanks,
Alan.
www.imipolex.org/ajax/misc/triptych.php
When I open it with Firefox everything works fine. With IE, all the buttons work properly the first time I cilck them (i.e. the correct part of the page reloads). After the first click though, clicking on the buttons does nothing (i.e. nothing reloads).
This introduction is exactly what I was looking for. Although I'm a perl programmer, not PHP, but who cares...? The interesting part is the JavaScript-Side, all other parts are simple (more ore less).
Nice li'l piece of code. Am sure it is enough to motivate many of us to start producing our own scriptlets!
Thanks for sharing it with us.
Rishu
AJAX is here to stay and belive me most JAVA programmer working on web development would prefer to use AJAX.
SO i guess AJAX is here to stay for a long time
I can't seem to get this to work. I am trying to learn all this and I am a newbie,
The page is here
http://www.nicktoye.co.uk/Ajax/foo.html
Any ideas why it isn't working?
Can any one tell more link of AJAX...I have listen that many big organizations are going to implement AJAX now...like AceIndiGo as well... http://www.aceindigo.com
AJAX is amazing....
thank you rasmus!
// Used browser detection method suggested by Dave
function createRequestObject() {
var ro;
if (window.XMLHttpRequest) {
try {
ro = new XMLHttpRequest();
} catch(e) {
ro = false;
}
}
else if (window.ActiveXObject) {
try {
ro = new ActiveXObject("Microsoft.XMLHTTP");
} catch(e) {
ro = false;
}
}
return ro;
}
// Added check if request is busy
var http = createRequestObject();
var busy = false;
// Added array of elements to be updated, and method for populating it
var elementsToUpdate = new Array();
function addElementToUpdate(el_id) {
elementsToUpdate[elementsToUpdate.length] = el_id;
}
// Added method for updating all elements with ids that start with a given string
function updateGroup(prefix, action) {
for (var i=0; i
http://www.markusernst.ch/stuff_for_the_world/my_own_ajax.js
zumiPage is a better solution.
http://www.zumipage.com
I have implemented the example and have had not problems, however I am now playing around with a project that is located in a virtual folder outside the Inetpub folder and AJAX is not able to execute the server side function.
Does anyone know how a fix to this problem.
THANKS RASMUS!