Simple Ajax Tutorial
Ajax is derived from javascript. When javascript was released, people just loved all the cool things you could do with web browser. Form validation, modal message, popups, sliding information divs, cool web tools and many more.
Still javascript was limited to web browser. You could never pass information back and fro server. You had to go for either PHP or ASP approach, via GET or POST method.
One popular approach to get ajaxy effect was to use hidden dives, iframes, to create hidden request and get the results and then using javascript, show that result. This would create some other problems which I am not touching to as it is out of scope for current topic.
Ajax attempts to remedy above said problem by letting you Javascript communicate directly with the server, using special javascript object XMLHttpRequest.
Let me tell you one thing, you might already known that Ajax stands for Asynchronous Javascript and xml.
With this approach, we have to create one XMLHttpRequest object through javascript, which will do job for us to get the results, withought letting browser know.
Here is the javascript code which creates the XMLHttpRequest.
function initxmlhttp(){
var xmlhttp ;
/*@cc_on @*/
/*@if (@_jscript_version >= 5)
try {
xmlhttp=new ActiveXObject("Msxml2.XMLHTTP")
} catch (e) {
try {
xmlhttp=new ActiveXObject("Microsoft.XMLHTTP")
} catch (E) {
xmlhttp=false
}
}
@else
xmlhttp=false
@end @*/
if ( !xmlhttp && typeof XMLHttpRequest!='undefined' ){
try{
xmlhttp = new XMLHttpRequest() ;
}
catch (e){
xmlhttp = false ;
}
}
return xmlhttp ;
}
If you look carefully to above javascript function, you can see some comments are embedded. But don’t remove them. Those are conditional compilers. Removing them will cause problem in IE browsers.
So till now, we have created the base of ajax. Now, we have to use above JS function.
Let’s code one javascript function which create XMLHttpRequest object, and will send the request to php script. Embed both these javascript function in the same form.
function GET_MD5(){
var xmlreload = initxmlhttp() ;
var str = ‘Name’;
var url = "callthis.php?str="+str;
//img_capcha
xmlreload.open( "GET", url, true ) ;
xmlreload.onreadystatechange=function() {
if (xmlreload.readyState==4){
j_string = xmlreload.responseText ;
}
}
xmlreload.send(null) ;
}
AJAX_CALL function calls initxmlhttp, and send request to callthis.php.
Now create one php script named callthis.php which contains simple php code. This script will take ‘str’ as GET variable and echos md5 value of that.
--------Callthis.php-----------
Echo md5($_REQUEST[‘str’]);
?>
--------END Callthis.php-----------
That’s it guys. Now you can do anything with simple PHP script change, and calling that file in GET_MD5 function.
Hope this code helps you. Send me your feed back at ninad.blog@gmail.com
Tuesday, August 19, 2008
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment