AJAX using XMLHttpRequest Object

Bellow is a sample code that asynchronously sends a post request to a file named “test.php”. All of these happens behind the scenes using XMLHttpRequest Object.

So why use AJAX on the client-side instead of PHP? – AJAX allows web pages to be updated asynchronously by exchanging small amounts of data with the server behind the scenes. This means that it is possible to update parts of a web page, without reloading the whole page. Classic web pages, (which do not use AJAX) reloads the entire page for the content to change, which, in my opinion, is slower. So that is why I prefer AJAX for client-side processing.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
<!DOCTYPE html>
<html>
<head>
    <script>
    function cvf_load_php_response() {
        var xmlhttp;
        if (window.XMLHttpRequest) { // code for IE7+, Firefox, Chrome, Opera, Safari
            xmlhttp = new XMLHttpRequest();
        } else { // code for IE6, IE5
            xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
        }
       
        // Stores a function (or the name of a function) to be called automatically each time the readyState property changes
        xmlhttp.onreadystatechange=function() {
           
            // 0: request not initialized
            // 1: server connection established
            // 2: request received
            // 3: processing request
            // 4: request finished and response is ready
           
            // 200: "OK"
            // 404: Page not found
           
            // When readyState is 4 and status is 200, the response is ready:
            if (xmlhttp.readyState == 4 && xmlhttp.status == 200) {
                document.getElementById("cvf_div").innerHTML = xmlhttp.responseText;
            }
        }
        xmlhttp.open("POST","test.php",true);
        // To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you want to send in the send() method:
        xmlhttp.setRequestHeader("Content-type","application/x-www-form-urlencoded");
        xmlhttp.send("fname=Carlo&lname=Fontanos");
    }
   
   
    // Load the function or if you want trigger the function on button click then use onclick="cvf_load_php_response()"
    cvf_load_php_response();
    </script>
</head>
<body>
    <div id="cvf_div"></div>
</body>
</html>

What we did above is we instantiated the XMLHttpRequest (for IE7+, Firefox, Chrome, Opera, Safari) or ActiveXObject(“Microsoft.XMLHTTP”) – (for IE6, IE5) and set it into a variable xmlhttp. We then set a function onreadystatechange that will be called automatically each time the readyState property changes. If the readyState returns “4” with the status of “200”, we set the response of xmlhttp.responseText to the element where we want the response of “test.php” to be outputted.

Create a new php file “test.php” on the same folder then place this block of code:

1
2
3
4
5
6
7
<?php
// Check if post is set and not empty
if(isset($_POST['fname']) && !empty($_POST['fname'])) {
        // Generate the response
    echo 'I received this first name: ' . $_POST['fname'];
}
?>

if you want to trigger a $_GET to read contents of a document like a text file, then you don’t need to give the .send() method any parameters. There is also no need to set the setRequestHeader() for HTTP header.

1
2
xmlhttp.open("GET","test.txt",true);
xmlhttp.send();

Reference: www.w3schools.com



Do you need help with a project? or have a new project in mind that you need help with?

Contact Me