How to dynamically load Sql data into Dropdown using Select2 - javascript

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);
});
}

Related

How to load data dynamically in multiselect Dropdown using Select2

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);
}

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?

How to get a selected value from HTML and handle it in js or php?

I have created an array of events and now I have a filter by location dropdown. How do I get the value selected in the dropdown and handle it in js or php? Which one would it be better so it shows events from that location and not all the events. I have have different files one for displaying the events (events.js and events.php) and the other files (filterevents.js and filter events.php) this is what I want to handle the filtering in.
HTML
<div class="events">
<form method="POST" id="eventForm">
Filter By Location<br/>
<select name="Locations">
<option value="Leeds">Leeds</option>
<option value="Newcastle">Newcastle</option>
<option value="London">London</option>
</select>
<input type="submit" name="submit" value="Search"/>
</form>
<div class="eventname"><!--obj.eventname--></div>
<div class="date"><!--obj.date--></div>
<div class="time"><!--obj.time--></div>
<div class="location"><!--obj.location--></div>
<p id="error" class="errormessage"></p>
<p id="allevents" class="postmessage"></p>
</div>
events.php
<?php
require_once('checklog.php');
require_once("db_connect.php");
require_once("functions.php");
session_start();
// Print out existing events
$query = "SELECT eventname, date, time, location FROM events ORDER BY eventname";
$result = mysqli_query($db_server, $query);
if (!$result)
die("Database access failed: " . mysqli_error($db_server));
while ($row = mysqli_fetch_array($result)) {
$events[] = $row;
}
mysqli_free_result($result);
require_once("db_close.php");
echo json_encode($events);
?>
events.js
$(document).ready(function() {
var events = document.getElementById("allevents").value;
// Call Ajax for existing comments
$.ajax({
type: 'GET',
url: 'events.php',
success: function(result) {
var arr = JSON.parse(result);
for(var i = 0; i < arr.length; i++) {
var obj = arr[i];
var output = document.getElementById("allevents");
output.innerHTML += '<div class="comment-container"><div class="eventname">'+obj.eventname+'</div><div class="date">'+obj.date+'</div><div class="time">'+obj.time+'</div><div class="location">'+obj.location+'</div></div>';
}
}
});
filterevents.php
<?php
require_once('checklog.php');
require_once("db_connect.php");
require_once("functions.php");
This is where I want to filter but not sure how to do it.
?>
filterevents.js
// When post button is clicked
$(document).ready(function() {
var forum = $("#eventForm");
$("#eventForm").on('submit', function(event) {
event.preventDefault();
var events = new FormData(this);
if (events) {
// Call Ajax for new comment
$.ajax({
type: 'POST',
url: 'filterevents.php',
data: events,
processData: false,
contentType: false,
success: function(response) {
if(response == "Success")
{
document.getElementById("comment").innerHTML = response;
} else {
document.getElementById("error").innerHTML = response;
}
}
});
} else {
document.getElementById("error").innerHTML = "Please Select A Location";
}
return false;
});
});

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>

PHP auto-fill selectbox through URL

I have a question I can't figure out.
<?php
$killtheboy = 0;
if($killtheboy == 1){
echo "<input type=\"text\" name=\"dwanummer\" id=\"dwanummer\">";
}else{
echo "<div id=\"dropdowndwa\">
<select name=\"dwanummer\" id=\"dwanummer\" class=\"dwanummer\">
<option selected=\"selected\">Kies uit lijst</option>";
include("config/instellingen.php");
$query = "SELECT DISTINCT `Klantvraag`,`Wensweek` FROM `DWA` WHERE `Status DWA` = 'DBAA' OR `Status DWA` = 'DBAP' OR `Status DWA` = 'DIUI' ORDER BY wensweek - '$wensweekber' ASC";
if ($result = mysqli_query($connect, $query)) {
while ($get = mysqli_fetch_assoc($result)) {
$week = date('W', strtotime("this week"));
$jaar = date('Y', strtotime("this week"));
$wens = ''. $jaar . ''. $week. '';
$wensweek = $get['Wensweek'];
$wensweekber = $wensweek - $wens;
echo '<div class="selectBlock"><option value="' . $get['Klantvraag'] . '" name="dwanummer" id="dwanummer" class="dwanummer">'.$get['Klantvraag'] . ' Wensweek : ' . $wensweekber . '</option></div>';
}
}
echo "</select></div><br />";
}
?>
The above code (PHP) fetches a list of numbers on pageload and I have to select one in order to fetch that information through JS.
<script type="text/javascript">
$(document).ready(function()
{
$(".kvraagnummer").change(function()
{
var id = $("#kvraagnummer option:selected").prop("value");
var dataString = 'id=' + id;
$.ajax
({
type: "POST",
url: "add_event_2.php",
data: dataString,
cache: false,
success: function(html)
{
$('.cnummer').html(html);
}
});
});
});
</script>
Basically I have a search system and u can find all 'cases' there and if you see one you want then you click it it goes to the above page with code and it auto selects that ID instead of still having to select it. (like additem.php?id=125533 or something)
Can someone please explain me how I can solve this.
Can you try this, You need to use selected attribute in select element
$Selected ='';
if(isset($_GET['id']) && ($get['Klantvraag'] == $_GET['id'])){
$Selected =" selected='selected' ";
}
echo '<option value="' . $get['Klantvraag'] . '" '.$Selected.' name="dwanummer" id="dwanummer" class="dwanummer">'.$get['Klantvraag'] . ' Wensweek : ' . $wensweekber . '</option>';
Javascript:
$(document).ready(function()
{
$(".kvraagnummer").change(function()
{
Populate();
});
Populate();
});
function Populate(){
var id = $("#kvraagnummer option:selected").prop("value");
var dataString = 'id=' + id;
$.ajax({
type: "POST",
url: "add_event_2.php",
data: dataString,
cache: false,
success: function(html)
{
$('.cnummer').html(html);
removeAllNameSelectBoxes();
var selected = $("#dropdowndwa option:selected").map(function (i, el) {
return el.value;
}).get();
getNamesFromSelectIds(selected);
}
});
}

Categories

Resources