Reputation: 350
I have index.php page where i want to have two "Select" elements. However I want second "Select" element to show up after one option was selected from the first one, and the second "Select" element will always contain different options based on what was selected in the first element. Both elements are reading data from MySql database. Therefore I've created another page called script.php which will hold second element until first one was selected and using jquery .load() it will load it right next to first element. But i need to transfer value from the first element to that script.php using AJAX request so it can return second elements with specific options. When I test each part separately it works fine (ajax request is passing data to script.php, script.php is loading when #first element is selected, when i open script.php page on it's own, it's giving #second just the way it should be). But when i put all this together as it is describe bellow, I am getting #second element without any options inside of it.
Here is index.php
//this is first select element and it works fine
echo '<select id="first">';
$data = $conn->query("SHOW TABLES FROM something");
while ($row = mysqli_fetch_array($data)) {
echo '<option>' . $row[0] . '</option>';
}
echo '</select>';
// this is placeholder for second select element
<div id="placeholder"></div>
Here is script.php:
// this variable will hold selected option from ajax request
$selected = $_POST['selectedOption'];
// this is second element and it works fine when it's not called from another page
echo '<select id="second">';
$data = $conn->query("SELECT * TABLES FROM $selected");
while ($row = mysqli_fetch_array($data)) {
echo '<option>' . $row['column'] . '</option>';
}
echo '</select>';
Here is ajax.js file
$(document).ready(function(){
$(document).on("change", '#first', function(event) {
// grabbing value of first element
var selectedOption = $('#first option:selected').val();
$.ajax({
type: 'POST',
url: 'script.php',
data: "selectedOption=" + selectedOption,
cache: false
});
//calling #second element to show up (script.php) in this case
$('#placeholder').load("script.php");
});
});
Hopefully i managed to explain my problem so you can understand it. Any ideas? What am I doing wrong?
Upvotes: 0
Views: 49
Reputation: 1061
$.ajax({
type: 'POST',
url: 'script.php',
data: "selectedOption=" + selectedOption,
cache: false
success: function(result) {
$("#placeholder").html(result);
}
});
The Ajax call is asynchronous, you want to set the second select element after the data was returned.
Upvotes: 1