I want to ask how to select default value from ajax to select2? My ajax code:
// Customer
$('.shipper').select2({
placeholder: "Choose Shipper",
selectionTitleAttribute: false,
ajax: {
url: 'getCustomer.php',
dataType: 'json',
data: function (params) {
return {
filter_name: params.term
};
},
processResults: function (data) {
return {
results: $.map(data, function (obj) {
return {id: obj.customer_id, text: obj.name};
})
};
},
cache: true
},
initSelection: function (element, callback) {
return callback({id: "<?php echo $data['customerId']; ?>", text: '<?php echo $shipper['name']; ?>'});
}
});
While my PHP code to fetch data is like this:
<?php
include('config.php');
$json = array();
if (isset($_GET['filter_name'])) {
$clientId = $_GET['filter_name'];
$query = "SELECT * FROM m_customer WHERE c_name LIKE '%$clientId%' AND c_status > 0 ORDER BY c_name ASC LIMIT 0,10";
} else {
$query = "SELECT * FROM m_customer WHERE c_status > 0 ORDER BY c_name ASC LIMIT 0,10";
}
$result = mysqli_query($conn, $query);
while ($row = mysqli_fetch_array($result, MYSQLI_ASSOC)) {
$json[] = array(
'customer_id' => $row['c_id'],
'name' => strip_tags(html_entity_decode($row['c_name'], ENT_QUOTES, 'UTF-8')),
);
}
echo json_encode($json);
?>
I'm creating update page for my PHP files. So I need this select2 is selected from my database. That's why I get data from database then try to set to initSelection. It's already shows up and selected. But when I press save button (and look at my code from inspect element), the select doesn't have value. So it failed to save (screenshot attached)
I have weird solution:
I put the Option manually with the value and text from DB. It's done! My code become like this:
<select class="shipping form-control" name="shipping_id">
<option value="<?php echo $data['shippingId']; ?>" selected><?php echo $shipping['name']; ?></option>
</select>
But is there any problem/cause further? Because I think it's weird solution... (although it's work)
Related
I am using mysql database to retrieve data and show it into Select2. Right now, the search data is being showed in the preview of the get call. But not in the options of the Select2. Even though I am receiving the correct response, i can't get it added into the options of the select box
Below is my Javascript code
$("#selecter").select2({
ajax: {
url: "index.php",
dataType: 'json',
delay: 250,
data: function (params) {
return {
q: params.term // search term
};
},
processResults: function (data) {
return {
results: data
};
},
cache: true
},
escapeMarkup: function (markup) { return markup; }, // let our custom formatter work
minimumInputLength: 2
});
and here is the php code
if(isset($_GET['q'])){
$urlparam_name = $_GET['q'] ."%";
$link = mysqli_connect('localhost', 'root', '', 'customerdatabase_13030') or die("Error " .mysqli_error($link));
$sql = "
SELECT `customer_13030`.`custID`, `customer_13030`.`name`
FROM `customer_13030`
WHERE `customer_13030`.`custID` like '$urlparam_name' OR `customer_13030`.`name` like '$urlparam_name'
GROUP BY `customer_13030`.`custID` ASC
";
$result = mysqli_query($link, $sql) or die("Error " .mysqli_error($link));
$rows = array();
while ($row = mysqli_fetch_assoc($result))
{
$rows[] =array(
'id' => $row['custID'],
'name' => $row['name']
);
}
echo json_encode($rows);
}
I'm not able to filter table data using Ajax. When I select BANK CREDIT from drop down it should fetch employee details with modeofpay(table column) as "BANK CREDIT" and when I select NEFT it should display employee details with modeofpay(table column) as "NEFT". As of Now nothing happens when i select drop down.
Controller:
public function filter($key = '')
{
$this->load->helper('url');
if ( $key == 'BANK CREDIT' ) {
$this->load->model('JcMeetingExpense_model');
$data = $this->JcMeetingExpense_model->getCredit($key);
}
else
{
$this->load->model('JcMeetingExpense_model');
$data = $this->JcMeetingExpense_model->getNeft($key);
}
echo json_encode($data);
}
Model:
public function getCredit($key)
{
$sql = "SELECT * FROM employee WHERE modeofpay = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
public function getNeft($key)
{
$sql = "SELECT * FROM employee WHERE modeofpay = '$key'";
$data = $this->db->query($sql);
return $data->result_array();
}
View:
<script type="text/javascript">
var paymode = $("#mode").change(function(){
$.ajax({
type:"POST",
url:url:'<?php echo base_url("JcMeetingExpense/filter/key/") ?
>'+paymode,
data:"key="+paymode,
dataType:'json',
success:function(data){
$("#viewjcexpense").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
<select name="mode" id="mode" >
<option value="BANK CREDIT">CREDIT</option>
<option value="NEFT">NEFT</option>
</select>
is your onchange event working ?
let's check with
$("#mode").change(function(){
alert(1);
});
if when u selected an option would be show the alert that's mean ur event working ,
now if that's working fine let's try to playing with ajax and do little recode, here i used post method
[ VIEW ]
$("#mode").change(function(){
$.ajax({
type : 'POST',
url : '<?=base_url(); ?>JcMeetingExpense/filter/',
data : { key : $("#mode").val() },
success : function(data){
console.log(data);//let's check on console what's response is
}
});
})
[CONTROLLER]
public function filter()
{
$this->load->helper('url');
$this->load->model('JcMeetingExpense_model');
$dataKey = $this->JcMeetingExpense_model->get_data_by_key();
echo json_encode($datadataKey);
}
[MODEL]
public function get_data_by_key()
{
//do post here let's say
$key = $this->input->post("key");
// i looked your query is vulnerable to SQL Injection
/* $sql = "SELECT * FROM employee WHERE modeofpay = '$key'";
$data = $this->db->query($sql);
return $data->result_array(); */
//so let's use query builder
$this->db->select("*");
$this->db->from("employee");
$this->db->where("modeofpay",$key);
$q = $this->db->get();
return $q->result_array();
}
now check response in console
<script type="text/javascript">
$("body").on('change','#mode',function(){
$.ajax({
type:"POST",
url:url:'<?php echo base_url("JcMeetingExpense/filter/key/") ?
>'+paymode,
data:"key="+paymode,
dataType:'json',
success:function(data){
$("#viewjcexpense").html(data);
},
error:function(XMLHttpRequest){
alert(XMLHttpRequest.responseText);
}
});
});
</script>
try this script instead of your previous script
i have changed $("#mode").change(function(){}); with $("body").on('change','#mode',function(){});
I have some problem with to display my appended checkbox in ajax call, this is my json result
[{"nama":"Food","idkategori":"1","dicek":"iya"},{"nama":"Fashion","idkategori":"2","dicek":"iya"},{"nama":"Beverages","idkategori":"3","dicek":"iya"},{"nama":"Art","idkategori":"4","dicek":"tidak"},{"nama":"Music","idkategori":"5","dicek":"tidak"},{"nama":"Technology","idkategori":"6","dicek":"tidak"},{"nama":"Smartphone","idkategori":"7","dicek":"tidak"},{"nama":"Computer","idkategori":"8","dicek":"tidak"},{"nama":"Games","idkategori":"9","dicek":"tidak"},{"nama":"Movies","idkategori":"10","dicek":"tidak"},{"nama":"Sports","idkategori":"11","dicek":"tidak"},{"nama":"Books","idkategori":"12","dicek":"tidak"}]
there is an checking in my query, if checkbox has been checked. value checkbox save to database, and I want to show my all checkbox which checked or not checked.
this is my ajax code
$.ajax({
url: host+'/skripsi3/phpmobile/appendfilter.php',
data: { "id": user},
dataType: 'json',
success: function(data, status){
$.each(data, function(i,item){
//alert("here");
$("#appendfilter").append('<input class="kategoriFilter" type="checkbox" value="'+item.nama+'" name="cektambah" id="'+item.idkategori+'"><label for="'+item.idkategori+'">'+item.nama+'</label>').trigger("create");
if(item.dicek=="iya")
{
$("#"+item.idkategori).prop('checked', true);
}
else if(item.dicek=="tidak")
{
$("#"+item.idkategori).prop('checked', false);
}
});
},
error: function(e){
//alert(e);
}
});
and this is my appendfilter.php
<?php
session_start();
include "config.php";
$user=mysql_real_escape_string($_GET["id"]);
$result=mysql_query("SELECT * from filtering WHERE id_tenant='$user'") or die(mysql_error());
if (!empty($result))
{
while ($row=mysql_fetch_array($result))
{
$tempfilter[] = $row['filter'];
$q="select 'iya' as dicek,kategori.id_kategori,kategori.nama from kategori WHERE id_kategori IN (".implode(',',$tempfilter).") UNION ALL select 'tidak' as dicek,kategori.id_kategori,kategori.nama from kategori where id_kategori NOT IN (".implode(',',$tempfilter).") ";
//echo $q;
$result2 = mysql_query($q) or die(mysql_error());
if (!empty($result2))
{
while ($row2=mysql_fetch_array($result2))
{
$fetchkategori[] = array
(
'nama' => $row2['nama'],
'idkategori' => $row2['id_kategori'],
'dicek' => $row2["dicek"]
);
}
}
}
}
mysql_close($con);
header('Content-Type:application/json');
echo json_encode($fetchkategori);
?>
Hope someone can help me solve my problem.
Try to check if your html is ready. Supposing that you get your json object correctly :
$(document).ready(function(){
var data =[
{"nama":"Food","idkategori":"1","dicek":"iya"},
{"nama":"Fashion","idkategori":"2","dicek":"iya"},
{"nama":"Beverages","idkategori":"3","dicek":"iya"},
{"nama":"Art","idkategori":"4","dicek":"tidak"},
{"nama":"Music","idkategori":"5","dicek":"tidak"},
{"nama":"Technology","idkategori":"6","dicek":"tidak"},
{"nama":"Smartphone","idkategori":"7","dicek":"tidak"},
{"nama":"Computer","idkategori":"8","dicek":"tidak"},
{"nama":"Games","idkategori":"9","dicek":"tidak"},
{"nama":"Movies","idkategori":"10","dicek":"tidak"},
{"nama":"Sports","idkategori":"11","dicek":"tidak"},
{"nama":"Books","idkategori":"12","dicek":"tidak"}];
$.each(data, function(i,item){
$("#appendfilter").append('<input class="kategoriFilter" type="checkbox" value="'+item.nama+'" name="cektambah" id="'+item.idkategori+'"><label for="'+item.idkategori+'">'+item.nama+'</label>').trigger("create");
if(item.dicek=="iya")
{
$("#"+item.idkategori).prop('checked', true);
}
else if(item.dicek=="tidak")
{
$("#"+item.idkategori).prop('checked', false);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<div id="appendfilter"></div>
I want to use jQuery auto complete multiple Fields in codeigniter framework I referred this tutorial.But my search filed not working.text fields doesn't show auto complete list
here is my code please help me to solve this.
view
.....................
<div class="row">
<form action="" name="students" method="post" id="students">
<input type="text" name="patientId" id="patientId_1" class="ui-autocomplete-input">
<input type="text" name="firstname" id="firstname_1" class="ui-autocomplete-input">
<input type="text" name="nic" id="nic_1" class="ui-autocomplete-input">
<input type="text" name="telephone" id="telephone_1" class="ui-autocomplete-input">
</form>
</div>
jQuery
.......
$('#patientId_1').autocomplete({
source: function( request, response ) {
$.ajax({
url : 'http://localhost/cafdc/BillingController/test',
dataType: "json",
data: {
name_startsWith: request.term,
type: 'patient_table',
row_num : 1
},
success: function( data ) {
response( $.map( data, function( item ) {
var code = item.split("|");
return {
label: code[0],
value: code[0],
data : item
}
}));
}
});
},
autoFocus: true,
minLength: 0,
select: function( event, ui ) {
var names = ui.item.data.split("|");
$('#firstname_1').val(names[1]);
$('#nic_1').val(names[2]);
$('#telephone_1').val(names[3]);
}
});
controller
.......................
public function test()
{
$data=$this->Billing_Model->get_data();
echo json_encode($data);
}
model
....................
public function get_data()
{
if($_POST['type'] == 'patient_table'){
$row_num = $_POST['row_num'];
$result =$this->db->query( "SELECT patientId, fname, nic, tpnumber FROM tblpatient where name LIKE '".strtoupper($_POST['name_startsWith'])."%'");
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['patientId'].'|'.$row['fname'].'|'.$row['nic'].'|'.$row['tpnumber'].'|'.$row_num;
array_push($data, $name);
}
}
}
Your code is not working Because you are not return any data from model
public function get_data()
{
if($_POST['type'] == 'patient_table'){
$row_num = $_POST['row_num'];
$result =$this->db->query( "SELECT patientId, fname, nic, tpnumber FROM tblpatient where name LIKE '".strtoupper($_POST['name_startsWith'])."%'");
$data = array();
while ($row = mysqli_fetch_assoc($result)) {
$name = $row['patientId'].'|'.$row['fname'].'|'.$row['nic'].'|'.$row['tpnumber'].'|'.$row_num;
array_push($data, $name);
}
return $data;// return your data
}
}
You have to set type:"POST" in ajax call otherwise it will take it as GET so add the type in your $.ajax call like,
$.ajax({
url:'...',
type:"POST",// add this line in your ajax call
....
})
I am using the select 2 plugin to search for users. Everything is up an running an my jsons end up with: [{"id":"1","text":"Alex Fagard (afagard) ID: 1"}] .etc.
I am using the following code to build the select 2 interface:
$(document).ready(function(){
$('#username-search').select2({
minimumInputLength: 2,
select: function(event, ui) {
AutoCompleteSelectHandler(event, ui)
},
ajax: {
url: "classes/search.class.php?sType=users",
dataType: 'json',
data: function (term, page) {
return {
term: term
};
},
results: function (data, page) {
return { results: data };
}
}
});
});
However I am stuck on how to make it so that when the admin selects a user (aka clicks on their dropdown area) the page redirects to userview.php?id=1 where 1 is the id from the JSON array.
Search function if anyone is interested:
public function searchUsers($term = '') {
if (isset($term)) {
$term = parent::secure($term);
$params = array( ':searchQ' => $term . '%' );
$sql = "SELECT distinct username as suggest, user_id, name
FROM login_users
WHERE username LIKE :searchQ
OR name LIKE :searchQ
OR user_id LIKE :searchQ
ORDER BY username
LIMIT 0, 5";
$stmt = parent::query($sql, $params);
if ( $stmt->rowCount() > 0 ) {
while($suggest = $stmt->fetch(PDO::FETCH_ASSOC)) {
$data[] = array(
'id' => $suggest['user_id'],
'text' => $suggest['name'] . ' (' . $suggest['suggest'] . ')' . ' ID: ' . $suggest['user_id'],
);
}
} else {
$data[] = array('id'=>'0', 'text'=>'No results found!');
}
echo json_encode($data);
flush();
}
}
$searchParam = new Search();
if (isset($_GET['term'])) {
// we secure the term before running the search and querying the database
$term = $_GET['term'];
switch (isset($_GET['sType']) ? $_GET['sType'] : NULL) {
case 'users':
$searchParam->searchUsers($term);
break;
case 'levels':
$searchParam->searchLevels($term);
break;
}
}
Version 4.0 +
Events are now in format: select2:selecting (instead of select2-selecting)
$("#search").on("select2:selecting", function(e) {
window.location.href = 'user_edit.php?id=' + e.val;
});
Came across the same question a year after posting this and googled something and ended up here forgetting I ever posted it in the first place.
Well found a solution:
<script>
$(document).ready(function () {
$("#search").select2({
ajax: {
url: "users.php",
dataType: 'json',
data: function (term) {
return {
term: term,
};
},
results: function (data) {
return {results: data};
}
}
});
$("#search").on("select2:selecting", function(e) {
window.location.href = 'user_edit.php?id=' + e.val;
});
});
</script>
Event name is select2:selecting