I have tried to add individual column search in the server side datatable but its not working.
// Apply the filter
$("#empTable tfoot input").on( 'keyup change', function () { alert('test');
tables
.column( $(this).parent().index()+':visible' )
.search( this.value )
.draw();
} );
I need the solution for this how to achieve in the datatable
assume you will filter column name, add this input in top column name
<input type="text" class="name_filter reload_datatable">
change your ajax datatable to this
var table = $(".table").DataTable({
"ajax": {
"url": "urlajax",
"dataType": "json",
"type": "post",
"data": function(d) {
d.name= $('.name_filter').val()
}
}
}
create function on change like this
$(".reload_datatable").change(function(){
table.ajax.reload();
});
and get data in ajax php with
$_POST['name']
Related
Hello all and thanks in advance,
Short story, I am using a plugin to dynamically populate select options and am trying to do it via an ajax call but am struggling with getting the data into the select as the select gets created before the ajax can finish.
First, I have a plugin that sets up different selects. The options input can accept an array or object and creates the <option> html for the select. The createModal code is also setup to process a function supplied for the options input. Example below;
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
let dueDate = {};
for (let i = 1; i < 32; i++) {
dueDate[i] = i;
}
return dueDate;
}
}
});
What I am trying to do is provide an object to the options input via AJAX. I have a plugin called postFind which coordinates the ajax call. Items such as database, collection, etc. are passed to the ajax call. Functions that should be executed post the ajax call are pass through using the onSuccess option.
(function ($) {
$.extend({
postFind: function () {
var options = $.extend(true, {
onSuccess: function () {}
}, arguments[0] || {});
options.data['action'] = 'find';
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof options.onSuccess === 'function') {
options.onSuccess.call(this, obj);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
}
});
}(jQuery));
The plugin works fine as when I look at the output it is the data I expect. Below is an example of the initial attempt.
$('#modalAccounts').createModal({
{
component: 'select',
options: function () {
$.postFind({
data: {
database: 'dashboard',
collections: {
accountTypes: {
where: {status: true}
}
}
},
onSuccess: function (options) {
let dataArray = {};
$.each(options, function (key, val) {
dataArray[val._id.$oid] = val.type;
});
return dataArray;
}
})
}
}
});
In differnt iterations of attempting things I have been able to get the data back to the options but still not as a in the select.
After doing some poking around it looks like the createModal script in executing and creating the select before the AJAX call can return options. In looking at things it appears I need some sort of promise of sorts that returns the options but (1) I am not sure what that looks like and (2) I am not sure where the promise goes (in the plugin, in the createModal, etc.)
Any help you can provide would be great!
Update: Small mistake when posted, need to pass the results back to the original call: options.onSuccess.call(this, obj);
I believe to use variables inside your success callback they have to be defined properties inside your ajax call. Then to access the properties use this inside the callback. Like:
$.ajax({
url: "../php/ajax.php",
type: "POST",
data: options.data,
myOptions: options,
statusCode: {
404: function () {
alert("Page not found");
}
},
success: function (result) {
var obj = $.parseJSON(result);
if (obj.success) {
if (typeof this.myOptions.onSuccess === 'function') {
this.myOptions.onSuccess.call(this);
}
}
},
error: function (xhr, text, err) {
console.log(err);
}
});
It's not clear to me where the problem is without access to a functional example. I would start with a simplified version of what you want to do that demonstrates the proper functionality. My guess is the callbacks aren't setup exactly correctly; I would want to see the network call stack before making a more definitive statement. A few well-placed console.log() statements would probably give you a better idea of how the code is executing.
I wrote and tested the following code that removes most of the complexity from your snippets. It works by populating the select element on page load.
The HTML file:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<select data-src='test.php' data-id='id' data-name='name'></select>
</body>
</html>
<html>
<script>
$('select[data-src]').each(function() {
var $select = $(this);
$select.append('<option></option>');
$.ajax({
url: $select.attr('data-src'),
data: {'v0': 'Alligator', 'v1': 'Crocodile'}
}).then(function(options) {
options.map(function(option) {
var $option = $('<option>');
$option
.val (option[$select.attr('data-id')])
.text(option[$select.attr('data-name')]);
$select.append($option);
});
});
});
</script>
And the PHP file:
<?php
header("Content-Type: application/json; charset=UTF-8");
echo json_encode([
[ 'id' => 0, 'name' => 'Test User 0' ],
[ 'id' => 3, 'name' => $_GET['v0'] ],
[ 'id' => 4, 'name' => $_GET['v1'] ]
]);
Here's a fiddle that also demonstrates the behavior.
I am using Twitter Typeahead (v0.11.1). I have configured an ajax call to get suggestion list upon typing each letter in textbox.
On entering every character an ajax call gets send and it brings results. If typed continuously in textbox then previous ajax calls are aborted and new ajax call is sent on pause of last character entered.
So, while this process if found some results after two characters and paused then it showing suggestion list. Now, if continue to type then exiting list goes away.
I would like to retain suggestion list for each ajax call till user not selected an item from it.
Below is the code used:
var typeahead_pre_written_xhr = null;
var helper_typeahead = $( "#input-box" ).typeahead({
highlight: true,
minLength: 0
},
{
name: "Search Suggestions",
display: ["title"],
templates: {
empty: function () {
return '<div class="tt-suggestion tt-selectable">No matching helper comment found</div>';
}
},
source: function (query, processSync, processAsync) {
if( typeahead_pre_written_xhr != null ) {
typeahead_pre_written_xhr.abort();
typeahead_pre_written_xhr = null;
}
action_url = "suggestion_list";
return typeahead_pre_written_xhr = $.ajax({ cache: false
, url: action_url + query
, type: 'POST'
, data: { 'search': query }
, dataType: 'json'
, success: function (data)
{
return processAsync(data.res);
}
});
}
}).bind("typeahead:selected", function(evt, item) {
// do some stuff
});
In select2 I have tags loaded by AJAX, if the tag is not found in the db then the user has the option to create a new one. The issue is that the new tag is listed in the select2 box as a term and not as the id (what select to wants - especially becomes a problem when loading the tags again if the user wants to update since only the term and not the id is stored in the db). How can I, on success of adding the term, make it so that select2 recieves the ID and submits the ID instead of the tag name/term?
$(document).ready(function() {
var lastResults = [];
$("#project_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: "framework/helpers/tags.php",
dataType: "json",
data: function(term) {
return {
term: term
};
},
results: function(data) {
return {
results: data
};
}
},
createSearchChoice: function(term) {
var text = term + (lastResults.some(function(r) {
return r.text == term
}) ? "" : " (new)");
return {
id: term,
text: text
};
},
});
$('#project_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({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(data) {
},
error: function() {
alert("error");
}
});
} else {
console.log("Removing the tag");
var selectedTags = $("#project_tags").select2("val");
var index = selectedTags.indexOf(e.added.id);
selectedTags.splice(index, 1);
if (selectedTags.length == 0) {
$("#project_tags").select2("val", "");
} else {
$("#project_tags").select2("val", selectedTags);
}
}
}
}
});
});
Heres part of the switch that does the adding
case 'add':
if (isset($_GET['term'])) {
$new_tag = escape($_GET['term']);
if (Nemesis::insert('tags', 'tag_id, tag_content', "NULL, '{$new_tag}'")) {
// we need to send back the ID for the newly created tag
$search = Nemesis::select('tag_id', 'tags', "tag_content = '{$new_tag}'");
list($tag_id) = $search->fetch_row();
echo $tag_id;
} else {
echo 'Failure';
}
exit();
}
break;
UPDATE: I've done a bit of digging, and what confuses me is that the select2 input does not seem to store the associated ID for the tag/term (see below). I know I could change the attribute with the success callback, but I don't know what to change!
As you have said, you can replace that value, and that is what my solution does. If you search the Element Inspector of Chrome, you will see, bellow the Select2 field, an input with the id project_tags and the height of 1.
The weird thing is that the element inspector of Chrome does not show you the values of the input, as you can see below:
However, you do a console.log($("#project_tags").val()) the input has values (as you see in the image).
So, you can simply replace the text of the new option by the id, inside the success function of the ajax call placed within the $('#project_tags').on("change") function. The ajax call will be something like:
$.ajax({
url: 'framework/helpers/tags.php',
data: {
action: 'add',
term: e.added.id
},
success: function(tag_id) {
var new_val = $("#project_tags")
.val()
.replace(e.added.id, tag_id);
$("#project_tags").val(new_val);
},
error: function() {
alert("error");
}
});
Please be aware that this solution is not bullet proof. For example, if you have a tag with the value 1 selected, and the user inserts the text 1, this will cause problems.
Maybe a better option would be replace everything at the right of the last comma. However, even this might have cause some problems, if you allow the user to create a tag with a comma.
Let me know if you need any more information.
I am trying to build a set of linked/chained multiselect boxes using MagicSuggest and a php query. So, first I build a MagicSuggest box with a function for when ms1 is changed:
$(document).ready(function() {
var ms1 = $('#ms1').magicSuggest({
data: 'datams1.php',
displayField: 'name' });
$(ms1).on('selectionchange', function(event, combo, selection){
run(selection);});
});
Then I build a new MagicSuggest box by running a php query that returns a json object:
function run(country) {
$.getJSON("query.php", { id: country[0].id}, callbackFuncWithData );
}
function callbackFuncWithData(region) {
var ms2 = $('#ms2').magicSuggest({
data: region,
displayField: 'name'
});
}
This works once I make an initial selection, but does not update if I change the selection. I have checked and within my "callbackFuncWithData" I am producing an updated "region" json object. So it might just be that I need to refresh/reload my #ms2 object.
My questions are:
Is there a way to force an refresh of the MagicSuggest data?
Is there a better/cleaner/more efficient way to use the results of one MagicSuggest box to query and return the data for a second, linked MagicSuggest box?
Thanks!
use setData() method to dynamically set the data when needed.
you can always use a library like angular to bind the component properties together.
This code makes 2 linked combos with the same data, but one of them shows the "name" field and the other one shows the "name1" filed.
function reflectSelection(ms1, ms2){
var val = parseInt(ms1.getValue());
var val1 = parseInt(ms2.getValue());
if(!isNaN(val)){
if(val != val1){
ms2.clear(true);
ms2.setSelection(ms1.getSelection());
}
}
else
{
ms2.clear(true);
}
}
var msName = $('#ms-onselectionchange').magicSuggest({
maxSelectionRenderer: function(){ return ''; },
useTabKey: true,
noSuggestionText: '',
strictSuggest: true,
maxSelection: 1,
allowFreeEntries: false,
placeholder : '',
data: [{'id':0, 'name':'Paris', 'name1':'Paris5'}, {'id':1, 'name':'New York', 'name1':'New York5'}],
});
var msName1 = $('#ms-onselectionchange1').magicSuggest({
maxSelectionRenderer: function(){ return ''; },
useTabKey: true,
noSuggestionText: '',
displayField: 'name1',
strictSuggest: true,
maxSelection: 1,
allowFreeEntries: false,
placeholder : '',
data: [{'id':0, 'name':'Paris', 'name1':'Paris5'}, {'id':1, 'name':'New York', 'name1':'New York5'}],
});
$(msName).on('selectionchange', function(e,m){
reflectSelection(msName, msName1);
});
$(msName1).on('selectionchange', function(e,m){
reflectSelection(msName1, msName);
});
I'm having trouble implementing autocomplete in jqgrid. I've walked researching, alias until I based this question on a site that currently do not meet. The problem is this, I have to use the autocomplete several times throughout the application I'm developing. And now I have this function:
Javascript:
function autocomplete_element(value, options) {
var $ac = $('<input type="text"/>');
$ac.val(value);
$ac.autocomplete({
source: function(request, response)
{
$.getJSON("autocomplete.php?id=estrategico",
{ q: request.term }, response);
}
});
return $ac;
}
Jqgrid:
jQuery("#obj_oper_org").jqGrid({
(...)
{name:'COD_OBJ_EST',index:'COD_OBJ_EST', hidden: true, editable:true, editrules:{required:true, edithidden:true}, edittype : 'custom', editoptions : {'custom_element' : autocomplete_element}},
What was intended to pass a parameter to the javascript function more in order not to repeat forever the same function for each field because I need to be constantly changing url. Is it possible to make something of the genre? Sorry for the question but I do not have much experience in javascript, so I have some difficulties
First of all you don't need to use edittype : 'custom' to be able to use jQuery UI Autocomplete. Instead of that you can use just dataInit.
You can define myAutocomplete function for example like
function myAutocomplete(elem, url) {
setTimeout(function () {
$(elem).autocomplete({
source: url,
minLength: 2,
select: function (event, ui) {
$(elem).val(ui.item.value);
$(elem).trigger('change');
}
});
}, 50);
}
and then use
{ name:'COD_OBJ_EST', hidden: true, editable: true,
editoptions: {
dataInit: function (elem) {
myAutocomplete(elem, "autocomplete.php?id=estrategico");
}
}}
Be careful that the name of parameter which will be send to the server is the standard name term instead of the name q which you currently use. I personally don't see any need to change the default name of the parameter.