I want to create a dropdown list from database with javascript. I am trying to make a dynamic form where I can add multiple rows using "add more" button. My html form contains an input type text and a drop down list
in html
<form id="add_name" name="add_name">
<table class="table table-bordered" id="dynamic_field">
<tr>
<td>
<select class="form-control" name="nom_ar">
<?php
while ($row2 = $result2->fetch_assoc()){
echo "<option value='".$row2['nom_ar']."'>".$row2['nom_ar']." </option>";
}
?>
</select>
</td>
<td><input type="text" name="name[]" placeholder="insert name" class="form-control name_list" /></td>
<td><button type="button" name="add" id="add" class="btn btn-success">add more</button></td>
</tr>
</table>
</form>
In the javascript code I added only the input type text and I don't know how to add the dropdown list like the next code shows :
$('#add').click(function(){
i++;
$('#dynamic_field').append('<tr id="row'+i+'"><td><select class="form-control" name="nom_ar"><?php while ($row2 = $result2->fetch_assoc()){echo "<option value='".$row2['nom_ar']."'>".$row2['nom_ar']."</option>";} ?></select></td><td><input type="text" name="name[]" placeholder="Ingredient" class="form-control name_list" /></td><td><button type="button" name="remove" id="'+i+'" class="btn btn-danger btn_remove">X</button></td></tr>');
}
How can I do it? My drop down list in js is always empty. I'm struggling as I'm a beginner. where should I put the php code?
Well, this is your JS code
<script type="text/javascript">
$('#add').click(function() {
$("#dynamic_field").append("<tr></tr>");
$.post("server.php", {
object_field: "Any data",
}, function(server_data) {
$("#dynamic_field tr:last-child").html(parse_server_data(server_data));
});
});
function parse_server_data(data) {
data = JSON.parse(data);
var output_string = "<td><select>";
for (var key in data) {
var value = data[key];
output_string += "<option value=" + key + ">" + value + "</option>";
}
output_string += "</select></td>";
return output_string;
}
</script>
I intentionally segregated server-side code (server.php file) and js code. Why? You should not mix code from server-side and client-side, use power of ajax technologies. Add to server.php your code that echo's all necessary data (in your case - your fetch_assoc). Learn about MVC model https://en.wikipedia.org/wiki/Model%E2%80%93view%E2%80%93controller
I also added JSON.parse function. JSON is standard of data compression and submission, check json_encode/json_decode functions in PHP and use them
Don't use tables a lot, practice divs/spans
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.