Behseini
Behseini

Reputation: 6328

Using Ajax, jQuery and PHP in two dropdown lists

I am trying to populate second dropdown list based on first dropdown list selection using Ajax, jQuery, PHP and MySQL. The problem is the options in second dropdown list just appears in one line (all options in one line)!

I was hoping the while loop inside the results.php could handle this but it seems not. How can I fix this issue?

Here is my code:

<html>
<body>
<?php
$mysqli = new mysqli('localhost', 'root', '', 'chain');
if ($mysqli->connect_errno) 
{
die('Unable to connect!');
}
else
{
$query = 'SELECT * FROM Cars';
if ($result = $mysqli->query($query)) 
 {
 if ($result->num_rows > 0) 
    {
 ?> 
 <p>
  Select a Car
<select id="selectCar">
<option value="select">Please Select From The List</option>
    <?php       
     while($row = $result->fetch_assoc()) 
   {
   ?>       
   <option value="<?php echo $row['id']; ?>"><?php echo $row['title']; ?></option>      
  <?php         
}
  ?>
 </select>
 </p>
<select>
    <option value="select">Please Select From The List</option>
    <option id="result"></option>
    </select>
    <?php
    }
    else 
    {
        echo 'No records found!';
    }
    $result->close();
}
else 
{
    echo 'Error in query: $query. '.$mysqli->error;
}
    }
     $mysqli->close();
    ?>
    <script type="text/javascript" src="jquery.js"></script>
    <script type="text/javascript">
        $(document).ready(function()
        {
            $('#selectCar').change(function()
            {
                if($(this).val() == '') return;
                $.get(
                    'results.php',
                    { id : $(this).val() },
                    function(data)
                    {
                        $('#result').html(data);
                    }
                );
            });
        });
    </script>
      </body>
      </html>

In the PHP result I have:

<?php
 $mysqli = new mysqli('localhost', 'root', '', 'chain');
 $resultStr = '';
 $query = 'SELECT * FROM models WHERE carID='.$_GET['id'];
 if ($result = $mysqli->query($query)) 
 {
if ($result->num_rows > 0) 
{
    while($row = $result->fetch_assoc())
    {
  $resultStr.=  '<option    value="'.$row['id'].'">'.$row['model'].'</option>'; 
    }
}
else
{
 $resultStr = 'Nothing found';
}
   }
    echo $resultStr;
   ?>

Upvotes: 0

Views: 1100

Answers (2)

Aldry Wijaya
Aldry Wijaya

Reputation: 425

You should edit your script into this..

<select id="result">
  <option value="select">Please Select From The List</option>
</select>

Upvotes: 1

Stefan S
Stefan S

Reputation: 647

You are setting $('#result').html(data); in the main file.

result should be the id of the HTML select element, you used it as id for the an option element.

(You are appending the values into the option element, which doesn't create new HTML elements, but they should be inserted into the select element.)

Upvotes: 1

Related Questions