I want a dependent select box I can load the data from my database into the select box however, when I click the show all countries when all select boxes have data only the province will return to the default data. What I need to do is when I click show all countries all the data from select box will reset to its default data and so on and so forth.
AJAX Script:
$(document).ready(function(){
//Show Province
$("#sort-country").change(function(){
var country = $(this).val();
$.ajax ({
url:"fetch_province.php",
method: "POST",
data: {country:country},
dataType: "text",
success: function(data){
$("#sort-province").html(data);
}
});
});
//Show Town
$("#sort-province").change(function(){
var country = $("#sort-country").val();
var province = $(this).val();
$.ajax ({
url:"fetch_town.php",
method: "POST",
data: {country:country, province:province},
dataType: "text",
success: function(data){
$("#sort-town").html(data);
}
});
});
//Show Barangay
$("#sort-town").change(function(){
var country = $("#sort-country").val();
var province = $("#sort-province").val();
var town = $(this).val();
$.ajax ({
url:"fetch_barangay.php",
method: "POST",
data: {country:country, province:province, town:town},
dataType: "text",
success: function(data){
$("#sort-barangay").html(data);
}
});
});
});
Fetch Province:
<?php
require "connect.php";
$output = "";
$sql = "SELECT * FROM tblLocation WHERE country='".$_POST['country']."' ORDER BY province";
$result = mysqli_query($conn, $sql);
$output = "<option value=''>Show All Province</option>";
while ($row = mysqli_fetch_array($result)) {
$output .= "<option value='".$row['province']."'>".$row['province']."</option>";
}
echo $output;
?>
Fetch Town:
<?php
require "connect.php";
$output = "";
$sql = "SELECT * FROM tblLocation WHERE country='".$_POST['country']."' AND province='".$_POST['province']."' ORDER BY town";
$result = mysqli_query($conn, $sql);
$output = "<option value=''>Show All Town</option>";
while ($row = mysqli_fetch_array($result)) {
$output .= "<option value='".$row['town']."'>".$row['town']."</option>";
}
echo $output;
?>
Fetch Barangay:
<?php
require "connect.php";
$output = "";
$sql = "SELECT * FROM tblLocation WHERE country='".$_POST['country']."' AND province='".$_POST['province']."' AND town='".$_POST['town']."' ORDER BY barangay";
$result = mysqli_query($conn, $sql);
$output = "<option value=''>Show All Barangay</option>";
while ($row = mysqli_fetch_array($result)) {
$output .= "<option value='".$row['barangay']."'>".$row['barangay']."</option>";
}
echo $output;
?>
Related
I need to get data from the database with ajax and put that data in the 'select' tag. I need to have every name in a different 'option'... View the code:
Index.php:
<label>Select:</label>
<select id="users"></select>
JS:
$(document).ready(function() {
setInterval(function() {
$.get("frombase.php", function(data) {
data = JSON.parse(data);
for (var id in data) {
$("#users").empty();
$("#users").append("<option value='"+ id +"'>"+ data[id] +"</option>")
}
});
}, 1000);
});
And frombase.php:
$sql = "SELECT * FROM `users`";
$result = mysqli_query($db, $sql);
$name = array();
while ($row = mysqli_fetch_assoc($result)) {
$name[] = $row['name'];
}
echo json_encode(array("name" => $name));
mysqli_close($db);
Look at the result (I do not need this)
(My english is not good, because I use Google Translate)
I would do in this way...
JS:
$(document).ready(function() {
$.ajax({
url :'frombase.php',
type: "POST",
dataType: "json",
success : function(data){
$("#users").empty();
$(data['options']).each(function(k,v){
$("#users").append("<option value='"+ v['id'] +"'>"+ v['name'] +"</option>");
});
},
error:function(){
alert('Error of server comunication');
}
});
});
PHP:
$db = 'YOUR CONNECTION';
$query = $db->prepare("SELECT id,name FROM users");
$query->execute();
$query->bind_result($id,$name);
while ($query->fetch()) {
$result[] = array('id'=>$id,'name'=>$name);
}
$root['options'] = $result;
$root = json_encode($root);
$db->close();
echo $root;
i have to get select option list from my database
and for this my controller is
<?php
require_once 'connexion.php';
$sql = "select * from Motif";
$stmt = sqlsrv_query($conn, $sql);
if ($stmt === false)
{
die(print_r(sqlsrv_errors() , true));
}
$data = array();
while ($row = sqlsrv_fetch_array($stmt, SQLSRV_FETCH_ASSOC))
{
$data["id"] = $row['id'];
$data["libelle"] = utf8_encode($row['libelle']);
echo json_encode($data);
}
echo json_encode($data);
exit;
?>
and my html like this
<select id="rejetselect" class="form-control">
<option value="" selected="selected"></option>
</select>
and to get values from database with ajax i did this code
var $select = $('#rejetselect');
$.ajax({
url: 'motifRejet.php',
dataType: 'json',
data: 'libelle',
success: function() {
alert('good');
},
error: function() {
alert('nooo');
}
});
so after testing all this i can see my alert in good and in my console i can see the information that i got from database but i can't see it in my select option
I'm trying to populate the second dropdown after I select the first option, nothing appears in the second dropdown.
My first select:
<select name="inst" class="form-control" required="" id="inst">
<option value=0 selected=1>Select...</option>
<?php
$sql="SELECT * FROM sapinst";
$myData=mysqli_query($GLOBALS['con'],$sql);
if (mysqli_num_rows($myData) > 0){
while ($row = mysqli_fetch_array($myData))
{
echo '<option value="' .$row["nbd"]. '">' .$row["nome"]. '</option>';
}
}
else{echo "No categories were found!";}
?>
</select>
My second select:
<select id= "sub" name="sub" class="form-control"></select>
My Script:
<script type="text/javascript">
$("#inst").change(function () {
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = '/ajax.php';
// call subcategory ajax here
$.ajax({
type: "POST",
url: url,
data: {
cat_val: cat_val
},
success: function (data)
{
$("#sub").html(data);
}
});
});
</script>
My Ajax.php file:
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST['cat_val'];
$sql = "SELECT * FROM " . $dbname . ".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($conn, $sql);
$msg = '';
if (mysqli_num_rows($result) > 0) {
while ($row = mysqli_fetch_array($result)) {
$msg =. '<option value="' . $row["nome"] . '">' . $row["nome"] . '</option>';
}
} else {
$msg .= "No categories were found!";
}
echo $msg;
mysqli_close($conn);
?>
if I try to print some thing in the Ajax php I can't...seems ajax.php won't run.
Am I calling it correctly?
Is your second ajax being called properly?
Check the console messages(in developer options, F12) for errors in ajax call.
you might want to do this as both cat_val are same. It might be giving an error. -
data: {
cat_val: cat_val_local //different variable names here.
},
Also "Select * from $TABLE_NAME(not #dbname)"
and next remove extra .[dot] here -> ".sappainel WHERE"
you can also try put console.log() in success callback and see if the success is returning any elements.
success: function (data)
{
console.log(data);
$("#sub").html(data);
}
If nothing is shown then your php might be wrong. Add an eror callback too! like this -
error: function (e)
{
console.log(e);
}
Hope this helps.
I already solved
Diferences on scrip:
<script type="text/javascript">
$("#inst").change(function(){
//get category value
var cat_val = $("#inst").val();
// put your ajax url here to fetch subcategory
var url = 'ajax.php';
// call subcategory ajax here
$.ajax({
type:"POST",
url:url,
data:{
cat_val : cat_val
},
success:function(data)
{
$("#sub").html(data);
}
});
});
</script>
On ajax.php
<?php
require_once 'edp/configdbedp.php';
$prod_cat = $_POST["cat_val"];
$sql = "SELECT * FROM ".$dbname.".sappainel WHERE nbd = '$prod_cat'";
$result = mysqli_query($GLOBALS['con'], $sql);
$msg ='';
if (mysqli_num_rows($result) > 0){
while ($row = mysqli_fetch_array($result))
{
$msg .='<option value="'. $row["nome"] .'">'. $row["nome"] .'</option>';
}
}
else{$msg .="No categories were found!";}
echo ($msg);
mysqli_close($GLOBALS['con']);
?>
This is how I build sql data and send back to ajax call:
(...)
$sql = "SELECT id_option FROM options WHERE id_win = '{$id_win}'";
$result = mysqli_query($conn, $sql);
$rows = array();
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row;
}
$data["win_data"] = $rows;
echo json_encode($data);
This is my ajax function to get options for selectpicker from DB:
$.ajax({
type: "POST",
url: ...,
data: ...,
dataType: "json",
success: function(data) {
$("#id_win").selectpicker("val", data.win_data);
// $("#id_win").selectpicker("val", [1,3];
}
});
data.win_data variable should be: [1,3]
but if I do:
console.log(JSON.stringify(data.win_data));
I get:
[{"0":"1","id_option":"1"},{"0":"3","id_option":"3"}]
What is the simplest way to get proper format array for selectpicker?
It is because $row is an array. Look: https://secure.php.net/manual/pt_BR/mysqli-result.fetch-array.php
You have to use like this:
(...)
$sql = "SELECT id_option FROM options WHERE id_win = '{$id_win}'";
$result = mysqli_query($conn, $sql);
$rows = array();
while ($row = mysqli_fetch_array($result)) {
$rows[] = $row['id_option'];
}
$data["win_data"] = $rows;
echo json_encode($data);
forget about mysqli and use PDO, it has everything you need.
$stmt = $pdo->prepare("SELECT id_option FROM options WHERE id_win = ?");
$stmt->execute([$id_win]);
$data["win_data"] = $stmt->fetchAll(PDO::FETCH_COLUMN);
echo json_encode($data);
this code is 2 times shorter and 100 times more secure
I been finding for long unable to search for it.. I have a dropdown select option call from mysql database.. I wanted when the user choose a employee from the option.. when selected.. it's list out the data from mysql database the employee data that is selected. here the code..
<select value="employee" selected="selected"> Select a employee</option>
<?php
$query = "SELECT * FROM users";
$result = mysqli_query($link,$query);
while ($row = mysqli_fetch_array($result)) {
$fname = $row["first_name"];
$lname = $row["last_name"];
echo "<option value'" . $fname . " " . $lname ."'>" . $fname . " " . $lname . "</option>";
}
?>
</select>
sorry i'm new to js.. how do I get the data from selected value?
First of all edit your page and add jquery library
<select id="listEmployee" value="employee" selected="selected"> Select a employee</option>
<?php
$query = "SELECT * FROM users";
$result = mysqli_query($link,$query);
while ($row = mysqli_fetch_array($result)) {
$fname = $row["first_name"];
$lname = $row["last_name"];
$id = $row["id"];
echo "<option value'" .$id."'>" . $fname . " " . $lname . "</option>";
}
?>
</select>
Then you should listen to select change
$( "#listEmployee" ).change(function() {
getSelectedEmplpyee();
});
Then create an ajax function that get informations about the selected employee
function getSelectedEmplpyee()
{
var selectedId = $('#listEmployee').val();
$.ajax({
type: "POST",
url: "Controller.php",
data: {selected: selectedId},
success: function(data) {
//display response
},
error: function(data) {
// display error
}
});
}
in controller.php read the id using
$id = $_POST['selected']
in controller.php run your select query and return result using echo ,
the result is stored in the variable data in your function getSelectedEmplpyee()
Try to do like this:
var selected_value = $('#your_select_id').val();
$.ajax({
type: "POST",
url: "your_url",
data: {selected: selected_value},
success: function(data) {
//display response
},
error: function(data) {
// display error
}
});