Load data into dropdown with ajax, php and mysql - javascript

Hi I need to populate a dropdown field using a value taken from the database and show it as selected and at the same i would like to show a list of options taken from the database,
Everything works fine except for the field "User Group" this is what i've done so far, can anybody please help me?
Many thanks
Html file
<div class="row">
<div class="col-md-6">
<div class="form-group">
<label class="control-label">User Group
<span class="required"> * </span>
</label>
<select class="form-control bs-select" id="userGroup" name="userPippo">
<?php
$select_group_query="SELECT group_id, group_name FROM user_group";
$run= mysqli_query($conn, $select_group_query);
while($row= mysqli_fetch_array($run)) {
echo "<option value= '".$row['group_id']."' >" . $row['group_name'] . "</option>";
}
?>
</select>
</div>
</div>
</div>
Javascript file
function GetUserDetail(id) {
$("#EditUserModal").modal("show");
$("#user_id").val(id);
var user_id = $('#user_id').val();
$.ajax({
url: "../controllers/ctrl_admin_user_app/ctrl_admin_get_user_details.php",
method: "POST",
data: {
user_id: user_id
},
dataType: "json",
success: function(data) {
console.log(data);
$('#firstName').val(data.user_first);
$('#lastName').val(data.user_last);
$('#userEmail').val(data.user_email);
$('#userTel').val(data.user_telephone);
$('#userFiscalcode').val(data.user_fiscalcode);
$('#userBirth').val(moment(data.user_birth).format('DD/MM/YYYY'));
$('#userDocument').val(data.user_iddocument);
$('#userRole').val(data.user_role);
// ricarico il campo per falo funzionare con il plugin bs-select
$('#userRole').selectpicker('refresh');
$('#userGroup').val(data.group_name); // doesn't work
// make it work with bs-select
$('#userGroup').selectpicker('refresh');
doesn 't work
$("#EditUserModal").modal("show");
}
});
}
PHP File
if (isset($_POST["user_id"])) {
$userid = $_POST['user_id'];
$user_id = filter_var($userid, FILTER_SANITIZE_NUMBER_INT);
$query = "SELECT group_id, group_name, user_first, user_last, user_email, user_telephone, user_fiscalcode, user_birth, user_iddocument, user_role FROM user_group_join LEFT JOIN (user_group, users) ON (user_group_join . group_join_id = user_group . group_id AND user_group_join . user_join_id = users . user_id) WHERE user_join_id = ? ";
$stmt = mysqli_prepare($conn, $query);
mysqli_stmt_bind_param($stmt, "i", $user_id);
mysqli_stmt_execute($stmt);
$result = mysqli_stmt_get_result($stmt);
$response = array();
while ($row = mysqli_fetch_assoc($result)) {
$response = $row;
}
echo json_encode($response);
}

from the Documentation,
.selectpicker('val');
You can set the selected value by calling the val method on the element.
$('.selectpicker').selectpicker('val', 'Mustard');
$('.selectpicker').selectpicker('val', ['Mustard','Relish']);
This is different to calling val() directly on the select element. If you call val() on the element directly, the bootstrap-select ui will not refresh (as the change event only fires from user interaction). You will have to call the ui refresh method yourself.
.selectpicker('refresh');
To programmatically update a select with JavaScript, first manipulate the select, then use the refresh method to update the UI to match the new state. This is necessary when removing or adding options, or when disabling/enabling a select via JavaScript.
$('.selectpicker').selectpicker('refresh');
So,
Replace these lines
$('#userGroup').val(data.group_name); // doesn't work
// make it work with bs-select
$('#userGroup').selectpicker('refresh');
with this line,
$('#userGroup').selectpicker('val', data.group_id).selectpicker('refresh');

Related

How to fetch mutiple values on select option and display in input type using ajax?

I'm trying to fetch mutiple values from database using ajax php.
I've a select option(value is fetching from database), and if i select any option then i want to display the related data which is matching with the id
of the the current option.but currently i'm able to fetch only one data column from databse.
I'm writing my current code please have a look at it and let me know how can i modify it.
My select option:-
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' onChange="getCity(this.value);" id="vno" required='true' >
<option value="">Select</option>
<?php
foreach($results as $vd) { ?>
<option value='<?php echo $vd['id'];?>'><?php echo $vd['vno'];?></option>";
<?php } ?>
</select>
and the js file
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:'id='+val,
success: function(data){
$("#rate").html(data);
}
});
}
retrive_data.php
<?php
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
$query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
$results = $db_handle->runQuery($query);
?>
<?php
foreach ($results as $city) {
?>
<option value="<?php echo $city["rate"]; ?>"><?php echo $city["rate"]; ?></option>
<?php
}
}
?>
Change your js code as below
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php?id=" + val,
success: function(data){
$("#rate").html(data);
}
});
}
I’m making some assumptions about the desired result, and I’m not sure what the connection is between vehicles and city rates... but there are multiple issues here. Let’s work through them:
<select data-placeholder="Choose a Vehicle..." class="chosen-select form-control" tabindex="-1" name='vno' id="vno" required='true' >
<option value="">Select</option>
<?php foreach($results as $vd): ?>
<option value="<?= $vd['id']?>" ><?= $vd['vno'] ?></option>";
<?php endforeach; ?>
</select>
<!-- add a landing spot for the data coming in -->
<select id="rate"></select>
Nothing major here, just took out the onChange (typical practice is to have a listener in the JavaScript. Separation of concerns)
In your JavaScript, I don’t think you were successfully passing the id. It should be a JavaScript object. Also, send data to a function that knows how to put the data in your form:
// Fetch city from Database
function getCity(val) {
$.ajax({
type: "POST",
url: "retrive_data.php",
data:{id: val},
success: function(data){
showRate(data);
}
});
}
Monitor the select for a change. (JavaScript should be inside document ready block)
$('#vno').on('change', function (){
getCity($(this).val());
});
Function to display the results of your ajax call:
showRate(data) {
// this lets you see the data that was returned
console.log(data);
var rate = $('#rate');
// clear current content
rate.html('');
// create options, assuming this is a select
$.each(data, function() {
rate.append($("<option />").val(this.rate).text(this.rate));
});
}
retrieve.php
Need to use prepared statements, and sending data as json instead of html is recommended
<?php
// sending json (data), not html (presentation)
header('Content-Type: application/json');
require_once ("dbController.php");
$db_handle = new DBController();
if (! empty($_POST["id"])) {
// substituting variables in a query is a big no-no
// $query = "SELECT * FROM tbl_vehicle WHERE id = '" . $_POST["id"] . "' ";
// must use placeholders / prepared statement
$query = "SELECT * FROM tbl_vehicle WHERE id = ?'";
// check your database object for how to do prepared statements and row fetching. If it doesn’t do prepared statements, dump it!
$stmt = $db_handle->prepare ($query);
$stmt->execute($_POST["id"]);
$out = array();
while($row = $stmt->fetch() ) {
$rate = $row['rate'];
$out[] = array(
'rate'=>$rate
);
}
die(json_encode($out));
}
Caveat: all code is off the top of my head, and typed on a phone. Syntax errors are likely. This is intended to show concepts and ideas for further research

Populate db values fill dynamically in textbox, based on selection of dropdown in php

I have used two fields in my DB, one field name is the category and another field name is mobile. I have already done it to Displaying category values in drop down box. but I just need to select those category value from drop-down selection then I want to show its mobile number in textbox field. any help greatly appreciated.
Dropdown box code:-
<select name="cat" id="cat">
<?php while($row1 = mysqli_fetch_array($result1)):?>
<option value="<?php echo $row1[0];?>">
<?php echo $row1[4];?>
</option>
<?php endwhile;?>
</select>
Input box code:-
<input placeholder="Phone Number" name="phoneNumber" id="pnum" type="text">
Javascript/AJAX POST:-
$('#cat').click(function() {
var package = $('#cat').val();
$.ajax({
data: {
'package': package
}, //Have u tried this
type: 'POST',
url: 'ajax1.php',
//dataType:'json',
success: function(data) {
$('#pnum').val(data);
}
});
});
ajax1.php:-
<?php
include('config.php');
if (isset($_POST['package'])) {
$query = "select * from `user_content` where Category=" . $_POST['package'];
$result1 = mysqli_query($db, $query);
if (mysqli_num_rows($result1) > 0) {
while ($res = mysqli_fetch_array($result1)) {
echo $res['Mobile'];
}
}
die();
}
?>
First thing that I noticed wrong in your code is semi-colon ; after while loop.
So change following:
<?php while($row1 = mysqli_fetch_array($result1)):;?>
with:
<?php while($row1 = mysqli_fetch_array($result1)):?>
The problem of undefined index is due to use of wrong condition here:
if (!isset($_POST['package']))
This should look like:
if (isset($_POST['package']))

On successful ajax, create a dropdown select from another table with preselected option value

For an ‘Edit’ modal, I initiate an ajax call to the php script named getSelectedMember.php that bring the information from the table items (Table 2).
<?php
require_once 'db_connect.php';
$memberId = $_POST['member_id'];
$sql = "SELECT * FROM items WHERE itemID = $memberId";
$query = $connect->query($sql);
$result = $query->fetch_assoc();
echo json_encode($result);
?>
This formulation_fk is in the table items a value of a select option from another table named formulation (Table 1).
This is code of 'edit.php' :
<form action=" " method="POST">
<div>
<label>Name</label>
<input type="text"><br>
</div>
<div>
<label>Formulation</label>
<select id="editFormulation">
</select>
</div>
<button type = "submit">Save changes</button>
</form>
My question is while updating a single item, how can I pass the select options from the formulation table in my edit form where the select option value will be the formulation_fk from the table items?
And this is my ajax call:
$.ajax({
url: 'getSelectedMember.php',
type: 'post',
data: {
member_id: itemID
},
dataType: 'json',
success: function(response) {
$("#editName").val(response.name);
$("#editFormulation").val(response.formulation_fk);
$(".editMemberModal").append( ? ? ? ? ? ? )
}
});
For clarification of my question, let's think that to edit Water, the action flow would be like this:
Click the edit button for ‘Water’.
Ajax call to getSelectedMember.php to get the name (Water) and
formulation_fk (1).
On response, Name field will output ‘Water’
and Formulation filed will output a dropdown select from
formulation table where option value = “1”
Something like this image below.
I have been trying to solve it for a while but I'll really appreciate any suggestion or expert help. Thanks in advance.
The PHP code needs to return an array of all the formulations, in addition to the formulation_fk from the items table.
$memberId = $_POST['member_id'];
$sql = "SELECT * FROM items WHERE itemID = $memberId";
$query = $connect->query($sql);
$result = $query->fetch_assoc();
$sql = "SELECT * FROM formulation";
$query = $connect->query($sql);
$formulations = array();
while ($row = $query->fetch_assoc()) {
$formulations[] = $row;
}
$result['formulations'] = $formulations;
echo json_encode($result);
Then the AJAX code can fill in the <select> before setting its value.
success: function(response) {
$("#editFormulation").empty(); // Clear out previous value
$.each(response.formulations, function() {
$("#editFormulation").append($("<option>", {
value: this.formulationID,
text: this.formulation_name
}));
});
$("#editFormulation").val(response.valuation_fk);
$("#editName").val(response.name);
}

Second dependent dropdown isn't getting filled with data

I'm trying to make a grade distributions website, and I'm creating 4 dropdowns correlating subject (cs, math, etc.), class (data structures, AI, etc.), professor, and quarter the class was taken. After the quarter dropdown is selected, I want to display a bar graph with the data.
The problem I'm running into is that I can't populate the second dropdown with data Basically, I can successfully pull data from the database for the first dropdown, and if the user selects something then the second dropdown (that was originally hidden using jquery) becomes visible, but it isn't properly pulling data from the database and adding it as options to the second dropdown. An example would be that I can select Computer Science from the first dropdown, then the second dropdown is visible, but it doesn't contain 'intro to programming', 'data structures', etc. in it; instead, it's just blank.
FYI, I'm using these selectpickers: http://silviomoreto.github.io/bootstrap-select/
PHP (error is most likely somewhere in the getClasses function, quite possibly the $_POST section of the code):
<?php
function getSubjects()
{
/* Get mysql connect information from external file and connect*/
require_once 'database.php';
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($connection->connect_error) die ($connection->connect_error);
/* Get the column containing the subjects from the table */
$query = 'SELECT DISTINCT Subject FROM gradelist ORDER BY Subject';
$result = $connection->query($query);
if(!$result) die ($connection_error);
/* Keep track of the number of rows in the column; necessary for iterating */
$rows = $result->num_rows;
/* selectBar keeps track of the html code for the select Bar*/
$selectBar = '';
for($j = 0; $j < $rows; $j++)
{
$result->data_seek($j);
$value = $result->fetch_assoc()['Subject'];
$selectBar .= '<option>' . $value .'</option>';
}
$result->close();
$connection->close();
return $selectBar;
}
function getClasses()
{
$connection = new mysqli($db_hostname, $db_username, $db_password, $db_database);
if($connection->connect_error) die ($connection->connect_error);
if(isset($_POST['subject']))
{
$query = "SELECT DISTINCT Class FROM gradelist WHERE Subject = $subject";
$result = $connection->query($query);
if(!$result) die ($connection_error);
}
else
{
die($connection_error);
}
$rows = $result->num_rows;
for($j = 0; $j < $rows; $j++)
{
$result->data_seek($j);
$value = $result->fetch_assoc()['Class'];
$selectBar .= '<option value = "' . $value . '">' . $value .'</option>';
}
$result->close();
$connection->close();
return $selectBar;
} ?>
HTML Portion of the code (again, the error might be with the $_POST part of the code) :
<form class="form-horizontal" method = "post" role="form">
<div class="form-group">
<div class="col-lg-10">
<select name = "subject" id="subject" class="selectpicker show-tick form-control" data-live-search="true" title ="Subject">
<?php echo getSubjects(); ?>
</select>
</div>
</div>
</form>
<form class="form-horizontal" method = "get" role="form">
<div class="form-group">
<div class="col-lg-10">
<select name = "class" id="class" class="selectpicker show-tick form-control" data-live-search="true" title ="Class">
<?php if(isset($_POST['subject'])) echo getClasses(); ?>
</select>
</div>
</div>
</form>
jQuery:
$(document).ready(function() {
$('#class').selectpicker('hide');
$('#professor').selectpicker('hide');
$('#quarter').selectpicker('hide');
});
$('#subject').on('change', function(){
$('#class').selectpicker('refresh');
$('#class').selectpicker('show');
});
$('#class').on('change', function(){
$('#professor').selectpicker('show');
});
$('#professor').on('change', function(){
$('#quarter').selectpicker('show');
});
$('#quarter').on('change', function(){
showTable();
temp = $('#class').selectpicker('val') + " with " + $('#professor').selectpicker('val') + " during " + $('#quarter').selectpicker('val');
$('#displayName').text(temp);
});
Your PHP is executed with $_POST["subject"] not set, and you never POST the subject the user chose to the page; if you don't make an additional POST request, there's no way for the classes to populate.
One way to do it (without changing any of your files) is like so:
$('#subject').on('change', function(){
$.post({
data: { subject: $(this).val() },
success: function (data) {
var classes = $(data).find("#class");
$("#class").replaceWith(classes);
}
});
});
So when a change event is triggered on the subject selection, we'll POST the selected subject to the current page. The response should be the entire document generated with the class selection filled (since $_POST["subject"] is set).
We then replace the current page's #class select element with the version in the generated data (wrapped in $() to create DOM elements from the stringified HTML, so we can use find()).
Another way might be to have files, getSubjects.php, getClasses.php, and so on, and POST individually to them (you make the first request onload, and subsequent requests onchange). This way, you can just append the generated option elements to the select elements on the page.
ALSO: Please please please sanitize $_POST["subject"] before using it in a database query. A user could easily add a fake option to the select locally with a malicious string for value, and you'd unknowingly query the DB with that. You can use prepared statements for this (mysqli has the prepare() function to prepare a statement before querying). More on that and combating SQL injection here.

Live AJAX search with multiple inputs simultaneously PHP/MySQL

I'm working on a live search in AJAX (for a database of powder horns) with two inputs, the first for the year, and the second for the conflict. The problem I'm having is when one of the inputs is blank, it only returns elements in the table that have no date or conflict name listed. Instead I want blank inputs to behave as null, and show everything from the table. I can fix the date section using a conditional to check if (!$date), but I can't get the select input to behave the same way if the user chooses blank again.
Any ideas on how to fix this? Especially in one query without a ton of PHP if/else?
HTML
<h1> Powder Horn Search Engine </h1>
Date <input id="date" type="text" name="variable">
To <select id="conflict">
<option> </option>
<option value="French & Indian War">French & Indian War</option>
<option value="Revolutionary War">Revolutionary War</option>
<option value="War of 1812">War of 1812</option>
</select>
<div id="result">
</div>
Javascript
var date="";
var conflict=""
$(document).ready( function () {
//Send date to PHP
$("#date").keyup(function(){
date = $("#date").val();
conflict=$("#conflict").val();
$.ajax({
type: "POST",
data: {date: date, conflict:conflict},
url: "powderhornsearch.php",
success: function(data){ //response param
$("#result").html(data);
}
});
});
//Send conflict to PHP
$("#conflict").change(function(){
conflict=$("#conflict").val();
date = $("#date").val();
$.ajax({
type: "POST",
data: {conflict: conflict, date:date},
url: "powderhornsearch.php",
success: function(data){ //response param
$("#result").html(data);
}
});
});
});
PHP
$date = $_POST['date'];
$conflict=$_POST['conflict'];
$result = mysql_query ("SELECT * FROM powderhorns WHERE Date LIKE $date AND Conflict LIKE '$conflict' ", $connection);
if (!$result) {
die("Database query failed:" . mysql_error());
}
echo "<table>";
while ($row = mysql_fetch_array($result)) {
echo "<tr>";
echo "<td>".$row[0]."</td>".
"<td>".$row[1]."</td>".
"<td>".$row[2]."</td>".
"<td>".$row[3]."</td>".
"<td>".$row[4]."</td>";
echo "</tr>";
}
echo "</table>";
EDIT
I changed the value of the blank select to "1" because it seemed like MySQL was having trouble with the empty string. I got everything to work by using the following code. As I am new to programming, if anyone has a suggestion on how to make it more condensed or elegant, I'd love your ideas. Thanks so much!
if (!$date) {
$date="";
}
if ($conflict=="1" && !$date)
{
$result = mysql_query ("SELECT * FROM powderhorns", $connection);
}
else if ($conflict==1){
$result = mysql_query ("SELECT * FROM powderhorns WHERE Date LIKE $date ", $connection);
}
else if (!$date && $conflict){
$result = mysql_query ("SELECT * FROM powderhorns WHERE Conflict LIKE '$conflict' ", $connection);
}
else{
$result = mysql_query ("SELECT * FROM powderhorns WHERE Conflict LIKE '$conflict' and Date LIKE $date ", $connection);
}
change it to:
$condition=1;
if(trim($date)) $condition .=" and Date LIKE '$date'";
if(trim($conflict)) $condition .=" and Conflict LIKE '$conflict'";
$result = mysql_query ("SELECT * FROM powderhorns WHERE $condition ", $connection);

Categories