1

Ok guys, i finally managed to make it work properly ofc i had to change the code again but now it works mostly how i want.

index.php

<form role="form" method="post" action="">
<select id="products" name="products">
<?php 
    require 'bundle.php';
    $products = loadProducts();
    foreach ($products as $product) {
    echo "<option id='".$product['id']."' value='".$product['id']."' selected>".$product['name']."</option>";
}
?>
</select>
<select id="bundles" name="bundles">
</select>
</form>

Script

<script type="text/javascript">
        $(document).ready(function(){
            $("#products").change(function(){
                var pid = $("#products").val();
                $.ajax({
                    url: 'data.php',
                    method: 'post',
                    data: 'pid=' + pid
                }).done(function(bundles){
                    console.log(bundles);
                    bundles = JSON.parse(bundles);
                    $('#bundles').empty();
                    bundles.forEach(function(bundle){
                        $('#bundles').append('<option>' + bundle.name + '</option>')
                    })
                })
            })
        })
    </script>

bundle.php

<?php 
    require 'conection.php';


    if(isset($_POST['pid'])) {
        $db = new DbConnect;
        $conn = $db->connect();

        $stmt = $conn->prepare("SELECT * FROM bundles WHERE pid = " . $_POST['pid']);
        $stmt->execute();
        $bundles = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($bundles);
    }

    function loadProducts() {
        $db = new DbConnect;
        $conn = $db->connect();

        $stmt = $conn->prepare("SELECT * FROM products");
        $stmt->execute();
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $products;
    }

 ?>

Ok so this is the code that works now, but i have some issues i still need help with:

1.) atm when i load the page it gets me the last option as selected but i want to have the first option selected w/o having to make an option first as <option selected="" disabled="">Select Product</option> , i want the first option from list to be the first row from db as selected [Solved this part]

2.) how can i display the selected value in index.php because based on the values from the 2 lists i need to get a different value from a different table for example ( first list selected value is: prodname and second list selected is 7 now i need the 2 values to get a 3'rd value which is = prodname7)

Maihes
  • 31
  • 6
  • try using `WHERE prod_id = '.$_GET['id'].'..` instead of `LIKE`in your query ,also check that your query is having `id` value or not – Swati Jan 28 '20 at 16:33
  • i did try = too but that makes the bundle list not populating at all i did try lots of stuff but cant seem to figure out what and where i'm missing or is wrong – Maihes Jan 29 '20 at 02:57
  • what does `$_GET['id']` have in it ? did you try to print it ? does it contain required `id` ? – Swati Jan 29 '20 at 04:21
  • so i changed the coding a bit to get the id properly but now it seems the bundle list is not populating at all – Maihes Jan 29 '20 at 20:46

3 Answers3

1

I don't see where you are actually passing the id so the PHP can access it. I'm not a PHP guy but I think you just have to add it as a query string like below:

var prodID = $(this).val();
            if(prodID) {
                $.ajax({
                    url: "bundle.php?id="+prodID,
                    dataType: "json",
                    success:function(data) {

                        $('select[name="bundle"]').empty();
                        $.each(data, function(key, value) {
                            $('select[name="bundle"]').append('<option value="'+ key +'">'+ value +'</option>');
                        });
                    }
                });
            }else{
                $('select[name="bundle"]').empty();
            }
Kyle
  • 1,463
  • 1
  • 12
  • 18
  • Thanks for quick reply but i tried that too to add the +prodID but that still didnt help coz i still got the other values too in the bundle list – Maihes Jan 28 '20 at 15:04
  • btw i changed the code a bit to pass the id but now it seems the bundle list is not populating at all – Maihes Jan 29 '20 at 20:47
1

I just want to close this topic since the original question was related to not getting the second list populated, since i solved that problem and not getting any answers for the updated question i see no point in this topic anymore.

So i will just post the full code of the working code for a dependent drop down list if there is anyone who will want a similar code.

Index.php

<form role="form" method="post" action="">
<label for="products">Product</label>
<select id="products" name="products" class="user">
<?php 
    require 'data.php'; 
    $products = loadProducts();
    $select = ' selected';
    foreach ($products as $product) {
    echo "<option id='".$product['id']."' value='".$product['id']."'".$select.">".$product['name']."</option>";
$select = '';
}
?>
</select>
<label for="bundles">Bundle</label>
<select id="bundles" name="bundles">
</select>
<input type="submit" name="submit" id="submit"></input>
</form>

Script:

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function(){
            $("select#products").change(function(){
                var products = $("select#products option:selected").val();
                $.ajax({
                    url: 'data.php',
                    method: 'post',
                    data: 'products=' + products
                    }).done(function(bundles){
                    console.log(bundles);
                    bundles = JSON.parse(bundles);
                    $('select#bundles').empty();
                    bundles.forEach(function(bundle){
                        $('select#bundles').append('<option>' + bundle.name + '</option>')
                    });
                });
            }).change();
        });
    </script>

data.php:

<?php 
    require 'DbConnect.php';

    if(isset($_POST['products'])) {
        $db = new DbConnect;
        $conn = $db->connect();



        $stmt = $conn->prepare("SELECT * FROM bundles WHERE pid = " . $_POST['products']);
        $stmt->execute();
        $bundles = $stmt->fetchAll(PDO::FETCH_ASSOC);
        echo json_encode($bundles);
    }

    function loadProducts() {
        $db = new DbConnect;
        $conn = $db->connect();

        $stmt = $conn->prepare("SELECT * FROM products");
        $stmt->execute();
        $products = $stmt->fetchAll(PDO::FETCH_ASSOC);
        return $products;
    }

 ?>

for a DB that looks like:

products:
id,name

bundles:
id,pid,name

So this is a working code for a dependent drop down list being populated from database using php and ajax where the second list is being defined by the first selection and the the lists are loaded with the page at showing the results instantly in the drop down. I do hope it helps some ppl. Thanks to all the ppl who answered this topic and helped me to get it working properly.

Maihes
  • 31
  • 6
0

you are getting no options because your $_POST['prodid'] is always null as per your code. you can verify it by

echo $_POST['prodid']

as line 2 below php opening tag

Ways to resolve:

  1. The method POST is taken from form tag, not from ajax call. So you need to pass your jquery ajax information as formdata so that your $_POST will capture in bundle.php

How to send FormData objects with Ajax-requests in jQuery?

or

  1. Use file_get_contents and get your array

How to get body of a POST in php?

$post= json_decode(file_get_contents('php://input'), true);

echo $post['prodid']; // verify you get prodid here.

or

echo $post->prodid; // verify you get prodid here. 

either one will work

On top of all, in bundle.php You are trying to populate only one row that matches prodid.... So no options are available. On all cases, you will be getting only one row as output.

Alaksandar Jesus Gene
  • 6,523
  • 12
  • 52
  • 83
  • thanks for the reply, i changed the code a bit in a different way and now it works mostly how i want maybe if you can check the updated question and see if you can help with that i would really appreciate – Maihes Feb 01 '20 at 11:34