Home > Software design >  AJAX with XMLHttpRequest doesn't send data
AJAX with XMLHttpRequest doesn't send data

Time:07-23

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.

CodePudding user response:

len&wid&sub

Taking some variables and putting the Bitwise & between them is not going to give you a useful value to submit to the server.

You need to encode the data in a format that you can transmit over HTTP and which your server-side code can read.

PHP supports URL Encoded and Multipart Form Encoded data natively so pick one of those.

The URLSearchParams API will generate URL Encoded data for you.

e.g.

xhttp.send(new URLSearchParams({ len, wid, sub }));

Passing a URLSearchParams object will also let XHR automatically set the correct Content-Type request header so PHP will know what it needs to do to decode the data and populate $_POST with it.

CodePudding user response:

You need to put all the parameters into a string of the form name=value with each one separated by &. And the values should be encoded in case they contain special characters.

You also need to set the content type so this data will be parsed correctly.

So change

xhttp.send(len&wid&sub);

should be:

xhttp.setRequestHeader('Content-type', 'application/x-www-form-urlencoded');
xhttp.send(`len=${encodeURIComponent(len)}&wid=${encodeURIComponent(wid)}&sub=${encodeURIComponent(sub)}`);
  • Related