AJAX XHR Request Example to PHP at Server Side

AJAX XHR Request Example to PHP at Server Side

Last Updated on July 27, 2023 by Subhash Jain

AJAX stand for Asynchronous JavaScript and XML. AJAX uses XHR object to send data to the server and uses JS and HTML DOM to display data. AJAX is the example of synergy between JS and HTML DOM.

XHR is the short form for XMLHttpRequest. All modern browsers have in-built XMLHttpRequest object to communicate between the client side and server side without page load. XHR object can be used in these useful scenarios:-

  • Submit the form without page re-load
  • After page-load, request data from server
  • After page-load, receive data from server
  • Sending data to server in the background

Live Username Availability Check with XHR (Client Side ) and PHP (Server Side) By POST

I am going to explain an example when we need to check at server side if the username already exists in DB or not. I will be displaying it with the code and live demo example. We are using AJAX method by using XMLHttpRequest XHR object to send request at server end by POST method. The server will return the data in JSON format. We will fetch the data from server without page reload and display the result on the screen if the “username exists” or “username does not exist”.

Part I: HTML Form & XHR Object Request by POST

Step 1: change event is fired/triggered in JS when the value of <input>, <select>, and <textarea> gets changed. On change event, we call function checkUsername(). We assume that these username already exists in DB: 'ram', 'manohar', 'tom', 'rakesh', 'ajay'. If username exists. We add bootstrap class text-danger to show alert and set value of username input field to blank.

<input type="text" name="username" id="username" value="" class="form-control"
         onchange="checkUsername()" />
        <span id="myuname"> </span>

Step 2: We use POST method to send XHR object request to server. Please note GET & POST – both can be used to send the request but both behaves differently. I would like to mention that we have used JS function serialize to serialize form data when we send via POST.

// JS script to serialize form data when we send via POST
    <script src = 'serialize-0.2.js'> </script>

    <script>

    ////////////////////////////////////  BOF JS  //////////////////////////////////////////////
function checkUsername(){

// Let us create a new XMLHttpRequest object
 xhr = new XMLHttpRequest();

//  Let us specify the type of request that we send tp server
xhr.open('POST', 'username-post-method-response.php', true);

        // Send the proper header information along with the request
        xhr.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');

// Send request with serialized form data
   params = serialize(myform);
console.log(params);
xhr.send(params);

        // Callback function is executed after the response from server is over
    xhr.onload = function() {
// Check if HTTP response tatus is 200 and browser has got response from server
if (xhr.status != 200 && xhr.readyState == 4 ) {

// If POST URL is not found then 404: Not Found error
console.log(`Error ${xhr.status}: ${xhr.statusText}`); 

// Display server response 
} else { 
rdata = JSON.parse(this.responseText);
console.log(`Done, got ${xhr.response.length} bytes`); 
document.getElementById("myuname").innerHTML = rdata.msg;
if(rdata.success == false){
// username does not exist
document.getElementById("myuname").className = 'text-success';

}
else
{
                    // username exists. We add bootstrap class text-danger to show alert and set value of username input field to blank.
document.getElementById("myuname").className = 'text-danger';
document.getElementById("username").value = '';
}
//alert(rdata.success);
}
};

// event e
xhr.onprogress = function(event) {
if (event.lengthComputable) {
console.log(`Got ${event.loaded} of ${event.total} bytes`);
} else {
// If no Content-Length 
console.log(`Got ${event.loaded} bytes`); 
}

};

xhr.onerror = function() 
{
alert("Request failed");
};
}
////////////////////////////////////  EOF JS  //////////////////////////////////////////////
    

    </script>

Part II: Server Response via PHP Script

We assume that you get your result form MySQL Query in array format. Let us pre-define array to explain here with the example code as given below.

////////////////////////////////////  BOF PHP  //////////////////////////////////////////////
    <?php
    $data = array();
    $usernames = array('ram', 'manohar', 'tom', 'rakesh', 'ajay');
    $uname = $_POST['username'];
    //$uname = 'ram';
    if(in_array($uname, $usernames))
    {
        $data['success'] = true;
        $data['msg'] = 'username exists';

    }
    else
    {

        $data['success'] = false;
        $data['msg'] = 'username does not exist';
    }
    $response_data = json_encode($data);
    echo $response_data;
    ?>
////////////////////////////////////  EOF PHP  //////////////////////////////////////////////
    

    </script>

Live Username Availability Check with XHR (Client Side ) and PHP (Server Side) By GET

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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