简体   繁体   中英

PHP not recieveing variable from AJAX

So here is my code:

<!DOCTYPE html>
<script type="text/javascript" src="https://code.jquery.com/jquery-1.7.1.min.js"></script>
<html>
  <title>Login</title>
  <body>
    <p>Enter the name of your school bellow in full</p>
    <br>
    <input type="text" id="school_text" name="school_txt" onkeyup="check_school()">
    <p id="output_field">School does not exist</p>
    
    <script>
    var result = ("");
    var schoolEntry = document.getElementById("school_text").innerHTML;
    function check_school() {
        console.log("Checking if school exists");
        schoolEntry = document.getElementById("school_text").innerHTML;
        $.ajax({
            url: 'checkSchool.php',
            type: 'POST',
            dataType:'json',
            data: {'post_var':document.getElementById("school_text").innerHTML},
            success: function(data) {
                console.log(data);
                result = data;
            }
        });
        document.getElementById("output_field").innerHTML = (result);
    }
    </script>
  </body>
</html>

and the php script

<?php
$user_input=$_POST['post_var'];
echo json_encode($user_input."1test_string");
?>

For whatever reason, php just won't receive the variable from the ajax script. The PHP is able to send a variable to to the ajax success function, and there are no errors in the Apache logs. Could someone please tell me what i've dont wrong? I also worry that there could be an issue with apache as well.

Look you have sent Data to the PHP through jquery Ajax. But in php end you will not receive the data in POST because you have sent it through the body not through form-data, so whenever you will send data through body you will get the response in php//input

<?php
$user_input=file_get_contents("php://input");
echo json_encode($user_input["post_var"]."1test_string");
?>

please check the above code may be you will get your required answer

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