We have seen how to “Get” a server resource asynchronously, now let’s see how to post data to server asynchronously without bringing user to another form or posting to its own form.

The following example is textbox for user to check if the desired user id has been used. The backend logic is being served by a PHP file "verify.php". For the purpose of showing the case, my PHP file doesn't really check against a database.

I hard coded it in such a way, if the user id is "johnny", it says the user id has been used and no longer available. If you enter anything other than "johnny" it will say the user id is available.

If you are interested in my PHP code, here you are. If you are not, you may skip it.

content of verify.php

<?php 
  $userid = trim($_POST["userid"]);
  
  if ($userid == "")                // if user id is blank
    echo "you must not leave it blank"; 
  else if ($userid == "johnny")     // if user id is "johnny" (case sensitive)
    echo "'johnny' has been used, please choose another User ID";
  else                              // if user id anything else
    echo "yeah! user id \"".$userid."\" is available, you are free to use it.d";
?>
(Try to enter "johnny" and click "check")

Below is HTML code of my simplest input form to help user check user id. When you click on the "Check" button, it calls PostData().

<form>
    <label for="userid">User ID :</label>
    <input type="text" name ="userid" id="userid" onblur="PostData()" />
    <div id="div1"></div>
    <input type="button" value ="Check" onclick="PostData()" />
</form>

Below is function PostData(). The First and Second part are same as how we did in Get data earlier. Please notice the third (3) part, there are some differences between GET and POST action to the server.

function PostData() {
    // 1. Create XHR instance - Start
    var xhr;
    if (window.XMLHttpRequest) {
        xhr = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        xhr = new ActiveXObject("Msxml2.XMLHTTP");
    }
    else {
        throw new Error("Ajax is not supported by this browser");
    }
    // 1. Create XHR instance - End
    
    // 2. Define what to do when XHR feed you the response from the server - Start
    xhr.onreadystatechange = function () {
        if (xhr.readyState === 4) {
            if (xhr.status == 200 && xhr.status < 300) {
                document.getElementById('div1').innerHTML = xhr.responseText;
            }
        }
    }
    // 2. Define what to do when XHR feed you the response from the server - Start

    var userid = document.getElementById("userid").value;

    // 3. Specify your action, location and Send to the server - Start 
    xhr.open('POST', 'http://www.ajax-tutor.com/demo/verify.php');
    xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    xhr.send("userid=" + userid);
    // 3. Specify your action, location and Send to the server - End
}

Let's look at the "open" method of XHR, xhr.open('POST','verify.php'), we use "POST" instead of "GET". This is to tell the server that this is going to be a POST request.

The second parameter in "open" method is the server resource url. That's no different from what we have seen in GET data from server.

In compared with getting data from server, we We need to add a HTTP header in our request. A header that defines what kind of data will be contained in the body of the request. The Content Type of application/x-www-form-urlencoded is for form data.

As a POST requests, the string passed to the send() method must be in the proper format (which we might think of as query stringformat) in which the names and values must be properly URI-encoded. URI encoding is also known as Percent encoding.