简体   繁体   中英

Can't print POST variable from AJAX using PHP

I am getting a list of data from a mysql database which I add to a select list. When the user chooses an option I want to get the ID from the selected item, and use it to reference the index of my results array, like this:

echo $results[$id]['fruit'];

I retrieved the data from the database using $results = $stmt->fetchAll(PDO::FETCH_UNIQUE) so each id of the select list is the primary key of the record.

So I read that I can use AJAX to get the value of the selected item and send it back as a POST variable which I can then access in PHP. However when I go to print this variable I get nothing.

if(isset($_POST['id']))
{
    $id = $_POST['id']; 
    echo $id; //prints nothing
}

Here is my code:

<html>
<head>
    <script
    src="https://code.jquery.com/jquery-3.3.1.min.js"
    integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
    crossorigin="anonymous">
    </script>
    <script>
        function listChange() {
            var recID = document.getElementById("fruits").value;
            $.ajax({
                method: 'POST',
                data: {'id' : recID},
                dataType: "json",
                success: function(response)
                {
                    console.log(response);
                }
            });
        }
    </script>   
</head>
<body>
    Fruits
    <select id="fruits" name="fruits" onchange="listChange()">
        <option value="0">Apple</option>
        <option value="1">Pear</option>
        <option value="2">Watermelon</option>
        <option value="3">Orange</option>
    </select>
    <br/><br/>
    My Fruit <input type="text" id="myfruit">
    <?php
    if(isset($_POST['id']))
    {
        $id = $_POST['id']; 
        echo $id;  //does not print however post is working if you look in firefox -> web developer -> developer toolbar -> network

        //the id will be used to reference a variable 
        //$results[$id]['fruit'] which I got 
        //from a database like this 
        //$results = $stmt->fetchAll(PDO::FETCH_UNIQUE);
        //this value will set the text field myfruit
    }
    ?>
</body>
</html>

Try use this code in HMTL.

<html>
   <head>
       <script
       src="https://code.jquery.com/jquery-3.3.1.min.js"
       integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
       crossorigin="anonymous">
       </script>
        <script>
            function listChange(obj) {
                 var recID = obj.value;
                 var recID = $("#fruits:selected").text();
                 $.ajax({
                     method: 'POST',
                     data: {'id' : recID},
                     url:'demo.php',(put url of php file and remove in this file make diffrent php file)
                     dataType: "json",
                     success: function(response)
                     {
                         console.log(response);
                     }
                 });
             }
         </script>   
     </head>
    <body>
         Fruits
         <select id="fruits" name="fruits" onchange="listChange(this)">
             <option value="0">Apple</option>
             <option value="1">Pear</option>
            <option value="2">Watermelon</option>
             <option value="3">Orange</option>
         </select>
         <br/><br/>
         My Fruit <input type="text" id="myfruit">
         <?php
         if(isset($_POST['id']))
         {
             $id = $_POST['id']; 
             echo $id;  //does not print however post is working if you look in firefox -> web developer -> developer toolbar -> network

             //the id will be used to reference a variable 
             //$results[$id]['fruit'] which I got 
             //from a database like this 
             //$results = $stmt->fetchAll(PDO::FETCH_UNIQUE);
             //this value will set the text field myfruit
         }
         ?>
    </body>
</html>

I think you may try this

$(document).ready(function(){  
    $("#fruits").change(function(){
     var fruitValue = $(this).val(); // for the value i.e 0,1,2,3
     var fruitTect = $(this).text(); // for text i.e. Apple, Pear,...
    // then now you can do ur ajax
     $.ajax({
       // Your Code For Post goes here
    });

    });
});

No need to call the onchange function in your html. Jquery will take care of the rest

Also your isset($_POST['id']) maybe isset($_POST['fruits'])

Rogers answer is right. and you miss the url parameter in your ajax call.

function listChange() {
  var fruitValue = $(this).val(); // for the value i.e 0,1,2,3
        $.ajax({
            url: '/myPhpFile.php',
            method: 'POST',
            data: {'id' : fruitValue},
            dataType: "json",
            success: function(response)
            {
                console.log(response);
            }
        });
    }

if you realy want to call it in a single file you have to place the php code in top and do an exit after the condition is fullfilled..

<?php
  if(isset($_POST['id']))
  {
    $id = $_POST['id']; 

you need to encode as ajax expect a json data

$results_array = array("Id" => $id):
$json=json_encode( $results_array );
header('Content-Type: application/json'); //tell the broswer JSON is coming
echo $json; //Just plain vanillat JSON output

do your things here an exit. Be aware that each echo "something" falsify the json data expected by the ajax call

exit();
}
?>

Ok I found a much simpler way of doing this. Just get Javascript to encode the value in the URL when the select is changed, then access it in PHP using GET.

Encoding the URL in Javascript:

<script>
        $(document).ready(function(){  
            $("#fruits").change(function(){
                 var fruitValue = $(this).val(); 
                 window.location.href="ajax.php?id=" + fruitValue;
            });
        });
</script>

Echo the value in PHP:

if(isset($_GET['id']))
{
    $id = $_GET['id']; 
    echo $id;  
}

Print data via the different file. Php return data send to another file and ajax response data print in html.

Action file

if(isset($_POST['id']))
{
     $id = $_POST['id']; 
     echo $id; //prints nothing
}

View file

function listChange() {
        var recID = document.getElementById("fruits").value;
        $.ajax({
            url: 'action.php',
            method: 'POST',
            data: {'id' : recID},
            dataType: "json",
            success: function(response)
            {
                $('#your_id').html(response);
            }
        });
    }

OR

<html>
<head>
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous">
</script>
<script>
    function listChange() {
        var recID = document.getElementById("fruits").value;
        $("#your_id").html(recID);
    }
</script>   
</head>
<body>
Fruits
<select id="fruits" name="fruits" onchange="listChange()">
    <option value="0">Apple</option>
    <option value="1">Pear</option>
    <option value="2">Watermelon</option>
    <option value="3">Orange</option>
</select>
<br/><br/>
My Fruit <input type="text" id="myfruit">
<div id="your_id"></div>
</body>
</html>
<script>
     function listChange() {
                var recID = document.getElementById("fruits").value;
                $.ajax({
                    url:'ajax.php'
                    method: 'POST',
                    data: {'id' : recID},
                    success: function(response)
                    {
                        console.log(response);
                    }
                });
            }

</script>

<?php

print_r($_POST);

?>

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