How to fix 'Form Not Submitting' in PHP - php

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.

Related

Semantic-UI Multiple selection with PHP

I want to use JS library "Semantic-UI" with my PHP code
I want to replace the ordinary select boxes with "Semantic-UI Multiple selection Dropdown"
The original PHP Code that generates the Select items:
<div class="list-group">
<h3>Material</h3>
<?php
$query = "SELECT DISTINCT(product_gender) FROM product";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
?>
<div class="list-group-item checkbox">
<label><input type="checkbox" class="common_selector gender" value="<?php echo $row['product_gender']; ?>" > <?php echo $row['product_gender']; ?></label>
</div>
<?php
}
?>
</div>
I want to replace input with Semantic-UI :
<div class="list-group">
<h3>Gender</h3>
<select multiple="" class="label ui selection fluid dropdown">
<?php
$query = "SELECT DISTINCT(product_gender) FROM product";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
foreach($result as $row)
{
?>
<div class="list-group-item checkbox">
<option name='gender' class="common_selector gender" value="<?php echo $row['product_gender']; ?>"><?php echo $row['product_gender']; ?></option>
</div>
<?php
}
?>
</select>
</div>
It gathers the options, But didn't post data, since the function that posts data is :
<script>
$(document).ready(function(){
filter_data();
function filter_data()
{
$('.filter_data').html('<div id="loading" style="" ></div>');
var action = 'fetch_data';
var es2 = get_filter('es2');
var bw2 = get_filter('bw2');
var tl = get_filter('tl');
var b2 = get_filter('b2');
var gender = get_filter('gender');
var material = get_filter('material');
var hinge = get_filter('hinge');
$.ajax({
url:"fetch_data.php",
method:"POST",
data:{action:action, es2:es2, bw2:bw2, tl:tl, b2:b2, gender:gender, material:material, hinge:hinge},
success:function(data){
$('.filter_data').html(data);
}
});
}
function get_filter(class_name)
{
var filter = [];
$('.'+class_name+':checked').each(function(){
filter.push($(this).val());
});
return filter;
}
$('.common_selector').click(function(){
filter_data();
});
});
And we get Data by this :
if(isset($_POST["gender"]))
{
$gender_filter = implode("','", $_POST["gender"]);
$query .= "
AND product_gender IN('".$gender_filter."')
";
}
if(isset($_POST["material"]))
{
So please how can I merge Semantic-UI with my code ?

How to populate dropdown field pre-selected with the existing data from another MySQL table?

In my database I have 2 tables:
To insert data, I have a form that populates dropdown options from the table formulation. This is what the insert form for formulation dropdown looks like:
<?php
$formulation = '';
$query = "SELECT * FROM formulation";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
$formulation .= '<option value="' . $row["formulationID"] . '">' . $row["formulation_name"] . '</option>';
}
?>
<select>
<option value="">Select formulation</option>
<?php echo $formulation; ?>
</select>
Now I am working on the ‘Update’ form. But my question is how can I populate the ‘Formulation’ field dropdown with the data from the formulation table (like as the insert form) but pre-selected with the existing formulation value for the name from the items table? Like this image below:
I am having problem with how I should build the form. How should I proceed with this form?
<?php
$output = array('data' => array());
$sql = "SELECT * FROM items";
$query = $connect->query($sql);
while ($row = $query->fetch_assoc()) {
$output['data'][] = array(
$row['name'],
);
}
echo json_encode($output);
?>
<form action=" " method="POST">
<div>
<label>Name</label>
<input type="text"><br>
<label>Formulation</label>
<select >
<!--What should be the codes here? -->
</select>
</div>
<button type = "submit">Save changes</button>
</form>
Thanks in advance for your suggestion.
Note: I'm not a user of mysqli so maybe there will be some error, but you will get the idea. This will not tackle the update part, just the populate part
Since you are editing a certain item, I will assume that you have something to get the item's itemID.
<?php
$sql = "SELECT * FROM items WHERE itemID = ?";
$query = $connect->prepare($sql);
$query->bind_param("s", $yourItemID);
$query->execute();
$result = $query->fetch_assoc();
$itemName = $result['name'];
$itemFormulation = $result['formulation_fk'];
//now you have the name and the formulation of that certain item
?>
<form action=" " method="POST">
<div>
<label>Name</label>
<input type="text" value="<?php echo $itemName; ?>"><br>
<label>Formulation</label>
<select >
<?php
$query = "SELECT * FROM formulation";
$result = mysqli_query($connect, $query);
while ($row = mysqli_fetch_array($result)) {
?>
<option value="<?php echo $row['formulationID']; ?>" <?php echo ($row['formulationID'] == $itemFormulation) ? 'selected' : ''; ?>>
<?php echo $row['formulation_name']; ?>
</option>
<?php
}
?>
</select>
</div>
<button type = "submit">Save changes</button>
</form>
I changed the code to better suit the problem, there may be typos, just comment for clarification
If I have understand Your question... You have to put Your result into a string. For example:
<?php
$output = array('data' => array());
$sql = "SELECT * FROM items";
$query = $connect->query($sql);
$option = '';
while ($row = $query->fetch_assoc()) {
$name=$row['name'],
$option.='<option value="$name">$name</option>'
}
echo json_encode($output);
?>
<form action=" " method="POST">
<div>
<label>Name</label>
<input type="text"><br>
<label>Formulation</label>
<select >
<?=$option?>
</select>
</div>
<button type = "submit">Save changes</button>
</form>
I hope to be of help
This should do the trick:
<?php
$itemsSql = "SELECT * FROM items WHERE itemId = 5";
$itemQuery = $connect->query($sql);
$item = $itemQuery->fetch_assoc();
$formulationsSql = "SELECT * FROM formulation";
$formulationsQuery = $connect->query($sql);
$formulations = $itemQuery->fetch_assoc();
?>
<form action="updateItem" method="POST">
<div>
<label>Item Name</label>
<input type="text" value="<?= $item[0]['name']; ?>"><br>
<label>Formulation</label>
<select>
<?php foreach($formulations as $formulation){
echo '<option value="'. $formulation['formulationId'].'">' .
$formulation['formulation_name'] . '</option>';
} ?>
</select>
</div>
<button type = "submit">Save changes</button>
</form>

how to get each input value on form submit

I'm building a friend request system,But my problem is how to get each user value which is the id in my code,But with the code i have so far it only get and return only the first user id even when you try to add other friend it only get the first user id in my database please someone should fix my code.
users.php
<div class="users_b">
<?php
include 'db.php';
$sq = "select * from alert_users_account";
$query = mysqli_query($con,$sq);
while($row = mysqli_fetch_assoc($query)){
?>
<div class="user_dis_p">
<div id="user_img"><a href="alert_profile.php?id=<?php echo $row['id']?>"><img src="alert<?php echo $row['photo']; ?>">
</a></div> <div id="user_fs">
<a href="alert_profile.php?id=<?php echo $row['id']?>">
<?php echo $row['firstname']." "." "." "." ".$row['surname'];?></a>
<form id="f_form">
<input type="text" name="friend_id" id="friend_id" value="<?php echo $row['id']?>">
<input type="submit" id="add_user" value="ADD" onclick="return request()">
</form>
</div><?php }?>
</div>
</div>
<div id="msg"></div>
<script>
function request(){
var frnd = document.getElementById("friend_id").value;
alert(frnd);
$.ajax({
type:'get',
url:'user_request.php',
data:{
frnd:frnd
},
cache:false,
success: function(message){
$("#msg").html(message);
}
});
return false;
}
</script>
user_request.php
<?php
session_start();
include 'db.php';
if(isset($_SESSION['email'])){
$eml = $_SESSION['email'];
$sq = $con->prepare("select id from alert_users_account where email_phone=?");
$sq->bind_param('s',$eml);
$sq->execute();
$res = $sq->get_result();
$ro = $res->fetch_assoc();
$user = $ro['id'];
if($_GET['frnd']){
echo $id = $_GET['frnd'];
$sql = $con->prepare("select * from alert_users_account where id=?");
$sql->bind_param('i',$id);
$sql->execute();
$result = $sql->get_result();
$row = $result->fetch_assoc();
$frnd = $row['id'];
$sql = $con->prepare("insert into friend (user_id,friend_id)values (?,?)");
$sql->bind_param('ss',$user,$frnd);
$sql->execute();
$sql->close();
echo "successfully inserted!";
}else{
echo 'error';
}
}else{
echo 'you cant add a friend!';
}
?>
I also try to use post method but both still give the same feedback
It appears you will need to rewrite certain aspects of your code. Here is my explanation:
You're using a while loop to show many different form elements with the id of "friend_id".
By using document.getElementById("friend_id"), you're only able to get one of those input elements that has the id of "friend_id".
You might use class="friend_id" on your input elements and go from there.

2 Forms (select) - 1 is dependent from 2

I want create form in html+php. I have got 2 tables in my database.
Categories: id_category, category
Dairy: id_dairy, id_category, product_name
And now is question. How can I create 1 form with 2 select dropdowns. Is it possible to do it in PHP without AJAX?
I mean that - I want choose Category and then choose Products without refresh page.
Code:
<form role="form" action="kalorie.php" method="post">
<div class="form-group">
<label for="kategoria">Kategoria:</label>
<select class="form-control" name="kategoria">
<option>Wybierz kategorie</option>
<?php
$sql_1 = "SELECT * FROM produkty";
$result_1 = mysqli_query($conn, $sql_1);
while($row_1 = mysqli_fetch_assoc($result_1)) {
echo '<option>'.$row_1["produkt"].'</option>';
}
$kat = $_POST['kategoria'];
?>
</select>
<select class="form-control" name="produkt">
<option>Wybierz produkt</option>
<?php
$sql_2 = "SELECT * FROM $kat";
$result_2 = mysqli_query($conn, $sql_2);
while($row_2 = mysqli_fetch_assoc($result_2)) {
echo '<option>'.$row_2["produkty"].'</option>';
}
?>
</select>
</div>
<button type="submit" class="btn btn-default" name="oblicz">Wyślij</button>
</form>
Ajax is best solution for this.
But if you want an alternative than you can use "iframe" and submit ypur form in that frame.
Non Ajax solution:
Load your product subcategories into a JavaScript object keyed by the category id. When the category is changed in the category select list, swap out the options in the product list.
<script>
var produkts = {
<?php
$sql_2 = "SELECT * FROM $kat";
$result_2 = mysqli_query($conn, $sql_2);
$id_category = 0;
list($delim1, $delim2) = array('', '');
while($row_2 = mysqli_fetch_assoc($result_2)) {
$delim2 = '"';
$row_2 = $row['value'];
if ( $id_category != $row_2['id_category'] ) {
$id_category = $row_2['id_category'];
echo $delim1 . $id_category . ': "';
$delim1 = '", ';
}
echo '<option>' . $row_2['produkty'] . '</option>';
}
echo $delim2;
?>
};
// example: {1: "<option>cheese</option><option>butter</option>", 2: "<option>ice cream</option>"}
</script>
<form role="form" action="kalorie.php" method="post">
<div class="form-group">
<label for="kategoria">Kategoria:</label>
<select class="form-control" name="kategoria">
<option>Wybierz kategorie</option>
<option value="1">Me</option>
<option value="2">You</option>
<?php
$sql_1 = "SELECT * FROM produkty";
$result_1 = mysqli_query($conn, $sql_1);
while($row_1 = mysqli_fetch_assoc($result_1)) {
echo '<option>'.$row_1["produkt"].'</option>';
}
$kat = $_POST['kategoria'];
?>
</select>
<select class="form-control" name="produkt">
<option>Wybierz produkt</option>
</select>
</div>
<button type="submit" class="btn btn-default" name="oblicz">Wyślij</button>
</form>
<script>
document.querySelector('select[name=kategoria]').addEventListener('change', function (evt) {
var kat = evt.target;
var kat_sel = kat.options[kat.selectedIndex].value
document.querySelector('select[name=produkt]').innerHTML = produkts[kat_sel];
})
</script>
Mocked up JSFiddle demo.

View customer info on select change

I'm creating a page which will allow an admin to select a user from a drop down list, which populates from a database. When the person is selected, the info associated with that person will then be viewed on the page. I already have a select statement which selects all the info and the drop down menu is populating correctly. However, I'm unsure on how to get that selected user's info to display on the page once selected. Would I need to do an entirely different select statement and query which checks which customer was selected? Or is there another way?
customer.php
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name='selectCust' id='selectCust'>";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
echo "<option>$name</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
viewUser.php
if(isset($search)){
$select = "SELECT * FROM $cust WHERE acctNum='{$search}'";
$result = mysqli_query($db, $select);
if(mysqli_num_rows($result) > 0){
if($row = mysqli_fetch_assoc($result)){
$acct = "{$row['acctNum']}";
echo $acct;
}
}
}
script.js
$(document).ready(function(){
function searchAjax(){
var search = $('#selectCust').val();
$.post('includes/viewUser.php', {searchUsers: search}, function(data){
$('#view_form').append(data);
})
}
$('#selectCust').on('change', function(ev){
ev.preventDefault();
searchAjax();
})
})
Search.php
<script type="text/javascript "src="//ajax.googleapis.com/ajax/libs/jquery/1.8.0/jquery.min.js"></script>
<script type='text/javascript'>
$(document).ready(function(){
$(".dropdown-users").on("change",function(event){
event.preventDefault();
search_ajax_way();
});
});
function search_ajax_way(){
var search_this=$("dropdown-users").val();
$.post("Ajaxsearch.php", {searchusers : search_this}, function(data){
$(".results").html(data);
})
}
</script>
<div id="view_form" class="view">
<form method="post">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select class="dropdown-users">";
echo "<option></option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo "<option value="$acct">$name ($acct)</option>";
}
echo "</select>";
?>
</fieldset>
</form>
</div>
<label>Enter</label>
<input type="text" name="search_query" id="search_query" placeholder="What You Are Looking For?" size="50"/>
<input type="<span id="IL_AD1" class="IL_AD">submit</span>" <span id="IL_AD6" class="IL_AD">value</span>="Search" id="button_find" />
<div class="results"></div>
//********************************************************************************************
********************************************************************************************//
Ajaxsearch.php
<?php
$con = mysqli_connect("localhost","my_user","my_password","my_db"); // Enter your information here
$term = $_POST['searchusers']
$term = mysqli_real_escape_string($con, $term);
if($term == "")
echo "Enter Something to search";
else {
$query = mysqli_query($con, "select * from USERDATEBASEHERE where ID = '{$term}' ");
$string = '';
if (mysqli_num_rows($query) > 0) {
if (($row = mysqli_fetch_assoc($query)) !== false) {
$string = "{$row['ID']}";
}
} else {
$string = "This Person does not exist";
}
echo $string;
}
?>
<div id="view_form" class="view">
<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
<fieldset>
<label for="viewCustomer">Select Customer</label>
<?php
echo "<select name=\"somename\" onchange=\"this.form.submit();\">";
echo "<option value=\"\">Select User</option>";
while($row = mysqli_fetch_assoc($custResult)){
$name = "{$row['fName']} {$row['lName']}";
$acct = $row['acctNum'];
echo '<option value="'.$acct.'">$name ($acct)</option>';
}
echo "</select>";
?>
</fieldset>
</form>
</div>
The options must have some refering value, through which you can retrieve the details of selected user, whenever the value of option is not initiated then the default value of the option will be option's label.

Categories