I am using a select2 jQuery plugin with ajax autocomplete from a remote server. But the user input gets appended to the dropdown list. Can someone help me with how to not display the user input in the select2 autocomplete dropdown?
here is my js code
$('#id_available_users').select2({
placeholder: "Select an Existing User",
allowClear: true,
minimumInputLength: 3,
tags: [],
ajax: {
url: '/api/users/',
dataType: 'json',
type: "GET",
data: function (term) {
return {
query: term.term,
};
},
processResults: function (data) {
if (data.length > 0)
{
return {
results: $.map(data, function (item) {
return {
text: item.name + ', ' + item.email + ', ' + item.location.city + ' ' + item.location.state + ' ' + item.location.zip + ' ' + item.location.country,
id: item.id,
}
})
};
}
else return {results: [{ 'loading' : false, 'description' : 'No result', 'name' : 'no_result', 'text' : 'No result'}]}
}
},
});
Finally, I figured it out. Here is how I fix it:
$('#id_available_users').select2({
placeholder: "Select an Existing User",
allowClear: true,
minimumInputLength: 3,
tags: [],
templateResult: function formatState (state) {
if (!state.id) {
return state.text
}
if (!state.text.name && !state.text.email) {
return; // here I am excluding the user input
}
var $state = '<p><b>'+ state.text.name + '</b>, ' + state.text.email + ', ' + state.text.location.city + ' ' + state.text.location.state + ' ' + state.text.location.zip + ' ' + state.text.location.country +'</p>';
return $state;
},
ajax: {
url: '/api/users/',
dataType: 'json',
type: "GET",
data: function (term) {
return {
query: term.term,
};
},
processResults: function (data) {
if (data.length > 0)
{
return {
results: $.map(data, function (item) {
return {
text: item,
id: item.id,
}
})
};
}
else return {results: [{ 'loading' : false, 'description' : 'No result', 'name' : 'no_result', 'text' : 'No result'}]}
}
},
});
Here, I have overwritten the templateResult and put a check if the item has no name and email (that will be the user input) just return true don't add it to the dropdown list.
I ma using jquery UI auto complete and i am getting the results, the only problem i am getting the results
http://prntscr.com/rsm946
not sure why it is not display, the json is coming as correct
my JSOn
[{"name":"author","type":"U","status":"0","owner":"dbo"},{"name":"author_dates","type":"U","status":"0","owner":"dbo"}]
$("#student").autocomplete(
{
source: function(request, response) {
$.ajax({
url: "search.cfc?method=searchByName&returnformat=json",
dataType: "json",
data: {
search: request.term,
maxRows: 10
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.label, value: item.label
};
}));
}
})
},
select: function( event, ui ) {
$('#submit').css("display", "block");
}
});
Please consider the following:
$("#student").autocomplete({
source: function(request, response) {
$.getJSON("search.cfc", {
method: "searchByName",
returnformat: "json",
search: request.term,
maxRows: 10
}, function(data) {
response($.map(data, (item) => {
return $.extend(item, {
label: item.name,
value: item.name,
});
}));
});
},
select: function(event, ui) {
$('#submit').css("display", "block");
}
});
Your object attribute is name, not label so u should write name despide of label
$("#student").autocomplete(
{
source: function(request, response) {
$.ajax({
url: "search.cfc?method=searchByName&returnformat=json",
dataType: "json",
data: {
search: request.term,
maxRows: 10
},
success: function(data) {
response($.map(data, function(item) {
return {
label: item.name, value: item.name
};
}));
}
})
},
select: function( event, ui ) {
$('#submit').css("display", "block");
}
});
I am having some problems using datatables.net with requirejs and some buttons and data loaded through the ajax request from datatables.net (JSON). I have tried and tried but still no luck.
The problem I face is: Uncaught ReferenceError: editPermission is not defined at HTMLButtonElement.onclick (permissions.php:1)
Here is the full backend PHP function that is connecting to the DB:
public function getAllPermissions($request, $columns): array
{
$bindings = array();
try {
$sql = "SELECT p.id, p.name, p.description, p.category, NULL AS roles,
CASE WHEN
p.required = 0 THEN concat('<button id=\'editpermission_', p.id, '\' onclick=\'editPermission(',p.id,')\' class=\'btn btn-warning\'>Edit</button>')
ELSE null END
AS edit
FROM ".$this->tbl_permissions." p";
$stmt = $this->conn->prepare($sql);
$stmt->execute();
$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
$return_data = array(
"data" => MiscFunctions::data_output($columns, $data)
);
return $return_data;
} catch (\PDOException $e) {
http_response_code(500);
$result = ["Error" => $e->getMessage()];
return $result;
}
}
Under here is the file that ajax asks for the data (permissions_getall.php):
<?php
try {
require '../../vendor/autoload.php';
session_start();
$request = new PHPLogin\CSRFHandler;
$auth = new PHPLogin\AuthorizationHandler;
$admin = new PHPLogin\AdminFunctions;
if ($request->valid_token() && ($auth->isSuperAdmin() || $auth->hasPermission('View Permissions'))) {
unset($_GET['csrf_token']);
$columns = array(
array( 'db' => 'id', 'dt' => 0 ),
array( 'db' => 'name', 'dt' => 1 ),
array( 'db' => 'description', 'dt' => 2 ),
array( 'db' => 'category', 'dt' => 3 ),
array( 'db' => 'roles', 'dt' => 4 ),
array( 'db' => 'edit', 'dt' => 5 )
);
$data = $admin->getAllPermissions($_GET, $columns);
echo json_encode($data);
} else {
http_response_code(401);
throw new Exception('Unauthorized');
}
} catch (Exception $e) {
error_log($e->getMessage());
echo json_encode($e->getMessage());
}
This is the JS file:
require(['jquery', 'multiselect', 'datatables', 'datatables.net', 'datatables.net-bs4', 'datatables.net-buttons', 'datatables.net-buttons-bs4', 'datatables.net-select-bs4', 'loadingoverlay'], function ($) {
console.log($);
//User Management scripts
/* HANDLES POPOVERS FOR USER INFO */
function userInfoPull(id, elem) {
$.ajax({
type: "POST",
url: "ajax/user_getinfo.php",
data: {"user_id": id, "csrf_token": $('meta[name="csrf_token"]').attr("value")},
async: false,
beforeSend: function () {
$.LoadingOverlay('show', {
image: '../login/images/Spin-0.8s-200px.svg',
imageAnimation: false,
imageColor: '#428bca',
fade: [200, 100]
});
},
complete: function () {
$.LoadingOverlay("hide");
},
success: function (user_info) {
user_info = JSON.parse(user_info);
var user_info_html = '';
for (var prop in user_info) {
if (user_info[prop] != '' && user_info[prop] != null) {
if (prop == 'UserImage') {
user_info_html += '<br><div class="img-thumbnail"><img src="' + user_info[prop] + '" height="240px"></div>';
} else {
user_info_html += '<div><b>' + prop.replace(/([A-Z])/g, ' $1') + ': </b>' + user_info[prop] + '</div>';
}
}
}
$(elem).attr('data-content', user_info_html).popover('show', {"html": true});
},
error: function (xhr, error, thrown) {
console.log(error);
}
});
};
$('body').on('mouseover', "a[id^='info_']", function () {
if ($(this).attr('data-content')) {
$(this).popover('show', {"html": true});
} else {
var id = this.id.split('_')[1];
userInfoPull(id, this);
}
});
$('body').on('mouseleave', "a[id^='info_']", function () {
$(this).popover('hide');
});
/****************************/
/* HANDLES MODAL FOR PERMISSION ROLES */
$('body').on('click', "button[id^='rolesbtn_']", function () {
var id = this.id.split('_')[1];
permissionRolesList(id);
});
function permissionRolesList(id) {
$.ajax({
type: "POST",
url: "ajax/permission_getroles.php",
data: {"permission_id": id, "csrf_token": $('meta[name="csrf_token"]').attr("value")},
beforeSend: function () {
$.LoadingOverlay('show', {
image: '../login/images/Spin-0.8s-200px.svg',
imageAnimation: false,
imageColor: '#428bca',
fade: [200, 100]
});
},
complete: function () {
$.LoadingOverlay("hide");
},
success: function (role_array) {
role_array = JSON.parse(role_array);
$('#permissionsButton').click();
$('#roles-selected').empty();
$('#roles-available').empty();
$('#permission_id').val(id);
$.each(role_array['permission_roles'], function (key, value) {
$('#roles-selected').append("<option value='" + value.id + "'>" + value.name + "</option>");
});
$.each(role_array['diff_roles'], function (key, value) {
$('#roles-available').append("<option value='" + value.id + "'>" + value.name + "</option>");
})
$("select[id^='roles-']").multiselect({
search: {
left: '<input type="text" name="q" class="form-control" placeholder="Search..." />',
right: '<input type="text" name="q" class="form-control" placeholder="Search..." />',
},
fireSearch: function (value) {
return value.length > 3;
}
});
},
error: function (xhr, error, thrown) {
console.log(error);
}
});
};
function editPermission(id) {
var id = id;
$.ajax({
type: "POST",
url: "ajax/permission_getdata.php",
data: {"permission_id": id, "csrf_token": $('meta[name="csrf_token"]').attr("value")},
beforeSend: function () {
$.LoadingOverlay('show', {
image: '../login/images/Spin-0.8s-200px.svg',
imageAnimation: false,
imageColor: '#428bca',
fade: [200, 100]
});
},
complete: function () {
$.LoadingOverlay("hide");
},
success: function (response) {
var respdata = JSON.parse(response);
$("#editPermissionForm").trigger("reset");
$("#edit_permission_id").val(respdata.id);
$("#edit_PermissionName").val(respdata.name);
$("#edit_PermissionDescription").val(respdata.description);
$("#edit_PermissionCategory").val(respdata.category);
$('#editPermission').modal('show');
},
error: function (xhr, error, thrown) {
console.log(error);
}
});
}
$('#saveRoles').click(function () {
var sendData = new FormData();
var formData = [];
var new_roles = [];
var id = $('#permission_id').val();
$('#roles-selected > option').each(function () {
new_roles.push($(this).val());
});
formJson = JSON.stringify(new_roles);
sendData.append('formData', formJson);
sendData.append('permissionId', id);
sendData.append('csrf_token', $('meta[name="csrf_token"]').attr("value"));
$.ajax({
type: "POST",
url: "ajax/permission_updateroles.php",
processData: false,
contentType: false,
data: sendData,
beforeSend: function () {
$.LoadingOverlay('show', {
image: '../login/images/Spin-0.8s-200px.svg',
imageAnimation: false,
imageColor: '#428bca',
fade: [200, 100]
});
},
complete: function () {
$.LoadingOverlay("hide");
},
success: function (response) {
response = JSON.parse(response);
permissionTable.ajax.reload();
$('#permissionsModal').modal('toggle');
},
error: function (xhr, error, thrown) {
console.log(error);
}
});
});
/****************************/
/* DATATABLE INITIALIZATION */
$(document).ready(function () {
permissionTable = $('#permissionList').DataTable({
dom: "<'row'<'col-sm-3'l><'col-sm-6 text-center'B><'col-sm-3'f>>" +
"<'row'<'col-sm-12'tr>>" +
"<'row'<'col-sm-5'i><'col-sm-7'p>>",
order: [[3, "asc"], [1, "asc"]],
columns: [
{
name: "id",
visible: true,
searchable: false,
sortable: false,
render: function (data, type, row) {
return "";
}
},
{
name: "name",
searchable: true
},
{
name: "description",
searchable: true
},
{
name: "category",
searchable: true
},
{
name: "assign roles",
width: "90px",
searchable: false,
render: function (data, type, row) {
return "<button id='rolesbtn_" + row[0] + "' class='btn btn-info'>Assign roles</button>"
}
},
{
name: "edit permission",
width: "40px",
searchable: false
}
],
columnDefs: [{
className: 'select-checkbox',
targets: 0
}],
paging: true,
ajax: {
url: "ajax/permissions_getall.php?csrf_token=" + $('meta[name="csrf_token"]').attr("value"),
error: function (xhr, error, thrown) {
alert(xhr.responseJSON.Error);
}
},
scrollY: "600px",
scrollCollapse: true,
lengthMenu: [[15, 30, -1], [15, 30, "All"]],
select: {
style: "multi",
selector: 'td:first-child'
},
buttons: [
{
extend: 'selectAll',
className: 'selectall',
action: function (e) {
e.preventDefault();
permissionTable.rows({page: 'current'}).select();
permissionTable.rows({search: 'removed'}).deselect();
}
},
"selectNone",
{
text: 'Add New Permission',
action: function (e, dt, node, config) {
$('#newPermission').modal('show');
},
className: "btn-success"
},
{
text: 'Delete Selected',
action: function (e, dt, node, config) {
var selected_array = dt.rows({selected: true}).data();
if (confirm("Are you sure you want to delete the selected permissions?")) {
for (var i = 0, len = selected_array.length; i < len; i++) {
deletePermission(selected_array[i][0], 'rolesbtn_' + selected_array[i][0]);
}
}
},
className: "btn-danger"
}
]
}).on("select", function () {
//console.log("selected");
});
});
/****************************/
function deletePermission(id, btn_id) {
var idJSON = "[" + JSON.stringify(id) + "]";
$.ajax({
type: "POST",
url: "ajax/permissions_delete.php",
data: {"ids": idJSON, "csrf_token": $('meta[name="csrf_token"]').attr("value")},
async: false,
success: function (resp) {
permissionTable.row($('#' + btn_id).parents('tr')).remove().draw();
},
error: function (err) {
console.log(err);
alert(err.responseText);
}
});
}
$("#newPermissionForm").submit(function (event) {
event.preventDefault();
var permissionName = $("#new_PermissionName").val();
var permissionDescription = $("#new_PermissionDescription").val();
var permissionCategory = $("#new_PermissionCategory").val();
$.ajax({
url: "ajax/permissions_add.php",
type: "POST",
data: {
"permissionName": permissionName,
"permissionDescription": permissionDescription,
"permissionCategory": permissionCategory,
"csrf_token": $('meta[name="csrf_token"]').attr("value")
},
beforeSend: function () {
$.LoadingOverlay('show', {
image: '../login/images/Spin-0.8s-200px.svg',
imageAnimation: false,
imageColor: '#428bca',
fade: [200, 100]
});
},
complete: function (resp) {
$.LoadingOverlay("hide");
},
success: function (response) {
permissionTable.ajax.reload();
$("#newPermission").modal('hide');
$("#newPermissionForm")[0].reset();
},
error: function (err) {
console.log(err);
}
});
});
$("#editPermissionForm").submit(function (event) {
event.preventDefault();
var permissionId = $("#edit_permission_id").val();
var permissionName = $("#edit_PermissionName").val();
var permissionDescription = $("#edit_PermissionDescription").val();
var permissionCategory = $("#edit_PermissionCategory").val();
$.ajax({
url: "ajax/permission_update.php",
type: "POST",
data: {
"permissionId": permissionId,
"permissionName": permissionName,
"permissionDescription": permissionDescription,
"permissionCategory": permissionCategory,
"csrf_token": $('meta[name="csrf_token"]').attr("value")
},
beforeSend: function () {
$.LoadingOverlay('show', {
image: '../login/images/Spin-0.8s-200px.svg',
imageAnimation: false,
imageColor: '#428bca',
fade: [200, 100]
});
},
complete: function (resp) {
$.LoadingOverlay("hide");
},
success: function (response) {
permissionTable.ajax.reload();
$("#editPermission").modal('hide');
$("#editPermissionForm")[0].reset();
},
error: function (err) {
console.log(err);
}
});
});
//Role assignment box button logic
(function () {
$('#btnRight').click(function (e) {
var selectedOpts = $('#roles-available option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#roles-selected').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
$('#btnAllRight').click(function (e) {
var selectedOpts = $('#roles-available option');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#roles-selected').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
$('#btnLeft').click(function (e) {
var selectedOpts = $('#roles-selected option:selected');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#roles-available').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
$('#btnAllLeft').click(function (e) {
var selectedOpts = $('#roles-selected option');
if (selectedOpts.length == 0) {
alert("Nothing to move.");
e.preventDefault();
}
$('#roles-available').append($(selectedOpts).clone());
$(selectedOpts).remove();
e.preventDefault();
});
}(jQuery));
// Converts array to object
function toObject(arr) {
var rv = {};
for (var i = 0; i < arr.length; ++i)
rv[i] = arr[i];
return rv;
}
});
Here is a image of the page with the button that is causing problems circled:
Here is what I have tried so far:
Attempted to move the function editPermission around as well as placing it inside the $(document).ready
I have noticed that when I click it in Chrome it seems to open a new page where it executes the script. Sort of weird. Screenshot (Normal page file circled):
What things can I try to solve this?
Currently, I cannot seem to retrieve any of the data from my XML file. Below is the code;
$(document).ready(function() {
setTimeout(function() {
$('#_Q0').autocomplete({
source: function(request, response) {
$.ajax({
url: "brands.xml",
dataType: "xml",
type: "GET",
success: function(xml) {
var results = [];
$(xml).find("brand").each(function() {
if (results.indexOf(request.term.toUpperCase()) >= 0) {
results.push(results);
}
});
response(results);
}
});
},
autoFocus: true,
minLength: 3,
response: function(event, ui) {
if (!ui.content.length) {
var noResult = {
value: "",
label: "No results found"
};
ui.content.push(noResult);
}
}
});
var render = $('#_Q0').autocomplete('instance')._renderMenu;
$('#_Q0').autocomplete('instance')._renderMenu = function(ul, items) {
items.push({
label: 'AUTRE MARQUE',
value: 'AUTRE MARQUE',
last: true
});
render.call(this, ul, items);
};
}, 100);
});
and here is a Plunk;
https://plnkr.co/edit/QFOYcJc7iQ8UQc0e5SKH?p=preview
I was previously working with a JSON source, but now have to switch to XML.
Thanks in advance
Th problem is in processing the xml
$(document).ready(function() {
setTimeout(function() {
$('#_Q0').autocomplete({
source: function(request, response) {
$.ajax({
url: "brands.xml",
dataType: "xml",
type: "GET",
success: function(xml) {
var term = request.term.toLowerCase();
var results = $(xml).find("brand").filter(function() {
return $(this).attr('label').toLowerCase().indexOf(term) > -1;
}).map(function() {
return {
label: $(this).attr('label')
}
}).get();
response(results, xml);
}
});
},
autoFocus: true,
minLength: 3,
response: function(event, ui) {
if (!ui.content.length) {
var noResult = {
value: "",
label: "No results found"
};
ui.content.push(noResult);
}
}
});
var render = $('#_Q0').autocomplete('instance')._renderMenu;
$('#_Q0').autocomplete('instance')._renderMenu = function(ul, items) {
items.push({
label: 'AUTRE MARQUE',
value: 'AUTRE MARQUE',
last: true
});
render.call(this, ul, items);
};
}, 100);
});
Demo: Plunker
I am trying to get the tags from my api. Everything works fine but I cant able to add new tags. Here is what i tried:
$(function(){
var user_email = localStorage.getItem('email');
var api = localStorage.getItem("user_api_key");
var auth = "apikey" +' ' +(user_email+":"+api);
$('#s2id_id_add-places').select2({
multiple: true,
tags: [],
tokenSeparators: [",", " "],
width: "200px",
ajax: {
placeholder: "Click to enter who",
type: "GET",
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization", auth);
xhr.setRequestHeader("Content-Type","application/json");
xhr.setRequestHeader("Accept","application/json");
},
url: "https://example.com/api/v3/places/",
dataType: "json",
contentType: "application/json",
processData: true,
quietMillis: 50,
data: function(term) {
return {
term: term
};
},
results: function(data) {
var results = [];
if(data.objects.length > 0) {
for (i=0; i<data.objects.length; i++) {
results.push({id: data.objects[i].id, text: data.objects[i].label, isNew: true});
}
}
return {
results: results
};
},
});
});
By using the above code, I can only get the tags but I cant able to add the new tags. how can i add the new tags?
Please help
$("#e11_2").select2({
createSearchChoice: function(term, data) {
if ($(data).filter( function() {
return this.text.localeCompare(term)===0;
}).length===0) {
return {id:term, text:term};
}
},
multiple: true,
data: [{id: 0, text: 'story'},{id: 1, text: 'bug'},{id: 2, text: 'task'}]
});
You have to create a function like createSearchChoice, that returns a object with 'id' and 'text'. In other case, if you return undefined the option not will be created.