I'm building an small web app querying a database with python CGI. The logic is: HTML Form - Python CGI - SQL query - python cgi prints results.
At the moment it works, but now I'm stuck creating the forms. What I want to do is auto fill the second form according the results of the first one. Example:
First Dropdown one options: Car, Motorcycle, BUS, Train.
Second dropdown: If I chose car, sow only car options. If train, only train options...
I know how to make it with SQL ('WHERE type = 'car'') But I don't know how to fill the html form.
I'm not using any framework, just HTML, Python (instead of php) and Postgresql
1 Answer 1
You have to use ajax: when the first select changes, you have to pass the selected value to the remote python script that processes the request and returns the result to the page: at this point via javascript must populate the second select.
The data can be simple html or json formatted.
This is an example using jquery and ajax (remember to include jQuery library) :
html:
<form action="" method="post">
<select class="changeStatus" name="changeStatus">
<option value="0">Car</option>
<option value="1">Motorcycle</option>
<option value="2">BUS</option>
</select>
</form>
javascript:
<script>
$('document').ready(function(){
// change event handler
$('select.changeStatus').change(function(){
// You can access the value of your select field using the .val() method
//alert('Select field value has changed to' + $('select.changeStatus').val());
// You can perform an ajax request using the .ajax() method
$.ajax({
type: 'GET',
url: 'your_script_python.py', // This is the url that will be requested
// select value available inside your_script_python.py
data: {selectFieldValue: $('select.changeStatus').val()},
// on success: populate your second select.
success: function(html){
alert('data passed: ' + html);
},
dataType: 'html' // or json
});
});
});
</script>