Ajax XMLHttpRequest Get Post Example

XMLHttpRequest object is used in javascript to implement ajax synchronous or asynchronous call to web service. This example will show you how to implement http get and post request to a web service in ajax use XMLHttpRequest. You will need to create a http web server to write response data back to the ajax client. Please refer Node JS Http Server Get Post Example to learn more.

1. XMLHttpRequest Methods And Attributes.

1.1 Methods.

  1. open( method, url, use_synchronous) : Create get or post request to web service.
  2. send(data) : Send request to http server and wait for response.
  3. getAllResponseHeaders() : Return all response http headers.
  4. getResponseHeader(header_name) : Return special http header value.
  5. setRequestHeader(header_name, header_value) : Set special http request header value.
  6. abort() : Abort current request.

1.2 Attributes.

  1. onreadystatechange : Specify the execution function when the XMLHttpRequest object’s readystate attribute is changed.
  2. readyState : Return current request state value.
  3. status : Return http status code.
  4. responseBody : Current response body data.
  5. responseText : Response tex string.
  6. responseXML : Response xml content.
  7. responseStream : Response text in stream format.

2. XMLHttpRequest Use Steps.

  1. Create a XMLHttpRequest object, different web browser use different method.
  2. Invoke open method to create a http request.
  3. Define the onreadystatechange callback function which is used to process the response when server response.
  4. Invoke send method to send request data to server.

3. XMLHttpRequest Get Post Example.

This example need a web server, we implement the web sever use Node JS. There are two js file, http_get_server.js is responsible for process http get request,  http_post_server.js is responsible for process http post request. Please refer Node JS Http Server Get Post Example for more detail.

READ :   jQuery Ancestor Descendant Selector Example

Please note, you should use below code to set response header Access-Control-Allow-Origin in server side code, otherwise you may encounter below error message.

Failed to load http://localhost:8888/http_get_server.js: No ‘Access-Control-Allow-Origin’ header is present on the requested resource. Origin ‘http://localhost:63342’ is therefore not allowed access.

resp.writeHead(200, {'Access-Control-Allow-Origin':'*'});

xml-http-request.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Ajax XMLHttpRequest Example</title>
    <script type="text/javascript" src="../lib/jquery-3.3.1.min.js"></script>

    <script type="text/javascript">
        
     var xmlHttpRequest = null;

     // Initialize xmlHttpRequest object when document is ready.
     $(document).ready(function () {
         // Define XMLHttpRequest object for Mozilla and Safari that is not IE compatible.
         if(window.XMLHttpRequest){
             xmlHttpRequest = new XMLHttpRequest();
         }else{
             // Create IE XMLHttpRequest object.
             if(window.ActiveXObject){
                 try{
                     xmlHttpRequest = new ActiveXObject("Msxml2.XMLHTTP");
                 }catch(exception)
                 {
                     try{
                         xmlHttpRequest = new ActiveXObject("Microsoft.XMLHTTP");
                     }catch(exception)
                     {
                         console.log(exception.toString());
                     }
                 }
             }
         }
     });

     // This is jQuery function entrance function.
     $(function () {
         // When click get button.
         $("#getButton").click(function () {

             // Use get method to browse a web page asynchronously ( the third parameter is true. ).
             xmlHttpRequest.open("get","http://localhost:8888/http_get_server.js", true);

             // When ajax response state is ready.
             xmlHttpRequest.onreadystatechange = function () {
                 // If response successfully.
                 if (xmlHttpRequest.readyState == 4 && xmlHttpRequest.status == 200) {
                     // Display server response data in an alert dialog.
                     alert(xmlHttpRequest.responseText);
                 }
             };

             // Send request to server.
             xmlHttpRequest.send("");
         });

         // When click post button.
         $("#postButton").click(function () {

             // Use post method to browse a web page synchronously ( the third parameter is false. ).
             xmlHttpRequest.open("post","http://localhost:8888/login", false);

             // Set below header to let post server can receive client post data.
             xmlHttpRequest.setRequestHeader("Content-Type", "application/x-www-form-urlencoded;");

             // Create post data in JSON object.
             var postDataObject = {user_name:'jerry', password:'666666'};

             //Get post data string format.
             var postDataString = JSON.stringify(postDataObject);

             // Send post data to server.
             xmlHttpRequest.send(postDataString);

             // Display server response data in an alert dialog.
             alert(xmlHttpRequest.responseText);
         })
     });

    </script>
</head>
<body>

<button id="getButton">Ajax Get Example</button>
<button id="postButton">Ajax Post Example</button>

</body>
</html>
(Visited 17 times, 2 visits today)

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.