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.

3 comments :

  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
  2. 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. psd to css

    ReplyDelete
  3. Hi I have struggleing for weeks trying to find REAL and COMPLETE information on how to use ajaxto call a server and get an answer back.

    I am use to program in perl and i find it sooooo easy... you call, you get...

    Now I am putting a program that uses html5 so some javascript... All i need to do is call my server for acertain web page built with a perl script then download that page to a local computer...

    Is there someone bright enough out there to build simple tools we can understand and use EASILY? I mean all what i have done so far does not work... why is it soooo damn complicated to fetch a file and save it locally in 2015 ????

    It should as easy as call get and save period... |Please drive me to something SIMPLE and inteligent that works.

    All the ezamples i found does not work, they do not say if i have to download and install something and they all presume i know what DOM is...

    Is there a REAL gebinner approach for this..

    Thanks

    ReplyDelete