Jump to content

Dependable dropdownlist php/mysql/ajax


php2014

Recommended Posts

Hi all,

 

I'm trying to code a dependable dropdownlist with php/mysql/ajax.

Goal is to select one thing in the first dropdown and depending on that option (and without reloading the page) enabling the second and add the options to the second, dependant on the first.

 

This is the index :

 

 

<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/dbconnect.php');
?>
 
<script type="text/javascript" src="http://ajax.googleapis.com/
ajax/libs/jquery/1.4.2/jquery.min.js"></script>
<script type="text/javascript">

$(document).ready(function()
{
$(".country").change(function()
{
var id=$(this).val();
var dataString = 'id='+id;

$.ajax
({
type: "POST",
url: "edit_form.php",
data: dataString,
cache: false,
success: function(html)
{
$(".city").html(html);
}
});

});
});
</script>

<?php

$id_test=$_POST['selector'];
$N = count($id_test);
for($i=0; $i < $N; $i++)
{
    $result = mysqli_query($conn, "SELECT * FROM cloud where id='$id_test[$i]'");
    while($row = mysqli_fetch_array($result))
      {
          
          $id_bird = $row['id'];

?>

<div style="margin:80px">
<label>Country :</label> <select name="country" class="country">
<option selected="selected">--Select Country--</option>
<?php
$sql=mysqli_query($conn, "SELECT category.id AS cat_id, category.name, category.type, cloud.id
FROM cloud,category,link_category_cloud
WHERE link_category_cloud.cloud_id = cloud.id
AND link_category_cloud.category_id = category.id
AND cloud.id='$id_test[$i]'");
while($row=mysqli_fetch_array($sql))
{
$id_test=$row['cat_id'];
$data=$row['name'];
echo '<option value="'.$id_test.'">'.$data.'</option>';
 } ?>
</select>
<br/>
<br/>
<label>City :</label> <select name="city" class="city">
<option selected="selected">--Select City--</option>

</select>

</div>

<?php
      }
}

?>

 

And this is the edit_form.php part :

 

 

<?php
require_once($_SERVER['DOCUMENT_ROOT'].'/dbconnect.php');
$cat_id = $_GET['cat_id'];
$cloud_id = $_GET['id'];
if($_POST['id_test'])
{
$id_test=$_POST['id_test'];
$data=$_POST['data'];
$sql=mysqli_query($conn, "SELECT * FROM link_category_cloud WHERE category_id={$cat_id}");

$data=$row['cloud_id'];
$id_test=$_POST['id_test'];
echo '<option value="'.$id_test.'">'.$id_test.' '.$data.'</option>';

//}
}

?>

 

Now, it does not work. I'm not only tring to pass through ID to 'edit_form.php', but also $data and $id_test. Any idea how I can do this?

Thank you very much, all help is so appreciated!!

Link to comment
Share on other sites

Hi, thanks. Looks good. But, how can I translate it to my own code? I need to have mysql in it, the first dropdown filled from mysql and the second also filled from mysql but then based on the first dropdown. Maybe you can give me some pointers :-).

 

The problem is I have seen quite some topics about it but for myself I don't get it to work.

Edited by php2014
Link to comment
Share on other sites

I explain how to use a database in the article.  You simply need to get an array of list items from the database using normal queries and then put that array into the foreach loops in the example.  It's the same exact theory, but you're making an array of list items from the db rather than hard coding the list like my example.

Here's a quick example from a db query using the $makes from the tutorial.

$get = mysqli_query($conn, "SELECT * FROM `car_makes`");
while($row = mysqli_fetch_assoc($get))
{ $makes[] = $row['make']; } // Now $makes is an array from the DB listing.
Link to comment
Share on other sites

Ok. Well as you can see I use an array too with the selector part at the beginning. However, I dont get it to work in my code from the first post tk passthrough more then 1 variable from mysql. I also don't see this from the tutorial. What am I doing wrong :(? Problem is I saw a lot of examples but I just dont get it to work for my own purposes. Thanks!

Link to comment
Share on other sites

Try some debugging and adding an alert

 $(document).ready(function()
    {
        $(".country").change(function()
        {
            var id=$(this).val();
            var dataString = 'id='+id;
            alert(datastring);             //<-- what does this show
            $.ajax
            ({
                type: "POST",
                url: "edit_form.php",
                data: dataString,
                cache: false,
                success: function(html)
                {
                    $(".city").html(html);
                }
            });

        });
    });

and try it with

datastring = '{"id":$(this).val()}';
Edited by Barand
Link to comment
Share on other sites

 

Try some debugging and adding an alert

 $(document).ready(function()
    {
        $(".country").change(function()
        {
            var id=$(this).val();
            var dataString = 'id='+id;
            alert(datastring);             //<-- what does this show
            $.ajax
            ({
                type: "POST",
                url: "edit_form.php",
                data: dataString,
                cache: false,
                success: function(html)
                {
                    $(".city").html(html);
                }
            });

        });
    });

and try it with

datastring = '{"id":$(this).val()}';

 

Hi Barand, I used your code as follows :

$(document).ready(function()
    {
        $(".country").change(function()
        {
            var id=$(this).val();
            var datastring = '{"id":$(this).val()}';
            alert(datastring);             //<-- what does this show
            $.ajax
            ({
                type: "POST",
                url: "edit_form.php",
                data: dataString,
                cache: false,
                success: function(html)
                {
                    $(".city").html(html);
                }
            });

        });
    });

However I receive the following message :

 

{"id":$(this).val()}

 

Am I doing something wrong here?

Edited by php2014
Link to comment
Share on other sites

 

I explain how to use a database in the article.  You simply need to get an array of list items from the database using normal queries and then put that array into the foreach loops in the example.  It's the same exact theory, but you're making an array of list items from the db rather than hard coding the list like my example.

Here's a quick example from a db query using the $makes from the tutorial.

$get = mysqli_query($conn, "SELECT * FROM `car_makes`");
while($row = mysqli_fetch_assoc($get))
{ $makes[] = $row['make']; } // Now $makes is an array from the DB listing.

 

I'm really , really trying hard to make it work with your example but it just does not work. This is the first part:

 

 

 

    <script>

    $('#makes').change(function(){ //Basically saying when the first select box changes values run the function below.

    var make = $(this).val(); // Grab the value of the selection to send to the select-request.php via ajax

    $.post('select-request.php', {make:make}, function(data){ // Run a ajax request and send the var make as a post variable named "make" and return the info in the "data" var.

    $('#models').html(data); // Have jquery change the html within the second select box with the "data" we got back from the ajax request.

    });

    });

    </script>

 

<?php

 

$cloud_id=$_POST['selector'];

$N = count($cloud_id);

for($i=0; $i < $N; $i++)

{

    $result = mysqli_query($conn, "SELECT * FROM cloud where id='$cloud_id[$i]'");

    while($row = mysqli_fetch_array($result))

      {

          

?>

 

    <?php

    // An array of options for the first select box.

    $makes=mysqli_query($conn, "SELECT category.id AS cat_id, category.name, category.type, cloud.id

FROM cloud,category,link_category_cloud

WHERE link_category_cloud.cloud_id = cloud.id

AND link_category_cloud.category_id = category.id

AND cloud.id='$cloud_id[$i]'");

while($row=mysqli_fetch_array($makes))

{

     

    // Displays the posted info

    if(isset($_POST['submit']))

    { echo '<pre>'; print_r($_POST); echo '</pre>'; }

    ?>

    <form action="" method="post">

    <select id="makes" name="makes"><!-- Make sure to give the select box a id, this will make it much easier to target with jquery. -->

    // Build the options for the first select box

    <option selected="selected">--Select Country--</option>

    <?php

    foreach($makes as $m){

    

    echo '<option value="'.$m.'">'.$m.'</option>'; } }

    ?>

    </select>

    <select id="models" name="models"><!-- Make sure to give the select box a id, this will make it much easier to target with jquery. -->

    </select>

    <input type="submit" name="submit" value="Submit">

    </form>

 

<?php

 

      }

}

 

?>

 

And this is select-request.php :

 

 

 

    <?php

    error_reporting(E_ALL); //Remove this line for production, it simply will allow php to display any errors

     

    // I built arrays based on the value names in the $makes array

    $get = mysqli_query($conn, "SELECT * FROM link_category_cloud WHERE category_id={$makes}");

while($row = mysqli_fetch_assoc($get))

{ $makes[] = $row['make']; } // Now $makes is an array from the DB listing.

     

    //We check to see if the "make" post has come through before we do any processing.

    if(isset($_POST['make']))

    {

    // In my example I assign the posted make to a variable and use strtolower() to put all the text in lowercase so it will match an array above.

    $model = strtolower($_POST['make']);

    // Using a varable variable I put it into a foreach loop and just like the first select box build the options.

    // Using echo we are able to essentially send back the data.

    // Basically whatever you echo on this page will be output on the main page.

    foreach($$model as $mo){ echo '<option value="'.$mo.'">'.$mo.'</option>'; }

    }

     

     

    ?>

 

All I want is that I can select this first dropdown and fetch the data from that dropdownlist from mysql and then pass it through to the second list.

Data that needs to be passed through to the second dropdown is the cloud_id and category_id.

 

I am really at a dead end here. I don't want to ask to much but maybe you can try to make what I want or something alike and explain what is happening?

What I have now is various examples, what I appreciate BIG time, but both don't work and I do not know why or how I could combine it.

 

Thank you very much.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.