Dynamically add select option with options from php - php

How do I create a dynamic select input with options from PHP whenever I click on a button?
The working should go like this:
Whenever I click on a button, a select element with options from PHP should be available to choose from.
<div class="form-group">
<label class="control-label col-sm-2" for="product">Products:</label>
<div class="col-sm-4">
<select class="form-control" name="product[]" multiple required>
<option selected="selected">--SELECT PRODUCT--</option>
<?php
$sql = "SELECT * FROM `product`";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()){
?>
<option value="<?php echo $row['name']; ?>"><?php echo $row['name']; ?></option>
<?php
}
?>
</select>
</div>
</div>
Whenever I click on a button, I should be able to create a new select input with the above-mentioned code.

here you need to use ajax like below
function getOptions(query){
$.post(endPoint, query, function(response){
$('select[name="product[]"]').empty();
response.forEach(function(value){
$('select[name="product[]"]').append("<option value='" +value+ "'></option>");
});
})
}
and trigger it on click
$('body').on('click', '#myButton', function(){
getOptions(null);
});

Related

How to get data from database using drop down list and display into input fields in php mysql?

When I select one of the year from drop-down list so, how to show the title that related to year into input fields of the form below.
$formationSQL = "SELECT title FROM formationacademique";
$result = $connection->query($formationSQL);
<form method="post">
<label>Select year:</label>
<select>
<?php foreach($result as $formation): ?>
<option id="formationID" name="formationID" value="<?= $formation['ID_Formation']; ?>"><?= $formation['year']; ?></option>
<?php endforeach; ?>
</select>
<label>title:</label>
<input type="text value="">
</form>
Here are some changes that are needed for your html formatting. Would need to know if you are wanting this change to happen with javascript or in php? If you don't know the difference, it is that php is server side that will only parse on page load and javascript can do it without a page refresh or reload.
$formationSQL = "SELECT title FROM formationacademique";
$result = $connection->query($formationSQL);
<form method="post">
<label for="formationID">Select year:</label>
<select id="formationID" name="formationID">
<?php foreach($result as $formation): ?>
<option value="<?php $formation['ID_Formation']; ?>"><?= $formation['year']; ?></option>
<?php endforeach; ?>
</select>
<label for="input_title">title:</label>
<input type="text" id="input_title" name="input_title" value="<?php $formation['ID_Formation']; ?>">
</form>
Add the following script contents to your js file or add the script after the form above for the javascript verse of changing the inputs value.
<script>
var year_select = document.getElementById( 'formationID' );
var year_title = document.getElementById( 'input_title' );
year_select.addEventListener( 'change', function( e ) {
year_title.value = year_select.selectedIndex.value;
});
</script>

isset() does not work properly by using include in PHP

I am a very beginner in programming PHP.
I have the following HTML code and two PHP code "include". I am not sure why ISSET() not firing at all.
If I remove the isset(){} it brings up the data perfectly fine...
but when I try with isset() it shows no data. Can anyone help?
<form action="functions/pos-getPrice.php"class="form-horizontal"
method="post">
<div class="form-group">
<label class="col-md-4 control-label">Item</label>
<div class="col-md-6 selectContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-list"></i>
</span>
<select name="item" id="item" class="form-control selectpicker" >
<option>Please select your item</option>
<?php include "functions/pos-getItems.php" ?>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-4 control-label">Price</label>
<div class="col-md-6 selectContainer">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-list"></i>
</span>
<select name="price" class="form-control selectpicker" >
<option value="">Please select your price</option>
<?php include "functions/pos-getPrice.php" ?>
</select>
</div>
</div>
</form>
<?php
if(isset($_POST['item']) && $_POST['item'] == 'jacket') {
include "db-Info.php";
$res = mysqli_query($con, "select id, price, pointRequired from
tblPrice");
while($row = mysqli_fetch_array($res))
{
$price = $row['price'];
$pointRequired = $row['pointRequired'];
echo "<option value=\"".$row['id']."\">";
echo "Price: $price" ?> <?php echo "Point: $pointRequired";
echo "</option>";
}
}
?>
<?php
include "db-Info.php";
$res = mysqli_query($con, "select distinct item from tblPrice");
while($row = mysqli_fetch_array($res)){
$array = $row['item'];
echo "<option value=\"".$row['item']."\">";
echo $array;
echo "</option>";
}
?>
From what I can tell, I'm assuming your item list is loading correctly, and your price list is not? Are you expecting the price list to change when a user selects in item?
In this instance, there is no $_POST data when you load your page containing the form. Selecting an item in your dropdown does not send any kind of POST request causing the prices to change. Thus, at the time of page load, your price script is checking to see if $_POST["item"] is set and if that item is "jacket," which it is not at the time of page load. So no prices load, and that's that; the script doesn't keep checking what the item is after that.
If you're expecting prices to dynamically load based on the selected item, you'll either need to have an AJAX call that fetches the price options every time an item is selected, or you can preload all the price data upfront when the page loads, then use javascript to populate the price options on change of the item selector.

change of drop down in php my sql Dynamically

I have two drop downs .one have static value and second get values from db. I want to that if value is selected from 1st drop down then relevant values loaded in 2nd drop down. I have tried. but its load all the data from database according to user.for example when user select from request type dropdown having value inquiry.then 2nd drop down load only the values which have catType Inquiry.and if he select the complaint then complaint data must be shown.I have been tried but all the data is loaded ,or only one data is loading.any body help me in this regard.Thanks in Advance. Here is My Code
<div class="col-md-4">
<div class="form-group">
<label for="requesttype"><?php echo $requestField; ?></label>
<select class="form-control" required="" id="requesttype" name="requesttype" onchange="fcrActionChange(this);">
<option value="">Select Request Type</option>
<option value="Inquiry">Inquiry</option>
<option value="Complaint">Complaint</option>
<option value="Service Request/FCR">Service Request/FCR</option>
<option value="Verification Call">Verification Call</option>
</select>
<span class="help-block"><?php echo $requestHelp; ?></span>
</div>
</div>
$("#requesttype").change(function() {
$("#catId).load("navigation.php?requesttype=" + $("#requesttype").val());
});
</script>
<div class="col-md-4">
<div class="form-group">
<label for="catId"><?php echo $categoryField; ?></label>
<select class="form-control" name="catId" id="catId">
$tcat = "SELECT catId, catName FROM categories WHERE userId = ".$userId." AND isActive = 1 AND catType = ".$_GET['requesttype'];
$rest = mysqli_query($mysqli, $tcat) or die('-2'.mysqli_error());
while ($tcatrow = mysqli_fetch_assoc($rest)) {
echo "<option value="$tcatrow['catId'] >";
echo clean($tcatrow['catName'])."</option>";
}
</select>
<span class="help-block"><?php echo $categoryHelp; ?></span>
</div>
</div>
</div>
Your code is pretty confusing but anyway, the important part is within your ajax request and your PHP file
Ex. you have a div id secondOpt to be filled from the query made by the requesttype.
**Note I added a userId input field to pass the value for the SQL query in the navigation.php
<select class="form-control" required="" id="requesttype" name="requesttype" onchange="fcrActionChange(this);">
<option value="">Select Request Type</option>
<option value="Inquiry">Inquiry</option>
<option value="Complaint">Complaint</option>
<option value="Service Request/FCR">Service Request/FCR</option>
<option value="Verification Call">Verification Call</option>
</select>
<input type="hidden" id="userId" value="<?php echo $userId;?>">
<div id="secondOpt"></div>
After this, you will have an ajax request below, you can use $.post from jQuery and render the returned data on the secondOpt element
$('#requesttype').change(function(){
$.post("navigation.php",{requesttype: $(this).val(),userId: $('#userId').val()},function(options)
{
$('#secondOpt').html(options);
});
});
And for the navigation.php UPDATED
//don't forget your config file here to connect with the database
$userId = mysql_real_escape_string($_POST['userId']);
$requesttype = mysql_real_escape_string($_POST['requesttype']);
$output = "<select id='catId'>";
$tcat = "SELECT catId, catName FROM categories WHERE userId = ".$userId." AND isActive = 1 AND catType = ".$requesttype;
$rest = mysqli_query($mysqli, $tcat) or die('-2'.mysqli_error());
while ($tcatrow = mysqli_fetch_assoc($rest)) {
$output.="<option value=".$tcatrow['catId']." >";
$output.=clean($tcatrow['catName'])."</option>";
}
$output.="</select>";
echo $output;

Empty query result

in a web form there are two drop-down lists. The second list items should change dynamically depending on the value selected on the first drop-down list.
This is how am I trying to do it:
index.php:
...
<script>
function getClient(val) {
$.ajax({
type: "POST",
url: "get_contacts.php",
data:'client_id='+val,
success: function(data){
$("#contacts-list").html(data);
}
});
}
</script>
...
<div class="form-group">
<label for="mto_client" class="col-sm-2 control-label">MTO Client</label>
<div class="col-sm-10">
<select name="mto_client" id="clients_list" onChange="getClient(this.value)">
<option value="">Select a Client</option>
<?php
do {
?>
<option value="<?php echo $row_RSClients['id_client']?>" ><?php echo $row_RSClients['client_name']?></option>
<?php
} while ($row_RSClients = mysql_fetch_assoc($RSClients));
?>
</select>
</div>
</div>
<div class="form-group">
<label for="mto_client_contact" class="col-sm-2 control-label">MTO Client Contact</label>
<div class="col-sm-10">
<select name="state" id="contacts-list">
<option value="">Select Client Contact</option>
</select>
</div>
</div>
get_contacts.php
<?php
require_once("dbcontroller.php");
$db_handle = new DBController();
if(!empty($_POST["client_id"])) {
$query ="SELECT * FROM tb_client_contacts WHERE contact_client_id = '" . $_POST["client_id"] . "'";
$results = $db_handle->runQuery($query);
?>
<option value="">Select Client Contact</option>
<?php
foreach($results as $state) {
?>
<option value="<?php echo $state["id_client_contact"]; ?>"><?php echo $state["contact_name"]; ?></option>
<?php
}
}
?>
There are objects on the table tb_clients_contact that meet the condition, but the second drop-down list doesn't show any objects.
Any help is welcome.
Instead of
$("#contacts-list").html(data);
It should be
$('#contacts-list').empty().append(data);
empty() will clear first the options inside the contacts-list select field, then append() will insert the options from the result of your AJAX.
You can also look at the console log for errors. If you are using Google Chrome, hit F12 to display the console log.

Ajax Html Forms with PHP, Jquery and MYSQL,

I understand this question may be entirely juvenile however I have been trying to debug it for an entire afternoon, not using an IDE other than sublime. would be really glad to receive any help and format this question nicely for future begineers when it works.
currently
my html.
<?php
//connect to the server & database
$connect = mysqli_connect('localhost','root','root','ikea');
if(!$connect)
{
echo "failed to connect ".mysqli_connect_error();
}
// query the database
$query = 'SELECT * from department
where iconpath Like "image%"
order by name asc';
$result = mysqli_query($connect,$query);
// retrieve the resultset
while( $row[] = $result->fetch_object());
?>
<form id="question2" method="POST">
<div class="form-group input-group">
<select style="width:8.7cm;" id="member_choice" class="form-control">
<option value="">-- Select One --</option>
<?php foreach($row as $option) : ?>
<option value="<?php echo $option->name; ?>"><?php echo $option->name; ?></option>
<?php endforeach; ?>
</select><br/><br/>
<button id="q2-submit" name="q2-submit" style="margin-left:5cm;" type="submit" class="btn btn-default btn-add"> Get Departments! </button>
</div>
</form>
my jquery
$('#question2').on('submit', function()
{
alert("submit!");
// AJAX STUFF HERE
$.post('q3.php', function(data)
{
console.log("here1");
$(".return").html(data);
});
});
and currently experimenting with my php trying to get it to return "content"
<?php
echo "content";
?>
Your question keeps changing. Honestly, I recommend you go through a tutorial on how to submit a form using AJAX with jQuery, like this one.
You should use submit handler instead of a click handler. Also your selector is wrong.
HTML
added name attribute to the <select> tag.
<form id="question2" method="POST" action="q2.php">
<div class="form-group input-group">
<label>Select Member Card Number</label>
<select name="member_choice" style="width:8.7cm;" id="member_choice" class="form-control">
<option value="">-- Select One --</option>
<?php foreach($row as $option) : ?>
<option value="<?php echo $option->name; ?>"><?php echo $option->name; ?></option>
<?php endforeach; ?>
</select><br/><br/>
<button style="margin-left:5cm;" type="submit" class="btn btn-default btn-add"> Get Departments! </button>
</div>
</form>
<div id="content"></div>
JQUERY
$('#question2').on('submit', function(event)
{
// stop form from submitting normally
event.preventDefault();
var $form = $(this);
var url = $form.attr('action');
$.post(url, $form.serialize(), function(data)
{
console.log("here1");
$('#content').html(data.content);
});
});
PHP (q2.php)
<?php
$content = $_POST['member_choice'];
echo json_encode($content);
?>
Your click handler doesn't prevent the form from submitting (the page gets refreshed) so you never see the ajax response. Use a submit handler instead:
$('#question2').on('submit',function(e)
{
var name = $('#department_choice :selected').val();
console.log("here");
$(".return").html("asdad");
$.post('q2.php', function(data)
{
console.log("here1");
$(".return").html(data);
});
return false;//prevent form submit
});

Categories