Using Ajax in JavaScript and jQuery

Ajax is technology that allows web page to update and perform actions dynamically without completely reloading the whole page, Google instance search and Google maps is one of the most great benefit of using Ajax, only the needed part of web page is loading with each action we make.

Simple Ajax example by JavaScript:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
<script>
function createRequestObject(){
    var request_;
    var browser = navigator.appName;
    if(browser == "Microsoft Internet Explorer"){
        request_ = new ActiveXObject("Microsoft.XMLHTTP");
    }
    else{
        request_ = new XMLHttpRequest();
    }
    return request_;
}
//==============================================================================
 
var msgdiv_http = createRequestObject();
 
function msgdiv_getInfo(S1){
    t = new Date().getTime();
    URL = 'getmd5.php?c='+S1+"&t="+t;
    Obj = document.getElementById('msgdiv');
    Obj.innerHTML = '<img src="load.gif" border="0">Loading ......';
 
    msgdiv_http.open("GET", URL,true);
    msgdiv_http.onreadystatechange = msgdiv_handleInfo;
    msgdiv_http.send(null);
}
 
function msgdiv_handleInfo(){
    Obj = document.getElementById('msgdiv');
    if(msgdiv_http.readyState == 2){
        Obj.innerHTML ='<img src="load.gif" border="0">Loading ......';
    }
    if(msgdiv_http.readyState == 4){
        Obj.innerHTML = msgdiv_http.responseText;
    }
}
</script>

HTML code:
1
2
3
4
<input type="text" name="T1" size="20">
<input type="button" value="Encode String" id="B1" onclick ="msgdiv_getInfo(T1.value);">
<BR><BR>
<div id="msgdiv"></div>

the previous JavaScript code calls a php file with a string parameter to get md5 encoding string, I also add another parameter changed every time to prevent get the same cashed page every time.
if calling second page takes time then we can print a loading message or loading image to indicate for that state.
The md5 php file:
1
2
3
<?
echo md5($_GET[c]);
?>



How to make Ajax by jQuery
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<body>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
  $("#B1").click(function(){
    $("#msgdiv").load("getmd5.php?c="+T1.value);
  });
});
</script>
<input type="text" name="T1" size="20">
<input type="button" value="Encode String" id="B1">
<BR><BR>
<div id="msgdiv"></div>
</body>


If this post was good and helpful for you, Please give it Like.
    Blogger Comment
    Facebook Comment

0 comments:

Post a Comment