Friday, June 23, 2017

JavaScript: AJAX Request


Introduction

In the previous post, we have talked about the basic idea behind AJAX. Before we continue with how to create a fully functional AJAX request, we need to understand some properties and methods of the XMLHttpRequest class. At minimum, we have to worry about the following:
 
  • The property XMLHttpRequest.onreadystatechange
  • The method XMLHttpRequest.open()
  • The method XMLHttpRequest.send()
There are other properties that we will use when we need them.


The property "XMLHttpRequest.onreadystatechange"

The value of this property is set to a function. The function will handle the event that will be fired when the value of the property "XMLHttpRequest.readyState" is changed. There are 5 values that the property can have. We will come to them later when we start talking about handling response.


The method "XMLHttpRequest.open()"

The method "open()" is used to initialize the request. This method can accept 4 parameters at most, two of them is a must and the others are optional.

//The first two must be provided
XMLHttpRequest.open(requestMethod,requestedURL,userName,password);

The request method is a string. The most common values of this field are the following:
MethodWhen to use
GETUsed to retrieve data such as files
POSTThis method is used to submit data to the server. Usually it causes some changes on the state of the server.
HEADWe use this method to get the response headers only.


The method "XMLHttpRequest.send()"

This method is used to send the request. It takes one parameter which is the content that we would like to send on the body of the request. We only need to provide the body content only if we will use the method 'POST'.


AJAX Request Example 1

Suppose that the URL of our server is "https://mysite.com" and suppose that on the server we have the directory "/posts" and inside that directory we have a file named "getPost.php". The file "getPost.php" will return a post based on its ID. The ID must be provided as query string. What we will do is to build a method that has the ID of the post as parameter. The method then display the result of the response.

function getPost(id){
    //get the post that has the given id
    var query = '?id='+id;
    var url = 'https://mysite.com/posts/getPost.php';
    var xmlhttpReq = new XMLHttpRequest();
    xmlhttpReq.open('GET', url+query, true);
    xmlhttpReq.onreadystatechange = function () {
    //display response result. we will do that on the next post
    }
xmlhttpReq.send();
}

Since we are using PHP, the file "getPost.php" might have something like this:

if($SERVER['REQUEST_METHOD'] == 'GET'){
    if(isset($_GET['id'])){
        $postID = $_GET['id'];
        //get the post from the database
        //and send it back using 'echo' command.
    }
    else{
        //the id parmeter is messing
        http_response_code(422);
    }
}
else{
    //method is not GET
    http_response_code(405);
}



AJAX Request Example 2

In this example, we want to implement a basic login system. We will be using the same URL in the previous example. But this time, we will be assume that we have another file. The file will be "login.php" that is located in the main directory of the server. Usually, the request method "POST" is used in such as situation. In this example, the username and password must be sent in the Request body since we are using "POST".

function login(username,password){
    var requestBody = 'username='+username+'&password='+password;
    var url = 'https://mysite.com/login.php';
    var xmlhttpReq = new XMLHttpRequest();
    xmlhttpReq.open('POST', url, true);
    //we must set this header to send data on the body
    xmlhttpReq.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    xmlhttpReq.onreadystatechange = function (){
        //display response result. we will do that on the next post
    }
    //sending the login string with the request body
    xmlhttpReq.send(requestBody);
}

The file "login.php" might have something like this:

if($SERVER['REQUEST_METHOD'] == 'POST'){
    if(isset($_POST['username'])){
        $username = $_POST['username'];
        if(isset($_POST['password'])){
            $password = $_POST['password'];
            //check database for the login info
        }
        else{
            //password is messing
            http_response_code(422);
        }
    }
    else{
        //Username is messing
        http_response_code(422);
    }
}
else{
    //method is not POST
    http_response_code(405);
}


In the next post, we will be learning how to handle the response that the server will give back after the request.


No comments:

Post a Comment

Feel free to write any thing in your mind here 😉