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
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 have implemented search module with jqueryUI autocomplete in which search suggestions are rendered with their category.
Now i want to make those suggestions clickable,I've already tried select function but its not working,now i stuck in it
My Jquery Code is
$( function() {
$.widget("custom.catcomplete", $.ui.autocomplete, {
_renderMenu: function(ul, items) {
var that = this,
currentCategory = "";
$.each(items, function(index, item) {
if (item.category != currentCategory) {
ul.append("<li class='ui-autocomplete-category'>" + item.category + "</li>");
currentCategory = item.category;
}
that._renderItemData(ul, item);
});
}
});
$( "#search" ).catcomplete({
source : function(request,response){
var term = $("#search").val();
$.ajax({
type : "GET",
url : "ajax/auto_search.php",
dataType : "json",
data : {term : term},
success : function(data)
{
console.log(data);
response($.map(data.list, function(item) {
return {
value: item.content_title,
label: item.content_title,
category: item.category_name,
url : item.url
}
}))
},
select: function( event, ui ) {
//main problem is with item.content_title unable to get its value
window.location.href = 'search.php?mode=content_type&query='+item.content_title;
}
});
}
});
});
php code is
<?php
include '../includes/dbconfig.php';
header('Content-Type: application/json');
$searchTerm = $_GET['term'];
$sql = "SELECT distinct content_title, c.content_title,p.category_name,c.content_url from content_ref_table c inner join category_ref_table p on p.category_id = c.category_id where c.content_title LIKE '%".$searchTerm."%' ORDER BY c.content_title ASC LIMIT 0,10";
$result = mysqli_query($conn,$sql) or die(mysqli_error($conn));
$data_array = array();
while($row = mysqli_fetch_array($result))
{
$data_array['list'][] = array("content_title" => $row['content_title'], "category_name" => $row['category_name'],"url" => $row['content_url'] );
}
echo json_encode($data_array);
?>
**EDIT: how Can I store the item.content_title in a global variable?i think if i'm able to store the item.content_title in variable then it can solve my problem **
I am testing select2 plugin in my local machine.
But for some reason. it is not collecting the data from database.
I tried multiple times but not able to find the issue.
Below are the code .
<div class="form-group">
<div class="col-sm-6">
<input type="hidden" id="tags" style="width: 300px"/>
</div>
</div>
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
type: "POST",
data: function (params) {
return {
q: params.term // search term
};
},
results: function (data) {
lastResults = data;
return data;
}
},
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
return { id: term, text: text };
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
i checked fetch.php and it is working fine. It is returning the data.
<?php
require('db.php');
$search = strip_tags(trim($_GET['q']));
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
$query->execute(array(':search'=>"%".$search."%"));
$list = $query->fetchall(PDO::FETCH_ASSOC);
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tid'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
echo json_encode($data);
?>
I am trying to create tagging and it will check tag in database.
if tag not found then user can create new tag and it will save in database and show in user user selection.
At the moment i am not yet created the page to save the tags in database.
I tried using select2 version 3.5 and 4.0.1 as well.
This is first time is i am trying select2 plugin. So, please ignore if i did silly mistakes. I apologies for that.
Thanks for your time.
Edit:
I checked in firebug and found data fetch.php didn't get any value from input box. it looks like issue in Ajax. Because it is not sending q value.
Configuration for select2 v4+ differs from v3.5+
It will work for select2 v4:
HTML
<div class="form-group">
<div class="col-sm-6">
<select class="tags-select form-control" multiple="multiple" style="width: 200px;">
</select>
</div>
</div>
JS
$(".tags-select").select2({
tags: true,
ajax: {
url: "fetch.php",
processResults: function (data, page) {
return {
results: data
};
}
}
});
Here is the answer. how to get the data from database.
tag.php
<script type="text/javascript">
var lastResults = [];
$("#tags").select2({
multiple: true,
//tags: true,
placeholder: "Please enter tags",
tokenSeparators: [","],
initSelection : function (element, callback) {
var data = [];
$(element.val().split(",")).each(function () {
data.push({id: this, text: this});
});
callback(data);
},
ajax: {
multiple: true,
url: "fetch.php",
dataType: "json",
delay: 250,
type: "POST",
data: function(term,page) {
return {q: term};
//json: JSON.stringify(),
},
results: function(data,page) {
return {results: data};
},
},
minimumInputLength: 2,
// max tags is 3
maximumSelectionSize: 3,
createSearchChoice: function (term) {
var text = term + (lastResults.some(function(r) { return r.text == term }) ? "" : " (new)");
// return { id: term, text: text };
return {
id: $.trim(term),
text: $.trim(term) + ' (new tag)'
};
},
});
$('#tags').on("change", function(e){
if (e.added) {
if (/ \(new\)$/.test(e.added.text)) {
var response = confirm("Do you want to add the new tag "+e.added.id+"?");
if (response == true) {
alert("Will now send new tag to server: " + e.added.id);
/*
$.ajax({
type: "POST",
url: '/someurl&action=addTag',
data: {id: e.added.id, action: add},
error: function () {
alert("error");
}
});
*/
} else {
console.log("Removing the tag");
var selectedTags = $("#tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index,1);
if (selectedTags.length == 0) {
$("#tags").select2("val","");
} else {
$("#tags").select2("val",selectedTags);
}
}
}
}
});
</script>
fetch.php
<?php
// connect to database
require('db.php');
// strip tags may not be the best method for your project to apply extra layer of security but fits needs for this tutorial
$search = strip_tags(trim($_POST['term']));
// Do Prepared Query
$query = $mysqli->prepare("SELECT tid,tag FROM tag WHERE tag LIKE :search LIMIT 4");
// Add a wildcard search to the search variable
$query->execute(array(':search'=>"%".$search."%"));
// Do a quick fetchall on the results
$list = $query->fetchall(PDO::FETCH_ASSOC);
// Make sure we have a result
if(count($list) > 0){
foreach ($list as $key => $value) {
$data[] = array('id' => $value['tag'], 'text' => $value['tag']);
}
} else {
$data[] = array('id' => '0', 'text' => 'No Products Found');
}
// return the result in json
echo json_encode($data);
?>
With the above code i am able to get the data from database. I get help from multiple users from SO. Thanks to all of them.
However, i am still refining other areas like adding tag in database. Once it completed i will post full n final code.
I am using an input box the select items from a database with ajax autocomplete. I want to remove the selected item so it can not be selected again. My code is as follows:
HTML
<input id='inpSelectRecipient' type='text' class='form-control' placeholder='Type recipient name here' autocomplete='off'></input>
Javascript
$("#inpSelectRecipient").autocomplete({
// Min Lenght Function
minLength: 2,
// Source Function
source: function (request, response) {
// Ajax Call
$.ajax({
url: '../getautocomplete.php',
data: request,
dataType: 'json',
type: 'GET',
success: function (data) {
// Ajax Data
response(data);
// Check if Results Exists
if (data.length === 0) {
// Alert Message/Class
varModalMessage = 'No Results Found'; // Message Text
varAlertClass = '4'; // Error Class
// Alert Message
modalAlert(varModalMessage, varAlertClass);
}
}
});
},
// Search Function
search: function(event, ui) {
},
// Select Function
select: function(event, ui) {
// Variable
var removedRecipient;
// Create Message Recipients
createMessageRecipients(ui.item.id);
// Clear Input
$('#inpSelectRecipient').val('');
// Test
//console.log('Receipients Array: ' + recipientsArray + ' Selected Array: ' + removedRecipient);
},
// Response Function
response: function( event, ui ) {
}
});
PHP
<?php
// Obtain Term
$term=$_GET["q"];
// Query
$query=mysql_query("SELECT * FROM tblUsers WHERE `userFirstName` LIKE '%" . $term . "%' OR `userLastName` LIKE '%" . $term . "%' ORDER BY userFirstName ");
// Json Array
$json=array();
// Array Function
while($contact=mysql_fetch_array($query)){
// JSON Array
$json[]=array(
'id'=>$contact["userID"],
'value'=>$contact["userFirstName"]." ".$contact["userLastName"],
'label'=>$contact["userFirstName"]." ".$contact["userLastName"]
);
}
// Obtain Json
$functionReturn = json_encode($json);
// Echo Function Return
echo json_encode($json);
?>
I have seen other examples however none that are using ajax to obtain the autocomplete array. Thanks so much for any help :)
*you need to send selected items id to server so that in sql query it can exclude that result.
var selectedElm = [];
$("#inpSelectRecipient").autocomplete({
......
});
select: function(event, ui) {
.....
selectedElm.push(ui.item.id);
....
}
source: function (request, response) {
request.exclude = selectedElm ;
$.ajax({
....
data: request,
.....
}
and on server side just use "where not in" query.*
I have a function which is returning the list of city names associated to city_id ordered by city name.
I want to show them in a select box. In Firefox (23.0.1) it is working fine even with order. But in case of IE (10) and chrome (29.0.1547.66 m) the order is not correct. I am using PHP and zend framework. My code:
$cities = $countryCityModel->getCities($country);
print json_encode(array('status'=>'Success',
'data'=>$cities)
);
public function getCities($countryId){
if(!$countryId)
return false;
$mdb = $this->getOldDbAdapter();
$sql = $mdb->select()
->from('cities', array('city_id','city'))
->where('country_id = ?', $countryId)
->order("city");
return $mdb->fetchPairs($sql);
}
$.ajax({
url : baseUrl + '/lead/index/get-cities',
dataType : 'json',
data : {
country:country_id
},
beforeSend : function(){
$("#holder_popup").show();
},
complete: function(){
$("#holder_popup").hide();
},
success : function(res) {
var sbuOptions = "<option value=''>--SELECT--</option>"
if(res.status == 'Success'){
for(i in res.data){
sbuOptions += "<option value='"+i+"'>"+res.data[i]+"</option>";
}
$("#city").html(sbuOptions);
}else{
$("#city").html(sbuOptions);
alert(res.msg);
}
},
error : function(jqXHR, exception) {
}
});
The returned value is like the following:
{
"status":"Success",
"data":{
"53029":"DURRES",
"53331":"ELBASAN",
"40239":"FIER",
"16235":"KAMEZ",
"42191":"KAVAJE",
"41375":"KUKES",
"53581":"PESHKOPI",
"57686":"SHIJAK",
"56756":"SHKODER",
"4496":"TIRANA",
"41342":"VLORE",
"19454":"VORE"
}
}
Please help me, how to resolve this issue?
can you update your code to this
public function getCities($countryId)
{
$resultArrary = array();
if($countryId)
{
$mdb = $this->getOldDbAdapter();
$sql = $mdb->select()
->from('cities', array('city_id','city'))
->where('country_id = ?', $countryId)
->order("city");
$result = $mdb->fetchAll($sql);
foreach($result as $key => $city )
{
$resultArrary[$key]['id'] = $city['city_id'];
$resultArrary[$key]['city'] = $city['city'];
}
}
return $resultArrary;
}
for(i in res.data)
{
cityData = res.data[i];
sbuOptions += "<option value='"+cityData.id+"'>"+cityData.city+"</option>";
}
Seems like chrome is auto sorting the json object with the index.
REF:
Chrome and IE sorts JSON Object automatically, how to disable this?
https://code.google.com/p/chromium/issues/detail?id=37404
You are missing ASC or DESC at line 12
->order("city ASC");