简体   繁体   中英

Why does this simple JavaScript+Ajax+php code not working?

I'm new to ajax, I am trying to send the html page data to php without reloading the current page. When I click on submit button it just blink "processing..."

html file

<!DOCTYPE html>
<head>
<script type="text/javascript">
function ajax_post(){
    var hr = new XMLHttpRequest();
    var url = "simple.php";
    var fn = document.getElementById("first_name").value;
    var ln = document.getElementById("last_name").value;
    var vars = "firstname="+fn+"&lastname="+ln;
    hr.open("POST", url, true);
    hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
    hr.onreadystatechange = function() {
        if(hr.readyState == 4 && hr.status == 200) {
            var return_data = hr.responseText;
            document.getElementById("status").innerHTML = return_data;
        }
    }
    hr.send(vars);
    document.getElementById("status").innerHTML = "processing...";
}
</script>
</head>
<body>
First Name: <input id="first_name" name="first_name" type="text">  <br><br>
Last Name: <input id="last_name" name="last_name" type="text"> <br><br>
<input name="myBtn" type="submit" value="Submit Data" onclick="ajax_post();"> <br><br>
<div id="status"></div>
</body>
</html>`

Php file

<?php 
echo 'Thank you '. $_POST['firstname'] . ' ' . $_POST['lastname'] . ', says the PHP file';
?>

Edit 1

I added alert message in onreadystatechange. It showing three alert messages 2,3,4 respectively.

alert(hr.readyState);

There are multiple things i can see:

  1. </script> a closing of the script which doesn't have any opening tag in the head.
  2. The variable vars doesn't create a query string as it is missing a ? .

So, the complete changes would be:

<head>
    <script type="text/javascript">
    function ajax_post(){
        var hr = new XMLHttpRequest();
        var url = "simple.php";
        var fn = document.getElementById("first_name").value;
        var ln = document.getElementById("last_name").value;
        var vars = "?firstname="+fn+"&lastname="+ln;
        //----------^---put this at start.
        hr.open("POST", url, true);
        hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
        hr.onreadystatechange = function() {
            if(hr.readyState == 4 && hr.status == 200) {
                var return_data = hr.responseText;
                document.getElementById("status").innerHTML = return_data;
            }
        }
        hr.send(vars);
        document.getElementById("status").innerHTML = "processing...";
    }
    </script>
</head>

Or you can send it as:

hr.send({ firstname:fn, lastname:ln }); 

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