How to load data dynamically in multiselect Dropdown using Select2 - javascript

I am trying to take the data dynamically from the Sql to a Dropdown that is in a modal window (Bootstrap) in order to update the data using Select2, I implemented the suggested code dropdownParent: $('#para2') from the official page but when I open the modal window the Dropdown appear empty I am not having the expected results, please help me to correct this problem.
HTML
<div class="row">
<div class="col-md-6 col-sm-6 col-lg-5 form-group">
<label class="col-form-label col-md-4 col-sm-2 label-align" for="descx">Para <i class="fa fa-users"></i></label>
<select name="acompanantes" id="para2" class="nuevo" multiple="multiple" data-placeholder="Para" style="width: 95%">
<option value=""></option>
{{empleado}}
</select>
</div>
</div>
PHP
function buscaMemoPorID(){
$soloID = $_POST["idMemo"];
$query = " SELECT TB_Memo.ID_Memo, TB_Memo.Fecha_Creacion, a.Nombres +' '+ a.Apellidos as Destinatarios, b.Nombres + ' ' + b.Apellidos as Remitente, TB_Memo.Asunto, TB_Memo.Contenido, TB_Memo.ID_TipoMemo, TB_Memo.ID_EstadoMemo, TB_Memo.Fecha_Envio, c.Descripcion, TB_Memo.ID_Memorandum, TB_Destinatario.ID_Empleado as Para
from TB_Memo
inner join TB_Destinatario on TB_Memo.ID_Memo = TB_Destinatario.ID_Memo
inner join TB_Remitente on TB_Memo.ID_Memo = TB_Remitente.ID_Memo
inner join [IHTT_RRHH].[dbo].[TB_Empleados] a on TB_Destinatario.ID_Empleado = a.ID_Empleado
inner join [IHTT_RRHH].[dbo].[TB_Empleados] b on TB_Remitente.ID_Empleado = b.ID_Empleado
left outer join [IHTT_MEMORANDUM].[dbo].[TB_EstadoDestinatario] c on TB_Memo.ID_EstadoDestinatario = c.ID_EstadoDestinatario
Where TB_Memo.ID_Memo = $soloID";
$p = array();
$data = $this->select($query, $p );
$datos[1]=count($data);
$datos[0]=array();
for($i=0; $i<count($data); $i++){
$datos[0][$i] = array("ult" =>1, "num" =>$data[$i]["ID_Memo"], "nome"=>$data[$i]["ID_Memorandum"],"tipoMe" =>$data[$i]["ID_TipoMemo"], "estaMe" =>$data[$i]["ID_EstadoMemo"], "asunto" =>$data[$i]["Asunto"], "contenido" =>$data[$i]["Contenido"], "fechEn" =>$data[$i]["Fecha_Envio"], "fechCre" =>$data[$i]["Fecha_Creacion"], "De" =>$data[$i]["Remitente"], "Para" =>$data[$i]["Para"], "estado"=>$data[$i]["Descripcion"], "Destinatarios"=>$data[$i]["Destinatarios"]);
}
echo json_encode($datos);
}
JS
function cargaMemoEspecifico(idmemo){
var cant = $("#mostrar").val();
var form_data = new FormData();
form_data.append("action","buscaMemoPorID");
form_data.append("idMemo",idmemo);
$.ajax({
url: 'api_con.php',
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
var area = data[0];
if(data[1]>0 ){
var detalle='';
var cantidad=80;
var total=0;
var num=1;
for(i=0; i<area.length; i++){
let datos = tinymce.get("mensaje2").setContent(area[i].contenido);
$("#modalconsulta2").modal("show");
$("#buscab2").val(area[i].De);
$("#para2").append("<option value='" + area[i].Para + "'>" + area[i].Destinatarios + "</option>");
$("#modal-asunto").val(area[i].asunto);
$("#modal-fecha").val(area[i].fechCre);
$("#mensaje2").val(area[i].contenido);
$("#idMemo").val(area[i].num);
}

Related

How to dynamically load Sql data into Dropdown using Select2

I am trying to take the data dynamically from the Sql DB to a Dropdown that is in a modal window (Bootstrap) in order to update the data using Select2, I implemented the suggested code dropdownParent: $('#para2') from the official page but when I open the modal window the Dropdown appear empty I am not having the expected results, please help me to correct this problem.
HTML
<div class="row">
<div class="col-md-6 col-sm-6 col-lg-5 form-group">
<label class="col-form-label col-md-4 col-sm-2 label-align" for="descx">Para <i class="fa fa-users"></i></label>
<select name="acompanantes" id="para2" class="nuevo" multiple="multiple" data-placeholder="Para" style="width: 95%">
<option value=""></option>
{{empleado}}
</select>
</div>
</div>
PHP
function buscaMemoPorID(){
$soloID = $_POST["idMemo"];
$query = " SELECT TB_Memo.ID_Memo, TB_Memo.Fecha_Creacion, a.Nombres +' '+ a.Apellidos as Destinatarios, b.Nombres + ' ' + b.Apellidos as Remitente, TB_Memo.Asunto, TB_Memo.Contenido, TB_Memo.ID_TipoMemo, TB_Memo.ID_EstadoMemo, TB_Memo.Fecha_Envio, c.Descripcion, TB_Memo.ID_Memorandum, TB_Destinatario.ID_Empleado as Para
from TB_Memo
inner join TB_Destinatario on TB_Memo.ID_Memo = TB_Destinatario.ID_Memo
inner join TB_Remitente on TB_Memo.ID_Memo = TB_Remitente.ID_Memo
inner join [IHTT_RRHH].[dbo].[TB_Empleados] a on TB_Destinatario.ID_Empleado = a.ID_Empleado
inner join [IHTT_RRHH].[dbo].[TB_Empleados] b on TB_Remitente.ID_Empleado = b.ID_Empleado
left outer join [IHTT_MEMORANDUM].[dbo].[TB_EstadoDestinatario] c on TB_Memo.ID_EstadoDestinatario = c.ID_EstadoDestinatario
Where TB_Memo.ID_Memo = $soloID";
$p = array();
$data = $this->select($query, $p );
$datos[1]=count($data);
$datos[0]=array();
for($i=0; $i<count($data); $i++){
$datos[0][$i] = array("ult" =>1, "num" =>$data[$i]["ID_Memo"], "nome"=>$data[$i]["ID_Memorandum"],"tipoMe" =>$data[$i]["ID_TipoMemo"], "estaMe" =>$data[$i]["ID_EstadoMemo"], "asunto" =>$data[$i]["Asunto"], "contenido" =>$data[$i]["Contenido"], "fechEn" =>$data[$i]["Fecha_Envio"], "fechCre" =>$data[$i]["Fecha_Creacion"], "De" =>$data[$i]["Remitente"], "Para" =>$data[$i]["Para"], "estado"=>$data[$i]["Descripcion"], "Destinatarios"=>$data[$i]["Destinatarios"]);
}
echo json_encode($datos);
}
JS
function cargaMemoEspecifico(idmemo){
var cant = $("#mostrar").val();
var form_data = new FormData();
form_data.append("action","buscaMemoPorID");
form_data.append("idMemo",idmemo);
$.ajax({
url: 'api_con.php',
dataType: 'json',
cache: false,
contentType: false,
processData: false,
data: form_data,
type: 'post',
success: function(data){
var area = data[0];
if(data[1]>0 ){
var detalle='';
var cantidad=80;
var total=0;
var num=1;
for(i=0; i<area.length; i++){
let datos = tinymce.get("mensaje2").setContent(area[i].contenido);
$("#modalconsulta2").modal("show");
$("#buscab2").val(area[i].De);
$("#para2").append("<option value='" + area[i].Para + "'>" + area[i].Destinatarios + "</option>");
$("#modal-asunto").val(area[i].asunto);
$("#modal-fecha").val(area[i].fechCre);
$("#mensaje2").val(area[i].contenido);
$("#idMemo").val(area[i].num);
}
} else {
detalle +='<tr><td colspan="8">NO HAY DATOS EN ESTE MOMENTO.........</td></tr>';
}
}
}).error(function(r){
console.log("Error-->",r.responseText);
});
}

How can I link data to a select element in AJAX method?

I have a problem wherein I cannot put the data inside select element and make an option using the ID to append on what is inside my ajax. I got the data and it is showing in an input element but when I switched it into select element it doesn't work.
Here is the image of my form
JQuery / Ajax code
function ToolsChange(element) {
let tools_id = $(element).val();
if (tools_id) {
$.ajax({
type: "post",
url: "form_JSON_approach.php",
data: {
"tools_id": tools_id
},
success: function(response) {
var dataSplit = response;
console.log(response);
var shouldSplit = dataSplit.split("#");
var shouldNotSplit = dataSplit.split();
console.log(shouldSplit);
console.log(shouldSplit[0]);
console.log(shouldSplit[1]);
console.log(shouldSplit[2]);
$("#sel_control_num").val(shouldSplit[0]);
var specs = [];
for (i = 1; i < shouldSplit.length; i += 3) {
specs.push(shouldSplit[i])
}
$("#sel_tools_spec").val(specs.join(', '));
$("#sel_tools_id").val(shouldSplit[2]);
}
});
}
}
HTML code(I had to comment select element because it is not showing the data)
<div class="form-group">
<label> Tools Specification: </label>
<input id="sel_tools_spec" class="form-control" name="tools_specification"
data-live-search="true" readonly>
<!-- <select id="sel_tools_spec" class="form-control selectpicker" data-live-search="true">
</select> -->
</div>
PHP code
<?php
include("../include/connect.php");
if(isset($_POST['tools_id'])){
$ID = $_POST['tools_id'];
$query = "SELECT tools_masterlist.control_no, tools_masterlist.tools_id,
tools_masterlist.tools_name,
tools_spec.model_num,tools_spec.model_num_val, tools_spec.status
FROM tools_masterlist LEFT JOIN tools_spec ON tools_masterlist.tools_id = tools_spec.tools_id
LEFT JOIN tools_registration ON tools_masterlist.control_no = tools_registration.reg_input
WHERE status = 1 AND tools_name = '$ID'";
$con->next_result();
// $result=mysqli_query($con, "CALL GetAjaxForToolsRegistration('$ID')");
$result=mysqli_query($con, $query);
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
// echo $row['control_no'] . "#" . $row['model_num'] . "#" . $row['tools_id'] ."#";
echo $row['control_no'] . "#" . '<option value="'.$row['tools_id'].'">'.
$row['model_num'] .'</option>' . "#" . $row['tools_id'] ."#";
}
}
else
{
}
}
?>
Don't need to split() or even return your response using echo ... #... #... .. Ok here is what you should do
The main idea in my code is: returning all the data from php/database
then control it in js/ajax and this will happen by using dataType : 'json' and echo json_encode($data)
in php
$return_result = [];
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_assoc($result))
{
$return_result[] = $row;
}
}
else
{
$return_result['error'] = 'error';
}
echo json_encode($return_result);
in javascript (ajax)
$.ajax({
type: "post",
url: "form_JSON_approach.php",
dataType : 'json', // <<<<<<<<<<< here
data: {
"tools_id": tools_id
},
success: function(response) {
if(!response.error){
//console.log(response);
$.each(response , function(index , val){
// here you can start do your stuff append() or anything you want
console.log(val.control_no);
console.log(val.tools_id);
});
}else{
console.log('You Have Error , There is Zero data');
}
}
});
You are appending all datas at onces instead inside for-loop you can directly append options inside your selectpicker and refresh it.
Demo Code :
$("#sel_tools_spec").selectpicker() //intialize on load
ToolsChange() //just for demo..
function ToolsChange(element) {
/*let tools_id = $(element).val();
if (tools_id) {
$.ajax({
type: "post",
url: "form_JSON_approach.php",
data: {
"tools_id": tools_id
},
success: function(response) {*/
//other codes....
$("#sel_tools_spec").html('');
//suppose data look like this...
var shouldSplit = ["1", "<option>A</option>", "1001", "2", "<option>B</option>", "1001"]
for (i = 1; i < shouldSplit.length; i += 3) {
//append options inside select-box
$("#sel_tools_spec").append(shouldSplit[i]);
}
$("#sel_tools_spec").selectpicker('refresh'); //refresh it
/* }
});*/
}
<link rel="stylesheet " type="text/css" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/css/bootstrap-select.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.12.2/js/bootstrap-select.min.js"></script>
<div class="form-group">
<label> Tools Specification: </label>
<select id="sel_tools_spec" class="form-control selectpicker" data-live-search="true">
</select>
</div>
Since you are using bootstrap. Just do the following
$("#sel_tools_spec").empty().append('<option value="ID">LABEL</option>').selectpicker('refresh');
Source: how to append options in select bootstrap?

Getting the selected value and rest of the value in the drop down list on onchange

I want to display the selected value of that particular id in a drop down list on clicking the edit button of that id along with rest of the values in the drop down list which enable to update the selected value to some other value in the drop down list on updation.
edit.php
<div class="row">
<div class="form-group">
<label class="control-label col-md-3">Category</label>
<div class="col-md-4">
<select class="form-control" name="project" id="project" required>
</select>
</div>
</div>
</div>
$("#type").change(function() {
var id = $(this).val(); //gives the type value
var dataString = 'id='+ id;
var editid = document.getElementById("editidhidden").value; //editidhidden gives the id
if (id=="dir") {
$.ajax({
type: "POST",
url: "edit_ajax.php",
data: {
id: id,
editid: editid,
dir :1,
},
cache: false,
success: function(html) {
$("#project").html(html);
}
});
}
});
edit_ajax.php
if($_POST['dir'])
{
$id=$_POST['id'];
$editid=$_POST['editid'];
$sql="SELECT * FROM project WHERE direct_type='$id'";
$result=$conn->query($sql);
//echo '<option selected="selected" value="">'.$roweditcategory['value'].'</option>';
while($row=$result->fetch_assoc())
{
$sqleditcategory="SELECT * FROM booking WHERE id='$editid'";
$resulteditcategory=$conn->query($sqleditcategory);
$roweditcategory=$resulteditcategory->fetch_assoc();
$id=$row['direct_intcode'];
$data=$row['direct_name'];
if($roweditcategory['value']==$id)
{
echo '<option value="'.$id.'" selected="selected">'.$data.'</option>';
}
echo '<option value="'.$id.'">'.$data.'</option>';
}
}

Function is not defined when call Js function in PHP Laravel

I'm working on a Laravel project. In my blade view, I have a Javascript function like this:
<script type="text/javascript">
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + emptyDropDown).empty();
$("#" + emptyDropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + emptyDropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
</script>
Then, I call this function in the body tag and pass two php parameters to it:
<?php echo "<script> autoFill('$dropDown', '$emptyDropDown'); </script>"; ?>
But when I run this, I got a error: "Uncaught ReferenceError: autoFill is not defined".
Here is my full code in blade view if you want:
<body>
<div class="flex-center position-ref full-height">
<div class="content">
<div class="title m-b-md">
Activiti Form
</div>
#if(isset($formDataResult) && isset($dropdownValue))
<div class="links">
<form action="{{ url('handle-form') }}" method="POST">
<!--Loop form data and call components to render form-->
#foreach($formDataResult as $formDataValue)
<div class="links">
#if($formDataValue['type'] == 'select')
#if(array_key_exists('description',$formDataValue))
<?php
$dropDown = $formDataValue['name']
?>
#component('components/InputSelect',[
'name' => $formDataValue['label'],
'id' => $formDataValue['name'],
'enumData' => $dropdownValue
])
#endcomponent
#else
<?php
$emptyDropDown = $formDataValue['name'];
?>
#component('components/EmptyInputSelect',[
'name' => $formDataValue['label'],
'id' => $formDataValue['name']
])
#endcomponent
#endif
#elseif($formDataValue['type'] == 'text')
#component('components/InputText',[
'name' => $formDataValue['label'],
'id' => $formDataValue['name'],
'type'=>$formDataValue['type']
])
#endcomponent
#endif
<br>
</div>
#endforeach
<?php echo "<script> autoFill('$dropDown', '$emptyDropDown'); </script>"; ?>
<!--Hidden input to store task id-->
#component('components/HiddenInput',[
'id' => $taskId
])
#endcomponent
<div>
<input type="reset" value="Reset Form">
<button type="submit">Complete Task</button>
</div>
</form>
</div>
<!--If don't have form data, show error alert-->
#else
<div class="alert">
<span class="closebtn" onclick="this.parentElement.style.display='none';">×</span>
<strong>Notice!</strong> There are no tasks at this moment!
</div>
#endif
</div>
</div>
</body>
<script type="text/javascript">
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + emptyDropDown).empty();
$("#" + emptyDropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + emptyDropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
</script>
How I can fix this?
Thank you very much!
You are trying to call the function before you define it. Put the <script type="text/javascript">...</script> defining the function before your <script> autoFill('$dropDown', '$emptyDropDown'); </script> which tries to call it.
You can read js value to using PHP. But you can print js value to HTML screen.
You have a <span> or <div> tag with class or id attribute then you can place your value inside that.
Here is your js functionality
<script>
// whatever value you need in your js from PHP. you need to below code.
let dropdown = <?php echo $dropDown; ?>
let emptyDropdown = <?php echo $emptyDropDown; ?>
// now pass your js variables here.
function autoFill (dropDown, emptyDropDown) {
$("#" + dropDown ).change(function() {
let $this = $(this);
$.ajax({
type: "GET",
url: "https://api.myjson.com/bins/bcnss",
success: function(response){
var dataLength = response.length;
$("#" + emptyDropDown).empty();
$("#" + emptyDropDown).append("<option value=''>Select</option>");
for( var i = 0; i< dataLength; i++){
var id = response[i].id;
var name = response[i].name;
$("#" + emptyDropDown).append("<option value='"+id+"'>" + name + " </option>");
}
}
});
});
}
</script>

Getting the data from database using a drop down

here i have written the code for a functionality using jquery-ajax in CODEIGNITER where i need to pass the value of the drop down to the database using 'ajax post method' execute a query and get and display the results/data in the same view page using onChange, but the problem is onChange no change is visible.
Please help me out on this.
view.php
<div class="col-sm-6 form-group">
<select class="chosen-select form-control" name="ProductCategoryID" id="item_code" value="<?php echo set_value('ProductCategoryID'); ?>" required>
<option>Select Item code</option>
<?php
foreach($itemlist as $row)
{
echo '<option value="'.$row->ItemCode.'">'.$row->ItemCode.'</option>';
}
?>
</select>
</div>
<div class="col-sm-12 form-group" id="description">
</div>
<script src="<?php echo base_url("assets/js/jquery-1.10.2.js"); ?>" type="text/javascript"></script>
<script type="text/javascript">
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#item_code').append('<textarea value="' + id + '">' + name + '</textarea>');
}
});
$('#item_code').trigger('chosen:updated');
});
</script>
Controller.php
<?php
class Ajax extends CI_Controller {
public function __construct()
{
parent::__construct();
$this->load->helper(array('form', 'url'));
$this->load->library(array('session', 'form_validation'));
$this->load->database();
$this->load->model('Gst_model');
$this->load->model('User_model');
$this->load->model('Report_model');
$this->load->helper('url');
}
function get_description()
{
$id = $this->input->post('id');
echo(json_encode($this->Report_model->get_description($id)));
}
}
Model.php
function get_description($item_code)
{
$result = $this->db->where('ItemCode', $item_code)->get('gst_itemmaster')->result();
$id = array('0');
$name = array('0');
for ($i=0; $i<count($result); $i++)
{
array_push($id, $result[$i]->ItemDescription);
array_push($name, $result[$i]->ItemDescription);
}
return array_combine($id, $name);
}
Your problem is that updating chosen-select dropdowns is a bit tricky. After you've updated your option list you have to call something like $('.my_select_box').trigger('chosen:updated'); Take a look at the chosen-select docs here.
Just put this after your ajax call at the end of your change() function:
$('#item_code').change(function(){
var item_code = $(this).val();
$("#description > option").remove();
$.ajax({
type: "POST",
url: "<?php echo site_url('Ajax/get_description'); ?>",
data: {id: item_code},
dataType: 'json',
success:function(data){
$.each(data,function(k, v){
var t_area = $('<textarea />');
t_area.val(k);
t_area.text(v);
$('#description').append(t_area);
});
$('#state').append('<textarea value="' + id + '">' + name + '</option>');
}
});
$('#item_code').trigger('chosen:updated');
});

Categories

Resources