Search code examples
phpajaxxmlhttprequest

AJAX with XMLHttpRequest doesn't send data


I want to build a simple program using XMLHttpRequest to calculate the area of the triangle. I used this code for client-side;

<body>
    <form>
        <label for="txtLength">Length</label>
        <input type="text" id="txtLength" name="txtLength"><br><br>
        <label for="txtWidth">Width</label>
        <input type="text" id="txtWidth" name="txtWidth"><br><br>
        <input type="hidden" name="submitted" value="1">
        <input type="button" name="Calculate" value="Calculate" onclick="calArea();">
    </form><br><br>

    <div id="showArea">Enter Values and click Calculate.</div>

    <script type="text/javascript">
        function calArea() {
            var len = document.getElementById("txtLength").value;
            var wid = document.getElementById("txtWidth").value;
            var sub = 1;

            var xhttp = new XMLHttpRequest();

            xhttp.onreadystatechange = function () {
                if (this.readyState == 4 && this.readyState == 200) {
                    document.getElementById("showArea").innerHTML = xhttp.responseText;
                }
            };

            xhttp.open("POST", "calculate_area.php", true);
            xhttp.send(len&wid&sub);
        }

</script>
</body>

This code is for the server side.

<?php 

print_r($_POST);
if (isset($_POST['sub'])) {
    $len = $_POST['len'];
    $wid = $_POST['wid'];
    $area = (($len*$wid)/2);
    echo $area;
}   
else{
    echo "Not input detected.";
}

?>

Even tried so many codes, It doesn't send the data to server side.


Solution

  • I found the mistake. I was sending the parameters as part of the URL, but need to send them as part of the request body.

    Client-side code;

    function calArea() {
        var len = document.getElementById("txtLength").value;
        var wid = document.getElementById("txtWidth").value;
        var sub = 1;
    
        var xhttp = new XMLHttpRequest();
    
        xhttp.onreadystatechange = function () {
            if (this.readyState == 4 && this.status == 200) {
                document.getElementById("showArea").innerHTML = xhttp.responseText;
            }
        };
    
        xhttp.open("POST", "calculate_area.php", true);
        xhttp.setRequestHeader("Content-Type", "application/json");
        xhttp.send(JSON.stringify({len: len, wid: wid, sub: sub}));
    }
    

    Server-side code;

    if (isset($_POST['sub'])) {
        $len = $_POST['len'];
        $wid = $_POST['wid'];
        $area = (($len*$wid)/2);
        echo $area;
    }   
    else{
        echo "Not input detected.";
    }