简体   繁体   中英

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.

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)}`);
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.

eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM