I have a select with MySQL option values. My problem is with that if I have more then 1 value in the table, it's alway prints one option. How can I add dynamically more option value if an Employee has more then 1 company?
For example: modal
It has 2 company and I want to print all of the company he has, not just 1. How can I do this?
I print the current MySQL datas in the fetch.php.
index.php
<label>Company:</label>
<select name="company" id="company" class="form-control">
<?php
$query2 = "SELECT * FROM company GROUP BY company_id";
$result2 = mysqli_query($connect, $query2);
while($row2= mysqli_fetch_array($result2)){
?>
<option value="<?php echo $row2['company_id'];?>"><?php echo $row2['company_name'];?></option>
<?php
}
?>
</select>
<script>
$(document).on('click', '.edit_data', function(){
var employee_id = $(this).attr("id");
$.ajax({
url:"fetch.php",
method:"POST",
data:{'employee_id':employee_id},
dataType:"json",
success:function(data){
$('#company').val(data.company);
}
});
});
</script>
fetch.php
if(isset($_POST["employee_id"]))
{
$query = "SELECT employee.id AS id, employee.name AS name, employee.address AS address, company.company_id AS company
FROM employee
LEFT JOIN employee_company ON employee.id = employee_company.employee_id
LEFT JOIN company ON company.company_id = employee_company.company_id
WHERE employee.id = '".$_POST["employee_id"]."'";
$result = mysqli_query($connect, $query);
$row = mysqli_fetch_array($result);
echo json_encode($row);
}
First of all, you can't select multiple options from a dropdown menu. You need to use a multi-select.
<select name="company" id="company" class="form-control" multiple>
<?php
$query2 = "SELECT * FROM company GROUP BY company_id";
$result2 = mysqli_query($connect, $query2);
while($row2= mysqli_fetch_array($result2)){
?>
<option value="<?php echo $row2['company_id'];?>"><?php echo $row2['company_name'];?></option>
<?php
}
?>
</select>
Then you need to change fetch.php return an array of all the company IDs:
if(isset($_POST["employee_id"]))
{
$query = "SELECT employee.id AS id, employee.name AS name, employee.address AS address, company.company_id AS company
FROM szerepek
LEFT JOIN employee_company ON employee.id = employee_company.employee_id
LEFT JOIN company ON company.company_id = employee_company.company_id
WHERE employee.id = '".$_POST["employee_id"]."'";
$result = mysqli_query($connect, $query);
if (mysqli_num_rows($result) == 0) {
echo json_encode(null);
} else {
$companies = array();
while ($row = mysqli_fetch_assoc($result)) {
$companies[] = $row['company'];
}
$row['companies'] = $companies;
echo json_encode($row);
}
}
and change the Javascript to loop through them and select all of them.
$(document).on('click', '.edit_data', function(){
var employee_id = $(this).attr("id");
$.ajax({
url:"fetch.php",
method:"POST",
data:{'employee_id':employee_id},
dataType:"json",
success:function(data){
if (data) {
$("#company").val(data.companies);
}
}
});
});
Related
I'm stuck getting my AJAX/PHP to work. I'd really appreciate it if someone can help me to spot the error(s) I'm making.
Here's an extract from my first file which successfully populates the select in the HTML:
<?php
include 'connect_db.php';
//get all period types data
$sql = "SELECT * FROM periodtypes ORDER BY period_type_id";
$result = mysqli_query($connect,$sql);
$rowCount = mysqli_num_rows($result);?>
The HTML/PHP for the select:
<select id="period_type_id" name="period_type_id" onchange="getNewP();">
<option value="">Select a Period Type</option>
<?php
if($rowCount>0){
while ($row=mysqli_fetch_assoc($result)){
echo '<option value="'.$row['period_type_id'].'">'.
$row['period_type_desc'].
' </option>';
}
}else{
echo '<option value="">Period type not available</option>';
}
?>
</select>
The HTML for the inputs I wish to update using the AJAX function below:
<label>Start Date (Auto-generated):</label>
<input type="text" id="start_date" name="start_date" value = "" readonly>
<br><br>
<label>End Date (Auto-generated):</label>
<input type="text" id="end_date" name="end_date" value = "" readonly>
And the AJAX function:
function getNewP(){
var id = $("#period_type_id").val();
alert(id); //This fires ok
if (id != '')
{
$.ajax({
url: "get_period_nbrs.php",
method:"POST",
data: { id : id },
dataType: "JSON",
success: function(output)
{
$('#start_date').text(output.start_date);
$('#end_date').text(output.end_date);
}
});
}else
{
alert("Please select a Period Type");
}
}
Finally, the main PHP script:
<?php
include 'connect_db.php';
if (isset($_POST['id']) && !empty($_POST['id'])){
//echo $_POST[id];
$sql = "SELECT SUBSTRING(MAX(period_nbr),5,2)+1 AS nxt_sfx,
MAX(start_date)+ 1 as start_date, MAX(end_date)+1 AS end_date
FROM periods AS p
INNER JOIN periodtypes AS pt on pt.period_type_id = p.period_type_id
WHERE p.period_type_id = '".$_POST['id']."'";
$result = mysqli_query($connect,$sql);
while($row=mysqli_fetch_array($result)){
if($result == true){
$start_date = $row['start_date'];
$end_date = $row['end_date'];
$period_nbr_nxt_sfx = $row['nxt_sfx'];
if ($period_nbr_nxt_sfx < 52 && $period_nbr_nxt_sfx != NULL){
$output['start_date'] = $row['start_date'];
$output['end_date'] = $row['end_date'];
echo json_encode($output);
}
}
}
}
?>
You're not using the right method to fill your inputs :
$('#start_date').text(output.start_date);
$('#end_date').text(output.end_date);
Should be :
$('#start_date').val(output.start_date);
$('#end_date').val(output.end_date);
JSON needs a root key, try this:
print_r( "{\"data\": ".json_encode($output)."}" );
instead of
echo json_encode($output);
i want the function(data) to get 2 attribute value from the database
This is the select option that display the display the address and contact value of the selected option in an input field
$('#recipient').change(function(){
var FULL_NAME = $(this).val();
$.ajax({
url:"load_data.php",
method:"POST",
data:{FULL_NAME:FULL_NAME},
success:function(data){
$('#address').val(data);
$('#contact').val(data);
}
});
});
and this is the load_data.php
<?php
$sql = "SELECT * FROM recipient";
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$output1 = $row["ADDRESS"];
$output2 = $row["CONTACT"];
$arr = array($output1,$output2);
}
echo $output1,$output2;
?>
How do i pass the $output1 into $('#address').val(data) and $output2 into $('#contact').val(data)
$('#recipient').change(function(){
var FULL_NAME = $(this).val();
$.ajax({
url:"load_data.php",
method:"POST",
dataType: "json",
data:{FULL_NAME:FULL_NAME},
success:function(data){
$('#address').val(data['ADDRESS']);
$('#contact').val(data['CONTACT']);
}
});
});
and the load_data.php
<?php
$result = mysqli_query($connect, $sql);
while($row = mysqli_fetch_array($result))
{
$arr["ADDRESS"] = $row["ADDRESS"];
$arr["CONTACT"] = $row["CONTACT"];
}
echo json_encode($arr);
?>
i am working with interlinked dropdown list i.e on selection of one dropdown list ajax call generated and populated another dropdown list and so on.
So my problem is with data coming from server side,on selection of each dropdown list i want to filter the available-results also,but the data that coming from server side get appended to show div i.e dropdown-list items and results-items.i only want to append results-items to show div.
client side code
var country_code = $(this).val();
console.log(country_code);
if(country_code){
$('#loadingmessage').show();
$.ajax({
type:'POST',
url:'dependent.php',
data:'country_code='+country_code,
success:function(html){
console.log(html);
$('#state').html(html);
$('#city').html('<option value="">Select state first</option>');
$('#results').html(html);
$('#loadingmessage').hide();
}
});
}else{
$('#state').html('<option value="">Select country first</option>');
$('#city').html('<option value="">Select state first</option>');
}
});
server side code
if(isset($_POST["country_code"]) && !empty($_POST["country_code"])){
$id = 1;
$code = $_POST['country_code'];
$code = mysqli_real_escape_string($conn,$code);
$query = "SELECT * FROM plus2_state WHERE country_code = '$code' ORDER BY state ASC";
$result = mysqli_query($conn,$query) or die(mysqli_error($conn));
$rowCount = mysqli_num_rows($result);
if($rowCount > 0){
while($row = mysqli_fetch_array($result)){
echo '<option class="state_option" value="'.$row['state_id'].'">'.$row['state'].'</option>';
}
}else{
echo '<option class="state_option" value="">State not available</option>';
}
$query_1 = "SELECT * from content where country_code = '$code' ORDER BY emp_name ASC";
$result_1 = mysqli_query($conn,$query_1) or die(mysqli_error($conn));
$row_count = mysqli_num_rows($result_1);
$_SESSION['result'] = array();
if($row_count > 0 )
{
while($content_rows = mysqli_fetch_array($result_1))
{
unset($_SESSION['result']);
echo "<div class='result'><div class='col-md-3 photo-grid' style = 'float:left'>
<div class = 'well well-sm'><h4><small>".$content_rows['emp_name']."</small></h4></div></div></div>";
$_SESSION['result'][$id] = array('name' => $content_rows['emp_name']);
}
}
else
{
echo "<div class = 'result'>no results found</div>";
}
$_SESSION['country_code'] = $code ;
//print_r($_SESSION['result']);
}
I have a form that adds vehicles to a database, there are 2 drop down select fields in the form, 'Make' and 'Model'
When I select an option from either one to insert it into the stock table in the database the make 'ID' or model 'ID' gets inserted into vehicle make / model rather than the name of the vehicle make, so '3' gets inserted instead of 'Volkswagen'
Here is some of my code
<form action="addstock.php" method="post" enctype="multipart/form-data">
<div class="make">
<div id="field1">Make:</div> <div id="field2">
<select name="mke" id="mke">
<?php
include 'includes/db2.php';
$SQL = "SELECT * FROM make";
$query = mysqli_query($con, $SQL);
while ($row = mysqli_fetch_array($query)) {
$res = "<option ";
$res .= "value='".$row['code']."'>";
$res .= $row['vehicle_make'];
$res .= '</option>';
echo $res;
}
?>
</select>
</div>
</div>
</div>
<script src="jquery/jquery-2.1.4.min.js"></script>
<script>
$(document).ready(function(){
$('#mke').change(function(){
var code = $(this).val();
var data = 'code='+code;
$.ajax({
type : "POST",
url : "fill.php",
data : data,
cache: false,
success: function(html)
{
$('#mdl').html(html);
}
});
});
});
</script>
Code for the model drop down option, the rest of the code for this is on another page (fill.php)
<div id="field1">Model:</div> <div id="field2">
<select name="mdl" id="mdl">
<option selected="selected">Model</option>
</select>
</div>
</div>
fill.php page
if(isset($_POST['code']))
{
$SQL = "SELECT * FROM model WHERE MakeCode = '".$_POST['code']."'";
$query = mysqli_query($con, $SQL);
if(mysqli_num_rows($query) == 0 )
{
echo '<option>No Results</option>';
} else {
while ($row = mysqli_fetch_array($query)) {
$res = "<option ";
$res .= "value='".$row['id']."' >";
$res .= $row['vehicle_model'];
$res .= "</option>";
echo $res;
}
}
} else {
echo '<option >error</option>';
}
?>
Back on the addstock.php page here is the insert code
<?php
if(isset($_POST['addstock'])){
$mke = $_POST['mke'];
$mdl = $_POST['mdl'];
$addstock = "insert into stock (veh_make,veh_model) values('$mke','$mdl')";
$addsto = mysqli_query($con, $addstock);
if($addsto){
echo "<script>alert('Vehicle has been added')</script>";
echo "<script>window.open('addstock.php','_self')</script>";
}
}
I'm fairly new to php and not sure how to insert the name instead of the id, as when I am trying to display a vehicle on another page the ID's show like 3 4, instead of Volkswagen Golf
Hope you understand what I mean
Any help is much appreciated!
You can insert the result of a SELECT statement that gets you the make and model:
"insert into stock (veh_make,veh_model) select make.vehicle_make, vehicle_model FROM make, model WHERE make.id=$mke AND model.id=$mdl"
But this is wrong DB design. stock should not contain make and model names, but rather IDs, references to rows in other tables, or Foreign Keys.
I am not posting here complete code yet I want an idea how to retrieve data in checboxes based on a dropdown list. I have a dropdownlist of users, and pages data in checkboxes.
Suppose table user have two columns (user_id, user) and pages have three columns (page_id, user_id, title).
I wish these cheboxes automatic check/uncheck acording to selected user without refreshing page. Suppose I am fetching users as
echo '<select name="user_id">';
echo '<option value="">Select User</option>';
$sql = "SELECT * from users";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
$uid = $row['user_id'];
$user = $row['user'];
echo '<option value="'.$uid.'">'.$user.'</option>';
}
echo '</select>';
And data in checkboxes on the basis of selected user (make sure user_id is compared in IF condition but not in query)
$user_id = $_POST['user_id']; //selected user from list
$query = "SELECT * from pages";
$result = mysql_query($query);
while($rowPage = mysql_fetch_assoc($result)) {
$upid = $rowPage['user_id'];
$pid = $rowPage['page_id'];
$title = $rowPage['title'];
if($upid == $user_id) {
echo '<input type="checkbox" name="userPages[]" value="'.$pid.'" checked="checked"> '.$title;
} else {
echo '<input type="checkbox" name="userPages[]" value="'.$pid.'"> '.$title;
}
}
How is it possible in Ajax/Jquery I mean without refreshing page.
Hope you understand what I mean.
Thanks
here is the asnwer what you can do is like this
echo '<select name="user_id" id="userCombo">';
echo '<option value="">Select User</option>';
$sql = "SELECT * from users";
$res = mysql_query($sql);
while($row = mysql_fetch_assoc($res)) {
$uid = $row['user_id'];
$user = $row['user'];
echo '<option value="'.$uid.'">'.$user.'</option>';
}
echo '</select>';
echo '<div id="userCheckBoxes"></div>'
Now put the ajax call on the change event of the select box.
I am here going to use jquery ajax.
<script type="text/javascript">
$(document).ready(function()
{
$("#userCombo").change(function()
{
var id=$(this).val();
var dataString = 'user_id='+ id;
$.ajax
({
type: "POST",
url: "ajax_checkboxes.php",
data: dataString,
cache: false,
success: function(html)
{
$("#userCheckBoxes").html(html);
}
});
});
});
</script>
Now make ajax_checkboxes.php into same directory.
then put your below code into the ajax_checkboxes.php. I assume you can make database connectivity and all by your self.
$user_id = $_POST['user_id']; //selected user from list
$query = "SELECT * from pages";
$result = mysql_query($query);
while($rowPage = mysql_fetch_assoc($result)) {
$upid = $rowPage['user_id'];
$pid = $rowPage['page_id'];
$title = $rowPage['title'];
if($upid == $user_id) {
echo '<input type="checkbox" name="userPages[]" value="'.$pid.'" checked="checked"> '.$title;
} else {
echo '<input type="checkbox" name="userPages[]" value="'.$pid.'"> '.$title;
}
}
I did not taste it on my local server but I am sure It will work.
PS dont for get to include jQuery on the head section of your site.