0

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>
Magearlik
  • 523
  • 1
  • 6
  • 18
  • as you are setting you dataType to JSON, the callback waiting a JSON response, in the same time, you are returning a full HTML page, your ajax request will return your entire page, it's better to separate your PHP code in a separated file and return a [json encoded](http://php.net/json_encode) response – hassan Mar 28 '18 at 11:14
  • You didn't define an endpoint in the ajax request, so it will call the same url. Which will return with the same html page, if you take a look at the response variable I'm pretty sure you will see the whole html page again with the ID on it. You will have to send only the ID when $_POST['id'] is not empty and then load it to somewhere with js. – Bakayaro Mar 28 '18 at 11:16

6 Answers6

0

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'])

Roger
  • 1,693
  • 1
  • 18
  • 34
0

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>
KruPa
  • 36
  • 2
  • 10
  • 3
    give url parameter in ajax call. then check in php file that id is or not? if any problem then comment plz i give You answare. – KruPa Mar 28 '18 at 11:43
  • 2
    @magearlik Actually What You Want Output at last i Don't understood. i hope this is help You. if this is help you then vote for it. Thanks. – KruPa Mar 28 '18 at 12:15
0

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();
}
?>
Martin S.
  • 256
  • 1
  • 10
  • You don't need the URL. It defaults to the page you are on. As for encoding it properly isn't this data: {'id' : fruitValue} putting it in JSON format. – Magearlik Mar 29 '18 at 00:21
0

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;  
}
Magearlik
  • 523
  • 1
  • 6
  • 18
-1

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>
Dilip Solanki
  • 437
  • 3
  • 13
-3
<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);

?>