Blog Archive

JavaScript AJAX GET and POST HTTP request example

In this tutorial we are going to learn how to make http GET request and POST request using AJAX. Ajax is a group of interrelated web development techniques used on the client-side to create asynchronous web applications. With Ajax, web applications can send data to, and retrieve data from, a server asynchronously (in the background) without interfering with the display and behavior of the existing page. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not needed (JSON is often used instead), and the requests do not need to be asynchronous.

Ajax is not a single technology, but a group of technologies. HTML and CSS can be used in combination to mark up and style information. The DOM is accessed with JavaScript to dynamically display, and to allow the user to interact with the information presented. JavaScript and the XMLHttpRequest object provide a method for exchanging data asynchronously between browser and server to avoid full page reloads.

JavaScript AJAX GET and POST HTTP request

Sample source code for Javascript AJAX GET HTTP request ajaxget.html

<html>
<head>
<title>Ajax GET HTTP Request</title>

<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript"> 
function ajaxRequest(){
     var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]; //activeX versions to check for in IE
     if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
      for (var i=0; i<activexmodes.length; i++){
       try{
        return new ActiveXObject(activexmodes[i]);
       }
       catch(e){
        //suppress error
       }
      }
     }
     else if (window.XMLHttpRequest) // if Mozilla, Safari etc
      return new XMLHttpRequest();
     else
      return false;
}

function ajaxget(){
    var mygetrequest=new ajaxRequest();
    mygetrequest.onreadystatechange=function(){
     if (mygetrequest.readyState==4){
      if (mygetrequest.status==200 || window.location.href.indexOf("http")==-1){
       document.getElementById("result").innerHTML = mygetrequest.responseText;
      }
      else{
       alert("An error has occured making the request");
      }
     }
    }
    var userId = encodeURIComponent(document.getElementById("userId").value);
    var password = encodeURIComponent(document.getElementById("password").value);
    mygetrequest.open("GET", "http://localhost:8080/AjaxTest/Login?userId="+userId+"&password="+password, true);
    mygetrequest.send(null);
}

</SCRIPT>
</head>
<body>

    <form method="get" action="">
        <table>
            <tr>
                <td>User Id:</td>
                <td><input type="text" id="userId" name="userId" size="30" />
                </td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="password" id="password" name="password"
                    size="30" />
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="button" value="submit" onClick="ajaxget()" />
                </td>
            </tr>
        </table>
    </form>

    <div id="result"></div>
</body>
</html>


JavaScript AJAX GET and POST HTTP request

Sample source code for Javascript AJAX POST HTTP request ajaxpost.html

<html>
<head>
<title>Ajax POST HTTP Request</title>
<SCRIPT TYPE="text/javascript" LANGUAGE="JavaScript"> 
function ajaxRequest(){
     var activexmodes=["Msxml2.XMLHTTP", "Microsoft.XMLHTTP"]; //activeX versions to check for in IE
     if (window.ActiveXObject){ //Test for support for ActiveXObject in IE first (as XMLHttpRequest in IE7 is broken)
      for (var i=0; i<activexmodes.length; i++){
       try{
        return new ActiveXObject(activexmodes[i]);
       }
       catch(e){
        //suppress error
       }
      }
     }
     else if (window.XMLHttpRequest) // if Mozilla, Safari etc
      return new XMLHttpRequest();
     else
      return false;
}

function ajaxpost(){
    var mypostrequest=new ajaxRequest();
    mypostrequest.onreadystatechange=function(){
     if (mypostrequest.readyState==4){
      if (mypostrequest.status==200 || window.location.href.indexOf("http")==-1){
       document.getElementById("result").innerHTML = mypostrequest.responseText;
      }
      else{
       alert("An error has occured making the request");
      }
     }
    }
   
    var userId = encodeURIComponent(document.getElementById("userId").value);
    var password = encodeURIComponent(document.getElementById("password").value);
    var parameters="userId="+userId+"&password="+password;
    mypostrequest.open("POST", "http://localhost:8080/AjaxTest/Login", true);
    mypostrequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    mypostrequest.send(parameters);
}

</SCRIPT>
</head>
<body>

    <form method="get" action="">
        <table>
            <tr>
                <td>User Id:</td>
                <td><input type="text" id="userId" name="userId" size="30" />
                </td>
            </tr>
            <tr>
                <td>Password:</td>
                <td><input type="password" id="password" name="password"
                    size="30" />
                </td>
            </tr>
            <tr>
                <td>&nbsp;</td>
                <td><input type="button" value="submit" onClick="ajaxpost()" />
                </td>
            </tr>
        </table>
    </form>

    <div id="result"></div>
</body>
</html>


JavaScript AJAX GET and POST HTTP request

Click here for Login Servlet Source code


XMLHttpRequest Object

  • Properties
    • readyState A number representing the current state of the request:
      • 0 - UNINITIALIZED
      • 1 - LOADING
      • 2 - LOADED
      • 3 - INTERACTIVE
      • 4 - COMPLETE
    • status 
      • The numeric HTTP status code returned by the web server.
    • statusText 
      • The text associated with the above HTTP status code. For example, 200 means "OK" and 404 means "Not found".
    • responseText 
      • A string containing the response data returned from the web server.
    • responseXML 
      • If the web server returns an XML document, this will be a DOM document object representing the parsed XML.
  • Methods
    • open(method, url, asynch, username, password) 
      • Initializes a new request. method is the HTTP request verb, usually "GET" or "POST". The last three options are optional: asynch defaults to true, username and password may be specified if the web server requires authentication.
    • setRequestHeader(name, value) 
      • Sets a the named request header.
    • send(data) 
      • Makes the request. optionally passing data.
    • abort() 
      • Aborts an active request.
    • getResponseHeader(name) 
      • Returns the value of the named response header.
    • getAllResponseHeaders() 
      • Returns a string containg all the response headers.
  • Events
    • onreadystatechange 
      • Raised anytime the readystate property changes.

1 comment :

  1. Hey, execuse me, I searched you're blog by the keywords "AJAX HTTP GET POST".

    I want to know how the AJAX operator, and I want to write a sample code by JavaScript.

    But, I also known the AJAX must be arrange in pairs with a web server (boa, goahead, etc.).

    So, is this sample code need collocated any source code on the web server??

    Thank a lot!!

    PS:
    1. I mean that I only enable a HTTP service (like Apache), but I don't do any thing on that.
    2. Sorry, my English was so pool, I hope you could understand what I said.

    ReplyDelete