A part of my form is added via ajax and this is making the form not to get submitted to the database. Once the part added via ajax is removed, the form gets submitted.
I have a working code for a form until I added a part that relies on ajax for the select element to get populated, what do I do to fix this problem?
<form action="" id="treeview_form" class="wpcf7-form" method="post" enctype="multipart/form-data">
<fieldset>
<legend>Register Agency</legend>
<div class="col-one-fourth">
<label>Select Parent Agency</label>
<select name="parent_category" id="parent_category">
</select>
</div>
<div class="col-one-fourth">
<label> Agency Name</label>
<input type="text" id="agencyName" name="agencyName" <?php if (isset($agencyName)) { echo 'value="' . htmlentities($agencyName, ENT_COMPAT, 'UTF-8') . '"'; } ?>>
</div>
<div class="clearfix"></div>
<div class="text-right">
<div class="divider-single"></div>
<input type="hidden" name="action" value="newAgency" />
<button class="btn btn-primary btn-big">Register</button>
</div>
</fieldset>
</form>
<script>
$(document).ready(function(){
fill_parent_category();
fill_treeview();
function fill_treeview()
{
$.ajax({
url:"fetch.php",
dataType:"json",
success:function(data){
$('#treeview').treeview({
data:data
});
}
})
}
function fill_parent_category()
{
$.ajax({
url:'fill_parent_category.php',
success:function(data){
$('#parent_category').html(data);
}
});
}
});
</script>
fill_parent_category.php
<?php
include 'database_connection.php';
$query = "SELECT * FROM agencies ORDER BY id ASC";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = '<option value="0">Parent Category</option>';
foreach ($result as $row) {
$output .= '<option value="'.$row["id"].'">'.$row["agencyName"].'</option>';
}
echo $output;
fetch.php
<?php
include 'database_connection.php';
$parentId = 0;
$query = "SELECT id, parentId, agencyName FROM agencies";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach ($result as $row) {
$data = get_node_data($parentId, $connect);
}
echo json_encode(array_values($data));
function get_node_data($parentId, $connect) {
$query = "SELECT id, parentId, agencyName FROM agencies WHERE parentId = '".$parentId."'";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
$output = array();
foreach ($result as $row) {
$sub_array = array();
$sub_array['text'] = $row['agencyName'];
$sub_array['nodes'] = array_values(get_node_data($row['id'], $connect));
$output[] = $sub_array;
}
return $output;
}
I expected the form to get posted and submitted to the database but after clicking the submit button, the form seems to process but return the same filled interface without submitting the form values.