How can I add select2 dynamic select box inside a while loop? - javascript

I'm trying to put a Select2 box inside a while loop. But it only works the first select tag. Although loop works fine, the select tag is not working after the first 1. how can I fix this issue?
I also tried adding printing PHP unique id to fix it. but nothing happened.
<select type="text" name="city" id="city-<?php echo $id; ?>" class="form-control"></select>
This is the javascript part:
<script type="text/javascript">
$('#city-<?php echo $id; ?>').select2({
placeholder: 'Select city',
ajax: {
url: 'processes/cities.php',
dataType: 'json',
delay: 250,
processResults: function (data) {
return {
results: data
};
},
cache: true
}
});
</script>
I'm expecting all the select boxes to work fine. But actually, only first 1 works.

It would be helpful if you provided the loop in your code example.
The most likely problem is that your id's are not unique. If you have multiple tags with the same id then javascript will only recognize the first one.
Here's an example to demonstrate.
https://jsfiddle.net/n8vxjoc1/1/
<div id="city-1">Content</div>
<div id="city-1">Content</div>
<script>
jQuery( '#city-1' ).html( jQuery( '#city-1' ).length );
</script>
Only the 1st element will change and it will display the number 1.
From the W3C specs:
The id attribute specifies its element's unique identifier (ID).
https://www.w3.org/TR/2011/WD-html5-20110525/elements.html#the-id-attribute
You should give the select dropdowns a class and target that instead.
E.g.
https://jsfiddle.net/n8vxjoc1/1/
<select name="city" class="select2 form-control">…</select>
<select name="city" class="select2 form-control">…</select>
<script type="text/javascript">
$('select.select2').select2({});
</script>

You can take help from this link: Demo
<select class="select2_el" style='width: 200px;'>
<option value='0'>- Search user -</option>
</select>
<div id='elements'>
</div>
<input type="button" id="btn_add" value="Add">
PHP:
<?php
include 'config.php';// add your config details on that file
$request = 1;
if(isset($_POST['request'])){
$request = $_POST['request'];
}
// Select2 data
if($request == 1){
if(!isset($_POST['searchTerm'])){
$fetchData = mysqli_query($con,"select * from users order by name limit 5");
}else{
$search = $_POST['searchTerm'];
$fetchData = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5");
}
$data = array();
while ($row = mysqli_fetch_array($fetchData)) {
$data[] = array("id"=>$row['id'], "text"=>$row['name']);
}
echo json_encode($data);
exit;
}
// Add element
if($request == 2){
$html = "<br><select class='select2_el' ><option value='0'>- Search user -</option></select><br>";
echo $html;
exit;
}
JS
$(document).ready(function(){
// Initialize select2
initailizeSelect2();
// Add <select > element
$('#btn_add').click(function(){
$.ajax({
url: 'ajaxfile.php',
type: 'post',
data: {request: 2},
success: function(response){
// Append element
$('#elements').append(response);
// Initialize select2
initailizeSelect2();
}
});
});
});
// Initialize select2
function initailizeSelect2(){
$(".select2_el").select2({
ajax: {
url: "ajaxfile.php",
type: "post",
dataType: 'json',
delay: 250,
data: function (params) {
return {
searchTerm: params.term // search term
};
},
processResults: function (response) {
return {
results: response
};
},
cache: true
}
});
}

Related

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?

Can I pass variables into an ajax query?

I'm creating a website and I want to load different queries onto a page depending on which button is clicked.
Can I do it like this?
The HTML :
<div id="Proceed">
4 Projects have been suggested to proceed.
</div>
<div id="result">
<!-- The title of the projects will be loaded here -->
</div>
<button id="foo"> Search </button>
The javascript:
$('#foo').on('click' function(){ //the button
var x = $(this).find('div').attr('id'); // get the id
$.ajax({
url: 'profile/inbox',
type: 'POST',
data: { id: x },
success: function(res){
('#result').html(res);
}
})
})
On profile.php:
function Inbox(){
$id = $_POST['id'];
$query = $this->db->query("SELECT `title` FROM `table` WHERE id=?",$id);
$load = $query->result_array();
$this->d['load'] = $load;
}
EDIT: I added some html to show where I plan to load the results of the query.
For eg:(This is your code I just slightly modified because for
example)
<div id="Proceed">
<select id="city" name="city">
<option value="">City:</option>
<option value="glasgow">Glasgow</option>
<option value="london">London</option>
</select>
</div>
<div id="result">
</div>
<button id="foo"> Search </button>
Script:(For eg:)
$("#foo").click(function() {
$.ajax({
url: 'profile/inbox', //Pass this value to the corresponding URL
type: 'POST',
dataType: "html",
data: {
"city": $('#city').val(), //Here request the value for id name is city
},
success: function(response){
$("#result").html(response); //Retrieve value form URL to pass the view page and value to set in <div id="result">
}
});
});
This is my url page(you just see what are the process there.. This is
for eg)
$sql = "SELECT * FROM entries";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// output data of each row
  while($row = $result->fetch_assoc()) {
  echo "success"."id: " . $row["id"]. " - City: " . $row["city"]. "<br>";
  }
} else {
  echo "0 results";
}
When you want to use a POST variable from PHP side you have to use
$_POST/$_REQUEST method in your case $id = $_POST['id']; this will work

pass value from multiple div to ajax on page load and on change

I'm trying to re-use the same code on several web pages to tidy up the code, especially when the same AJAX response in used once/few times on the page.
The response is a list of <option> to be placed into <select>.
On a NEW ENTRY to database page load, I want the <select> to be filled with correct <options>.
On an UPDATE to database page load, I want the <select> to be initially filled with selected <option selected>, but when .change is triggered, the cascading <select> must update accordingly.
Everything worked as expected, until I've decided to reuse the same code (response from Ajax) instead of having separate php syntax inside each <select>.
Now, when the page is loading the <select> values in all div's gets overwritten by the value from the last one.
Any Idea on how to accomplish this?
here is my code so far:
webpage.php
<div class="form-group">
<div class="col-xs-2"><input type="hidden" class="deptList_value" value="<?php echo $row['fDeptFK'];?>">
<select class="form-control deptList" name="deptFK" onchange="getId(this.value);" required>
</select>
</div>
<div class="col-xs-2"><input type="" class="areaList_value" value="<?php echo $row['PK'].'-'.$row['fDeptFK'].'-'.$row['fAreaFK'];?>">
<select class="form-control areaList" name="areaFK" required>
</select>
</div>
</div>
jquery:
$(document).ready(function(){
$(".deptList_value").each(function() {
var deptPK = $(this).val();
//alert(deptPK);
$.ajax({
url:"../GetData_DropDown/getdataDeptQA.php",
method:"POST",
data:{DeptNo:deptPK},
dataType:"text",
success:function(data)
{
$('.deptList').html(data);
}
});
});
$(".areaList_value").each(function() {
var arr = $(this).val().split('-');
var idPK = arr[0];
var deptPK = arr[1];
var areaPK =arr[2];
$.ajax({
url:"../GetData_DropDown/getdataAreaQA.php",
method:"POST",
data:{AreaNo:areaPK,DeptNo:deptPK},
dataType:"text",
success:function(data)
{
$('.areaList').html(data);
}
});
});
$('.deptList').change(function(){
var deptPK = $(this).val();
$.ajax({
url:"../GetData_DropDown/getdataAreaQA.php",
method:"POST",
data:{DeptNo:deptPK},
dataType:"text",
success:function(data)
{
$('.areaList').html(data);
}
});
});
getdataAreaQA.php
$output = '<option value=""></option>';
foreach($conn->query("EXEC [qa].[getQA_area_list] ".$_POST["DeptNo"]) as $rowA) {
if ($rowA['PK']==$_POST['AreaNo']) {
$output .= '<option value="'.$rowA['PK'].'" data-AP24FKvalue="'.$rowA['AP24FK'].'" selected>'.$rowA['Name'].'</option>';
} else {
$output .= '<option value="'.$rowA['PK'].'" data-AP24FKvalue="'.$rowA['AP24FK'].'">'.$rowA['Name'].'</option>';
}
}
echo $output;
EDIT
Not tested but this should work on a page with single row from database. The issue is with paginated pages with multiple rows on one page.
I propose you simplify a little bit more, and use specialized unique id in combination with your class handlers.
Lets first start by adjusting rows output from your loop:
<?php
$idx = 0;
/* your foreach/for/while loop */ {
$idx++;// just ensuring a unique value to utilize
?>
<div class="form-group">
<div class="col-xs-2">
<select id="dept_<?php echo $idx;?>"
data-dept="<?php echo $row['fDeptFK'];?>"
data-idx="<?php echo $idx;?>"
class="form-control deptList" name="deptFK" required>
</select>
</div>
<div class="col-xs-2">
<select id="area_<?php echo $idx;?>"
data-dept="<?php echo $row['fDeptFK'];?>"
data-area="<?php echo $row['fAreaFK'];?>"
data-idx="<?php echo $idx;?>"
class="form-control areaList" name="areaFK" required>
</select>
</div>
</div>
<?php }?>
No need for hidden inputs. The data-vars will contain all that you need. Note that each id should be unique per row output.
Now some slight adjustments to the jquery:
$(document).ready(function(){
$(".deptList").each(function() {
var idx = $(this).data('idx');// the unique row id
var dept = $(this).data('dept');
$.ajax({
url:"../GetData_DropDown/getdataDeptQA.php",
method:"POST",
data:{DeptNo: dept},
dataType:"html",
success:function(data)
{
$("#dept_"+idx).html(data);// targets unique id
}
});
});
$(".areaList").each(function() {
var idx = $(this).data('idx');
var dept = $(this).data('dept');
var area = $(this).data('area');
$.ajax({
url:"../GetData_DropDown/getdataAreaQA.php",
method:"POST",
data:{AreaNo: area, DeptNo: dept},
dataType:"html",
success:function(data)
{
$("#area_"+idx).html(data);
}
});
});
$('.deptList').change(function(){
var idx = $(this).data('idx');
var dept = $(this).val();// using .val not .data
$.ajax({
url:"../GetData_DropDown/getdataAreaQA.php",
method:"POST",
data:{DeptNo: dept},
dataType:"html",
success:function(data)
{
$("#area_"+idx).html(data);// targets area select
// you may want to update the area selects data too:
$("#area_"+idx).data('dept', dept);
}
});
});
});
By targeting using the row idx value, you can ensure which sub select options will be changed out. All the data-vars contain values for what you need to initially populate the select options.
Important Note
As we discovered through comments... if you try to use capitals in a data-varNAME, it will result in undefined when accessing it with the .data() jquery method. So instead, make sure the naming of the data-varname has no caps and it will be ok.

How to populate a dropdown with AJAX

I want to populate a dropdown (AJAX) when I click on the dropdown.
I have a dropdown categories and a button Add categories
When I open the page the first time, I can see my categories inside the dropdown.
If I want to include another categories, I click on Add categories and I insert my new categories.
After, if I click on the dropdown, I must see my new categories.
How to do that ?
I don't know exactly how to create that.
Thank you
my_ajax_file.php
$Qcheck = $OSCOM_Db->prepare('select categories_id as id,
categories_name as name
from :table_categories');
$Qcheck->execute();
$list = $Qcheck->rowCount();
if ($list > 0) {
$array = [];
while ($value = $Qcheck->fetch() ) {
$array[] = $value;
}
# JSON-encode the response
$json_response = json_encode($array); //Return the JSON Array
# Return the response
echo $json_response;
HTML code
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
}
});
});
}
</script>
<select name="category_id" id="Mycategory_id" class="form-control">
<option value="0" selected="selected">Haut</option>
<option value="23">Panneaux Signalétique</option>
<option value="20">Signalétique Camping</option>
<option value="22"> Barrières</option>
<option value="21"> Entrée</option>
</select>
<input type="hidden" name="current_category_id" value="0" /></div>
You need to update the select element with new options.
<script type="text/javascript">
function Mycategory_id() {
$("#myAjax").on('click', function(){
$.ajax({
url: 'http://www.my_ajax_file.php',
dataType: 'json',
success: function(data){
//data returned from php
var options_html = '';
for(index in data){
var category_id = data[index]['categories_id'];
var category_name = data[index]['categories_name'];
options_html += '<option value="'+category_id+'">' + category_name + '</option>';
}
$('#category_id').html(options_html);
}
});
)};
</script>
To make rendering easy, you can use mustache.js

codeigniter csrf not work in select option

I want to make step input with select option, in this case, i make 3 step, when select first option then will show next option 2, then option 3. i am using ajax and i set $config['csrf_protection'] = TRUE; in Codeigniter config file. In first select option (#kategori) is work and show next value in second select option, but in step 3 select option (#sub1 or secon function of javascript) n't work. thank before.
This is my view:
<?php echo form_open_multipart('',array('class'=>'form-horizontal'));?>
<?php echo form_label('Kategori','id_kategori',array('class'=>'col-sm-2 control-label'));?>
<select id="kategori" name="id_kategori">
<option value=""></option>
<?php
foreach($kategori as $kategori_umum)
{
echo '<option value='.$kategori_umum->id.'>'.$kategori_umum->nama_kategori.'</option>';
}
?>
</select>
<select id="sub1" name="id_kategori_sub1"> //step 2
<option value=""></option>
</select>
<select id="sub2" name="id_kategori_sub2"> //step 3
<option value=""></option>
</select>
Ajax :
<script type="text/javascript">
$('#kategori').change(function(){
var kategori_id = $('#kategori').val();
//alert(state_id);
if (kategori_id != ""){
var post_url = "<?php echo base_url();?>masuk/produk/get_sub1";
$.ajax({
type: "POST",
url: post_url,
data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>','kategori_id':kategori_id},
dataType: 'json',
success: function(kategori_sub1, dataType) //calling the response json array 'kategori_sub1'
{
$('#sub1').empty();
$('#sub1').show();
$.each(kategori_sub1,function(id,sub1)
{
var opt = $('<option />'); // creating a new select option for each group
opt.val(id);
opt.text(sub1);
$('#sub1').append(opt);
$('#sub2').hide();
});
},
error:function(xhr)
{
alert("Terjadi Kesalahan");
}
}); //end AJAX
} else {
$('#sub1').empty();
$('#sub2').empty();
}});
$('#sub1').mouseout(function(){
var sub1_id = $('#sub1').val();
if (sub1_id != ""){
var post_url = "<?php echo base_url();?>masuk/produk/get_sub2";
$.ajax({
type: "POST",
url: post_url,
data: {'<?php echo $this->security->get_csrf_token_name(); ?>':'<?php echo $this->security->get_csrf_hash(); ?>','sub1_id':sub1_id},
dataType: 'json',
success: function(kategori_sub2, dataType)
{
$('#sub2').empty();
$('#sub2').show();
$.each(kategori_sub2,function(id,sub2)
{
var opt = $('<option />');
opt.val(id);
opt.text(sub2);
$('#sub2').append(opt);
});
},
error:function(xhr)
{
alert("Kesalahan");
}
}); //end AJAX
}});</script>
I suspect your problem is using wrong event mouseout.
You should be using change the same way the first one that works does.
Beyond that more information is needed about the actual requests by inspecting in browser dev tools

Categories

Resources