I'm creating a form with three main fields and several additional fields. One of the main fields is select type and some of the additional fields are also select. The values for all the select fields come from the included .php files which are connected to the database. My goal is to make the additional fields show only the values related to the selection of the main select field. The way I see it is that onClick of the main select I will call a javascript function with ajax, which would send the new value to the same page and refresh the contents of the main div (with all the php included files, which will take the new parameter and show the needed values)
body
div id=container
div id=menu
div id=main
All what I know about ajax is how to send variables to the different php page and get echoed response. Can someone explain how to send/change the value of the php variable on the same page while refreshing the certain div. (or may be someone know a better solution for my problem). Thank you for your time!
Let's say your main select is like this:
<select id="main_select">
<option value="car">Cars</option>
<!-- other options -->
</select>
And you have a container which is supposed to show the details based on the selected option
<div id="details">
<!-- the details options will be added here -->
</div>
You have a PHP file which echos the details based on the selected option
<?php
$mainOption = $_POST['option'];
details($mainOption);
function details($opt)
{
if($opt == 'car')
echo '<select class="detail_select">
<option value="bmw">BMW</option>
<option value="ferrari">Ferrari</option>
<option value="porsche">Porsche</option>
</select>';
else if($opt == 'another_option')
{
echo 'other details';
}
}
?>
And your Ajax can be something like this:
$(document).ready(function () {
$('#main_select').change(function(){
$.ajax({
url: "something.php",
type: "post",
data: {option: $(this).find("option:selected").val()},
success: function(data){
//adds the echoed response to our container
$("#details").html(data);
}
});
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With