简体   繁体   中英

Why does PHP not receive POST data sent via AJAX?

I've seen this many times before on Stack Overflow and other websites, but none of the previous posts seem to be helping.

Assume the following HTML code:

<input maxlength="50" size="50" id="searchTxt" />

And assume the following AJAX call:

$.ajax({
    type: "POST",
    url: "tdat.php",
    data: {userresponse: $('#searchTxt').val()},
    success: function(){
        $('#searchTxt').val("")
    }
})

What should happen is that the data "userresponse" gets posted to the server, having the value of whatever is inside the input box, and then the input in the box is emptied.

Later, I have the following PHP code in tdat.php:

<?php
    if(isset($_POST['userresponse'])){
        $userResponsePHP = $_POST['userresponse'];
        switch($userResponsePHP){
            case "yes":
            echo "alert(\"hi\")";
            break;
        case "no":
            echo "alert(\"negative!\")";
            break;
        default:
            echo "alert(\"nope.\")";
            break;
        }
    }
?>

The PHP does not respond, even if the AJAX call works perfectly. PHP does not even receive the value of "userresponse". I have checked the file paths, localhost connection, adding quotes to "userresponse", and practically all other minor issues stated in other threads, but the problem persists. The AJAX call clears the value of searchTxt, thus it is a successful send. No errors are shown in the console . Why is this so?

Try the following:

$.ajax({
    type: "POST",
    url: "tdat.php",
    data: {userresponse: $('#searchTxt').val()},
    success: function(data){
        alert(data.message);
        $('#searchTxt').val("");
    }
})

php:

<?php
    header('Content-Type: application/json');
    if(isset($_POST['userresponse'])){
        $userResponsePHP = $_POST['userresponse'];
        switch($userResponsePHP){
            case "yes":
            echo json_encode(["message"=>"hi"]);
            break;
        case "no":
            echo json_encode(["message"=>"negative"]);
            break;
        default:
            echo json_encode(["message"=>"nope"]);

            break;
        }
    }
?>

Note: if the page is refreshing you aren't doing any ajax

The following code snippet works, however it's generally recommended not to use eval I'm using eval in this case because you have the JavaScript alert function on the server-side (in the PHP). What you should do is echo the text and then call the alert function on the Javascript side. However, in the interest of changing as little as possible to your code I'm leaving it as is and only making changes in the JavaScript.

2 things to make note of in this example I initialize the text box with one of your accepted values 'yes'. Of course you can change this so the ajax call is made on say a button click (wasn't sure what your use case was)

One small thing you forgot was to read in the data parameter in the success callback.

<script   src="https://code.jquery.com/jquery-2.2.3.min.js"   integrity="sha256-a23g1Nt4dtEYOj7bR+vTu7+T8VP13humZFBJNIYoEJo="   crossorigin="anonymous"></script>
<script>
$( document ).ready(function() {
   $('#searchTxt').val("yes");
       $.ajax({
           type: "POST",
           url: "tdat.php",
           data: {userresponse: $('#searchTxt').val()},
           success: function(data, textStatus, jqXHR) {
              eval(data);
              $('#searchTxt').val("")
           }
        })
    });
</script>
<input maxlength="50" size="50" id="searchTxt" />

Modify your ajax function first as follows:

$('#searchTxt').change(function(){
    $.ajax({
        type: "POST",
        url: "tdat.php",
        data: {userresponse: $('#searchTxt').val()},
        success: function(res){
            $('#searchTxt').val("");
            console.log(res);
        }
     });
 });

On the change event of searchTxt your ajax call will be executed and then check the console.

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