Dependent dropdown not working correctly - javascript

this is my first time on this site so I'll cut to chase.
I've been working on a fixed assets control web system using PHP, AJAX, jquery and MySQL as database (the project structure was made by following the tutorial from this website: https://www.itechempires.com/2016/07/pdo-crud-operations-using-php-bootstrap/ ), where such items are registered along with the categories to which each asset belongs, the transactions made by the users within the company and the reports generated by each transaction.
Currently I'm stuck with the dropdowns since I tried anything I could to make them work but without the results I've been looking for, which is:
in a modal there's a form where an asset is going to be added with its related information, two of those details are categories and subcategories which are handled by dependent dropdowns, the dropdown regarding to subcategories will be displayed once a category is selected.
The code snippets will be up for review which will be focused on the ones related to the dropdowns:
Tables
grupo (group or category)
id_grp (group id,autoincremented, not visible by the user)
codigo_grp (code)
nombre_grp (name)
subgeupo (subgroup or subcategory)
id_sgrp (subgroup id, autoincremented, not visible by the user)
codigo_sgrp (code)
nombre_sgrp (name)
vidaUtil_sgrp (useful life)
id_grp (group id, foreign key)
libAF.php: Contains all queries for crud operations
/*
* Get group's id and name
*
* #return $id_grp, $nombre_grp
* */
public function populateSelGrp()
{
$query = $this->db->prepare("SELECT id_grp, nombre_grp FROM grupo");
$query->execute();
$data = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
return $data;
}
/*
* Get sub-group's id and name
*
* #return $id_grp, $nombre_grp
* */
public function populateSelSgrp($id_grp)
{
$query = $this->db->prepare("SELECT * FROM subgrupo WHERE id_grp = :id_grp");
$query->bindParam("id_grp", $id_grp, PDO::PARAM_STR);
$query->execute();
$data = array();
while ($row = $query->fetch(PDO::FETCH_ASSOC)) {
$data[] = $row;
}
return $data;
}
populateSelGrp.php: loads the categories on to the parent dropdown
<?php
require 'libAF.php';
$data = "";
$object = new CRUD();
$grupos = $object->populateSelGrp();
$data .= '<select id="select_grp" class="form-control" onchange="populateSelSgrp()">';
$data .= '<option value="0" disabled selected>Escoja grupo</option>';
if (count($grupos) > 0) {
foreach ($grupos as $grupo) {
$data .= '<option id="selected_grp" value="' . $grupo['id_grp'] . '"> ' . $grupo['nombre_grp'] . '</option>';
}
}
else
{
$data .= '<option>No hay opciones disponibles</option>';
}
$data .= '</select>';
echo $data;
?>
populateSelSgrp.php: loads the subcategories on to the child dropdown
<?php
require 'libAF.php';
if (isset($_POST['id_grp']) && isset($_POST['id_grp']) != "") {
$id_grp = $_POST['id_grp'];
$data = "";
$object = new CRUD();
$subgrupos = $object->populateSelSgrp($id_grp);
$data .= '<label for="select_sgrp">Sub-grupo</label>';
$data .= '<select id="select_sgrp" class="form-control">';
$data .= '<option value="0" disabled selected>Escoja sub-grupo</option>';
if (count($subgrupos) > 0) {
foreach ($subgrupos as $subgrupo) {
$data .= '<option value="' . $subgrupo['id_sgrp'] . '"> ' . $subgrupo['nombre_sgrp'] . '</option>';
}
}
else
{
$data .= '<option>No hay opciones disponibles</option>';
}
$data .= '</select>';
echo $data;
}
?>
scptAF.js: Contains the scripts needed to make the inputs work
function populateSelGrp(){
$.get("ajax/activoFijo/populateSelGrp.php", {
},
function (data, status) {
//load options to dropdown list
$(".option_grp").html(data);
}
);
}
function populateSelSgrp(id_grp){
$.ajax({
url: "ajax/activoFijo/populateSelSgrp.php",
method: "POST",
data:{id_grp: id_grp},
success:function(data){
$(".option_sgrp").html(data);
}
})
}
activos.php (assets): visible page where the user adds, removes or updates an asset.
<div class="form-group">
<label for="select_grp">Grupo</label>
<div class="option_grp"></div>
</div>
<div class="form-group">
<div class="option_sgrp"></div>
</div>

I finally found a solution for this mess, was a little code I had to add to the javaScript file to send the id to the second dropdown. Although I finally fixed my problem, I'd like to see other suggestions on how to tackle this problem.
Here's my snippet
scptAF.js
function populateSelGrp() {
$.get("ajax/activoFijo/populateSelGrp.php", {
},
function (data, status) {
//load options to dropdown list
$(".option_grp").html(data);
}
);
}
function changeGrpId(){
var id_grp = document.getElementById("select_grp").value;
populateSelSgrp(id_grp);
}
function populateSelSgrp(id_grp) {
$.ajax({
url: "ajax/activoFijo/populateSelSgrp.php",
method: "POST",
data:{id_grp: id_grp},
success:function(data){
$(".option_sgrp").html(data);
}
})
}

Related

Onchange populate different dropdown based on value

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']);
?>

Get data from Database Using Ajax and PHP and Return Result as Dropdown list

I have the idea of what i wanted but need assistance on how to get it done.Below is the scenerio: I have a two dropdwon. The First dropdown is fetched from the DB, which works fine. At the change event of the first dropdown,the system should go to the Database, and fetch the result into the next dropdown. see what I have done so far for assistance:
JQUERY SECTION
<script type="text/javascript" src="includes/scripts/newJquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$("#locate").change(function(){
var selectedloc = $("#locate option:selected").val();
$.ajax({type: "POST",url:"process-loc.php",data:{loca:selectedloc}}).done(function(data){
var ans=jQuery.parse(data);
//using php-mysql before
var ps = ans.res;
$("#subloc").html(ps);
});
});
});
</script>
FrontEnd(HTML)
<tr>
<th>Primary Location:</th>
<?php
$result = mysqli_query($connection,"SELECT * FROM tab_location");?>
<td>
<select name="locate" class="form-control" id="locate">
<option>Select Main Location</option>
<?php while($rw = mysqli_fetch_array($result)){ ?>
<option value="<?php echo $rw['location_name'];?>"><?php echo $rw['location_name'];?></option>
<?php };?>
</select>
</td>
</tr>
<tr>
<th>Sub Location:</th>
<td id="subloc"></td>
</tr>
Process-loc.php
if(isset($_POST["loca"])){
include 'includes/session.php';
include 'includes/db_connection.php';
include 'includes/functions.php';
$main = $_POST["loca"];
$gets = "SELECT * FROM tab_fltlocation WHERE mainloc='".$main."'";
$get = mysqli_query($connection,$gets);
$gt = mysqli_fetch_array($get);
//$nos= $gt['opsNo'];
if(mysqli_num_rows($get)>=0)
{
echo json_encode(array("res"=>$gt));//or do a dropdown using <select name='subloc'><option value=$gt['loc']>$gt['loc']</option></select>
}else{
echo json_encode(array("res"=>"0"));
}
}
?>
This is what I wants to be displayed on the Front End page for the use:
$gt['loc']
How can I achieve this.
$query = "
SELECT
tariff_name
FROM tariff_setting";
$result = mysqli_query($this->_connection, $query);
while ($row = mysqli_fetch_assoc($result))
$response[] = $row['tariff_name'];
}
$tarrifList = json_encode($response);
// $tarrifList is the response and sent it in json encode format and decode on ajax success
// Javascript Process
var obj = JSON.parse(resdata);
var areaOption = "<option value=''>Select State</option>";
for (var i = 0; i < obj.length; i++) {
areaOption += '<option value="' + obj[i] + '">' + obj[i] + '</option>'
}
$("#patientSelectState").html(areaOption);
You can change your AJAX processor to do this:
Process-loc.php
/* Above code the same */
if(mysqli_num_rows($get)>=0) {
$out = '<select id="selSubLoc"><option value="">Choose One:</option>';
foreach($gt AS $loc){
$seld = ($_POST['loca'] == $loc) ' selected' ? : '' ;
$out .= '<option value="' .$loc. '" ' .$seld. '>' .$loc. '</option>';
}
$out .= '</select>';
}else{
$out = 0;
}
echo $out;
And change your front-end code's AJAX routine to be like this:
$.ajax({
type: "POST",
url:"process-loc.php",
data:{loca:selectedloc}
}).done(function(recd){
$("#subloc").html(recd);
});
The data received back from PHP will be in HTML format unless you use dataType: to change it, so you can build the HTML over on the PHP side and then just plop it into the #subloc table cell.
On the event of the first box call the function containing the ajax which would retrieve information from the database. This ajax call will get data according to the first input.
Now query your database and echo the results in a foreach loop(you can make a tag there only).
In the ajax 'success:' catch the data and display it.
//from the database
foreach ($info as $product)
{
echo "<option value=".$product['childsticker_id'].">".$product['name']</option>";
}
//ajax call page
success: function(result)
{
$("#states").html(result);
}
http://www.9lessons.info/2010/08/dynamic-dependent-select-box-using.html

div does not reload the changed content even with 'load'

I have been working on this for some time now. I have a php file that has a div which reads a directory and loads the files in the directory into a dropdown. When the user selects from the file the file gets selected and teh operation is performed. However, the file name does not disappear from the dropdown until the page is refreshed. I have tried '.load' and it doesn't work. As in, the content of the div does not get updated.
My code is as follows:
This is the PHP file:
<div id="mgA" class="form-group">
<label>Management Address:</label>
<?php
$path = "/licenses/ve/address/unused";
clearstatcache();
$files = array();
$handle = opendir($path);
echo '<select required id="mgmtAdd" class="form-control select2" style="width: 100%;">';
while ($file = readdir($handle)) {
if (substr($file,0,1) != ".") {
$files[]=$file;
}
echo "<option selected = 'selected' value='0'>Select</option>";
natsort($files); //sorting
foreach($files as $file){
echo "<option value ='$file'>$file</option>";
}
echo '</select>';
if (is_dir_empty($path)) {
echo "Max no of hosts already created";
}
function is_dir_empty($path) {
if (!is_readable($path)) return NULL;
return (count(scandir($path)) == 2);
}
closedir($handle);?>
This is the button which on click the div should reload all the contents again:
$( "#vServer").on( "click", function(e) {
e.preventDefault();
$("#mgA").load(virtualDialog);
alert("refreshed");
virtualDialog.dialog( "open" );
});
Please let me know if anyone has any idea, any help is appreciated! Thank you!
As epascarillo has pointed out, you are using load() incorrectly. This may be more in line with what you wish to do but I did not test (or even check very closely) your PHP code.
I am also assuming that the div #mgA is the content of the jQueryUI dialog that you are opening with virtualDialog.
javascript/jQuery:
$( "#vServer").on( "click", function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: 'ajax-reload.php',
success: function(d){
$("#mgA").html(d);
virtualDialog.dialog( "open" );
}
});
});
ajax-reload.php
<?php
$path = "/licenses/ve/address/unused";
clearstatcache();
$files = array();
$handle = opendir($path);
$out = '<select required id="mgmtAdd" class="form-control select2" style="width: 100%;">';
while ($file = readdir($handle)) {
if (substr($file,0,1) != ".") {
$files[]=$file;
}
$out .= "<option selected = 'selected' value='0'>Select</option>";
natsort($files); //sorting
foreach($files as $file){
echo "<option value ='$file'>$file</option>";
}
} //<=== this brace was missing
$out .= '</select>';
if (is_dir_empty($path)) {
$out = "Max no of hosts already created";
}
function is_dir_empty($path) {
if (!is_readable($path)) return NULL;
return (count(scandir($path)) == 2);
}
closedir($handle);
echo $out;
?>
See these additional examples of simple AJAX -- sometimes it helps to see the really simple examples:
AJAX request callback using jQuery

Yii renderpartial Eselect2 Design it's not Working properly

I want to Show My data in Popup,Once User Selected Department Showing that
Staff's names related to user Selected Department using Ajax,Geeting
data's Correctly But Am showing that Staff's names in Eselect2 Widget
Multiple option in Yii,that Eselect2 Design Not coming Its showing normal
Select Dropdown user Choose multiple choice using ctrl Keys .
My Codings, in that Div staff I am showing that eselect2 widget data's.
Ajax Coding
<div id ="staffs></div>
function selectstaff(id)
{
$.ajax({
type: 'POST',
url: '<?php echo Yii::app()->createAbsoluteUrl("user/users/ajaxselectstaff"); ?>',
data: 'id=' + id,
success: function (packages) {
$('#staffs').html(packages);
}
});
}
Controller Coding
public function actionAjaxselectstaff() {
$id = Yii::app()->request->getPost('id');
$model = Users::model()->getAllStaffDepartment($id);
$this->renderPartial('ajaxselect', array('model' => $model));
}
MOdel Coding,
public function getAllStaffDepartment($id, $type = '') {
$model = UserAccount::model()->findAll('department_code=:id', array(':id' => $id));
$userid = "";
$result = "";
if (isset($model)) {
foreach ($model as $data) {
$userid .= $data->user_id . ",";
}
}
$userid = trim($userid, ',');
if ($userid != "") {
$criteria = new CDbCriteria();
$criteria->condition = "user_role_id!=" . Yii::app()->mconstant->CONST_FIVE . " AND user_role_id!= " . Yii::app()->mconstant->CONST_SIX . " AND user_role_id!= " . Yii::app()->mconstant->CONST_NINE . " AND user_id IN (" . $userid . ")";
$result = Users::model()->findAll($criteria);
$data = CHtml::listData($result, 'user_id', 'real_name');
return $data;
} else {
return false;
}
}
Ajaxselect page:
<?php
Yii::app()->clientScript->scriptMap['jquery.js'] = false;
Yii::app()->clientScript->scriptMap['jquery.min.js'] = false;
if ($model) {
?>
<?php
$this->widget('ext.select2.ESelect2', array(
'name' => 'users',
'id' => 'users',
'data' => $model,
'htmlOptions' => array(
'multiple' => true,
'placeholder' => 'Select Users',
),
));
?>
<?php
} else {
echo "No Staff's Found";
}
?>
what's wrong in my code ? Am changes the page to render eselect2 widget design getting properly but render partial eselect2 design not getting,
There is small change in controller which is mention below.
public function actionAjaxselectstaff() {
$id = Yii::app()->request->getPost('id');
$model = Users::model()->getAllStaffDepartment($id);
$this->renderPartial('ajaxselect', array('model' => $model) ,false , true);
}
Please find description of third and forth paramerter of renderPartial in below link : http://www.yiiframework.com/doc/api/1.1/CController#renderPartial-detail

How to get data from php in JS on a native android app?

I'm working on a cross-platform application and I got some troubles with my data.
Actually I have a full website with a lot of php and I'm working with the Intel XDK to make a native application of this website.
But here is the thing, I know I can execute php on my native app, so i'm trying to execute few scripts directly on my server and to take back the result with an ajax request.
Here is the code : (Javascript)
var games = location.search;
var res = games.split("=");
$.ajax({ //create an ajax request to a page that prints the address.
url: "http://tonight-app.fr/php/mobile_app/getGamesLists.php", //url for the address page
data: {"name": res[1]},
success: function(result){
var games = result; //create a variable and give it the value of the response data
var gamesSplit = games.split(";");
for(i=0;i<gamesSplit.length;i++){
var gamesSplit2 = gamesSplit[i].split(",");
test(gamesSplit2[0]);
}
}
});
function test(gamesSplit2) {
console.log(gamesSplit2);
var ul = document.createElement("ul");
ul.id = "email-list";
ul.innerHTML = gamesSplit2;
document.getElementById('test').appendChild(ul);
}
Here is the php on the server (to this address mention in the url of the ajax)
<?php
require_once("connect_database.php");
mysqli_set_charset($con, "utf8");
$name = $_GET["name"];
$sql="SELECT * FROM `games`";
$reponse = mysqli_query($con, $sql);
while ($row = mysqli_fetch_array($reponse, MYSQL_NUM)) {
if ($row[2] == $name) {
echo $result = '
<a href="gamesReceipes.php?id=',$row[0],'">
<li class="unread clickable-row">
<div class="name">
',$row[1],'
</div>
<div class="message">
Voir la préparation
</div>
</li>;';
}
}
echo $result;
?>
So to explain, I'm executing my php script which gave me the $result and i'm supposed to display this result in my Ajax.
It's working on the emulator in the Intel XDK but not after when i'm building the app ! (Of course my phone have the 4g activated)
It's supposed to be like this on the display :
[
I hope you can understand my problem here ... Thanks guys !
By this link :
https://software.intel.com/en-us/articles/cordova-whitelisting-with-intel-xdk-for-ajax-and-launching-external-apps
Thanks yo #OldGeeksGuide who gave me this link ! I just had to add the link to my script in the intel xdk and it worked ! Thanks !
You appear to be trying to echo the same thing twice. returning data to an AJAX call should be done once and the last thing you do in the script.
<?php
require_once("connect_database.php");
mysqli_set_charset($con, "utf8");
$name = $_GET["name"];
$sql="SELECT * FROM `games`";
$reponse = mysqli_query($con, $sql);
// init the $result var
$result = '';
// incorrect parameter constant
//while ($row = mysqli_fetch_array($reponse, MYSQL_NUM)) {
while ($row = mysqli_fetch_array($reponse, MYSQLI_NUM)) {
if ($row[2] == $name) {
//echo $result = '
$result .= '
<a href="gamesReceipes.php?id=' . $row[0] . '">
<li class="unread clickable-row">
<div class="name">
' . $row[1] . '
</div>
<div class="message">
Voir la préparation
</div>
</li>;';
}
}
echo $result;
?>
You could also simplify this.
As you are passing the name of the game to this script you could add that to the query as a search criteria like so and then remove a lot of unnecessary processing.
<?php
require_once("connect_database.php");
mysqli_set_charset($con, "utf8");
// init the $result var
$result = '';
if ( isset($_GET['name'] ) {
$name = $_GET["name"];
$sql="SELECT * FROM `games` WHERE `name` = '$name'";
$reponse = mysqli_query($con, $sql);
// I assume there is only one ro w that contains this name
// so the loop is not required now
while ($row = mysqli_fetch_array($reponse, MYSQLI_NUM)) {
$result .= '
<a href="gamesReceipes.php?id=' . $row[0] . '">
<li class="unread clickable-row">
<div class="name">' . $row[1] . '</div>
<div class="message">Voir la préparation</div>
</li>;';
}
} else {
$result = 'No name parameter passed';
}
echo $result;
exit;
?>

Categories

Resources