How to get Tabulator to populate a headerFilter ONLY when it is clicked - tabulator

I'm using Tabulator with ajax to pull paginated data to the table. I'd like to use headerFilters with valuesURL but the AJAX request is a POST not a GET and valuesURL only works with GET. He alternative is to use values, but that seems to want to pull the values each time the data is refreshed. I need the headerFilter options to be refreshed ONLY when it the input box is clicked. Psuedo-process below...
Load all data
user clicks one headerFilter "City"
ajax called via POST to get list of relevant values for "City"
headerFilter is populated with list, which is then presented to the user via the drop down
Is this possible?
I've tried using a function in headerFilterParams to get the values but each headerFilter is refreshed when the data is refreshed as opposed to just the one that was clicked.

You can use the headerFilter in combination with a custom header filter component that makes the AJAX call to get the values when the header filter is clicked.
Example:
var cityFilter = function(headerValue, rowValue, rowData, filterParams){
// code to filter data based on selected city
};
// Custom header filter component
var customCityFilter = function(header) {
var self = this;
self.element = document.createElement("input");
self.element.setAttribute("type", "text");
self.element.setAttribute("placeholder", "Type to filter");
// Add click event to make the AJAX call when the input box is clicked
self.element.addEventListener("click", function() {
// Make the AJAX call to get the list of relevant values for "City"
// Replace with your own AJAX code
// Example using jQuery
$.ajax({
type: "POST",
url: "your_url",
data: {},
success: function(data) {
// Populate the headerFilter with the list of values
header.setFilterValues(data);
}
});
});
// Return the custom filter component
return self.element;
};
// Initialize the table with the custom header filter
var table = new Tabulator("#example-table", {
columns:[
{title:"City", field:"city", headerFilter:"custom", headerFilterParams:{component:customCityFilter}, headerFilterFunc:cityFilter},
// other columns
],
});

Related

React-Bootstrap-Table-Next Only One Row of Data in Table

I am trying to create a table for my website and for some reason it is only showing the first row of data.
This is how I am formatting the columns of the data:
const { items } = this.props.item;
// console.log({ items });
// react - bootstrap - table - next
const columns = [{
dataField: 'team',
text: 'Team',
sort: true,
formatter: (cellContent, row, rowIndex) => (
Object.values(row.team)[rowIndex]
)
}, {
dataField: 'current_Rank',
text: 'Current Rank',
sort: true,
formatter: (cellContent, row, rowIndex) => (
Object.values(row.current_Rank)[rowIndex]
)
}, {
dataField: 'new_Rank',
text: '321 Rank',
sort: true,
formatter: (cellContent, row, rowIndex) => (
Object.values(row.new_Rank)[rowIndex]
)
}];
This is how I am returning the table so that it renders the table:
return (
<BootstrapTable
keyField="team"
data={items}
columns={columns}
striped
hover />
)
}
}
The data:
Picture from the console
Live site: https://nhl-321-pointsystem.herokuapp.com/
I looked up your network response for /api/items API call, and found out that the data contains only one item. This being one of the reason you're seeing a single row when the table is rendered.
Please note the, another reason for the issue is, react-bootstrap-table-next key
data accepts a single Array object. And not array of single object.
You should re-arrange your data so that key 'team' will be present for all items in the array. And rest of the column header values (e.g. current_Rank) are available for each like.
Something like a reformat function I created in the sandbox available here.
Plus point - After you apply the reformat function, you won't need formatter for each column unlike your previous solution.
Alternate but recommended solution would be to send the formatted response from the API endpoint only, instead of re-parsing and creating new object to fit the needs of UI.
Sandbox link - https://codesandbox.io/embed/32vl4x4oj6

Trying to update a mongodb document field via pug/node.js button click

This is a document from my todo mongodb:
"_id" : ObjectId("5a1e96f856f24c43b886eb54"),
"title" : "Drink coffee",
"note" : "Tomorrow morning",
"open" : true,
"duedate" : "2017-12-03"
This is the pug code that populates a todo list page
each todo in todolist
if todo.open
div
a(href="#") #{todo.title}
div
p(style='white-space:pre;')
| #{todo.note}
| Due: #{todo.duedate}
button(id="doneButton") Done
The above works fine. The todo page displays all todo items as expected.
What I want to do:
When user clicks on 'Done' button, I want to update that particular document to "open": false.
(I want to do this onclick, and not by loading the item on a new edit page with an edit button. When todo list page reloads, that todo item is removed from the list. I do not want to delete the document as I need to archive it later on.)
So my questions are:
How do I code the 'Done' button on the pug page so that it gets
associated with the particular document that needs to be updated?
How do I structure the POST code on my index.js so that it listens for
the button click and performs the relevant document update?
UPDATE
OK, so I don't know enough to understand kentor's reply (but thank you anyway!). I did a bit of research though and some copying and pasting, and I have moved the problem a couple of steps forward - I hope.
New pug code:
each todo in todolist
if todo.open
a(href="#") #{todo.title}
p #{todo.note}
p Due: #{todo.duedate}
form#form_update_item(name="updateitem", method='post', action='/updateitem')
input#input_name(type="hidden", placeholder="", name="_id", value="#{todo._id}")
button(type="submit") Done
index.js code
router.post('/updateitem', function(req, res) {
var MongoClient = mongodb.MongoClient;
var ObjectId = require('mongodb').ObjectId;
var url = 'mongodb://localhost:27017/tododb';
MongoClient.connect(url, function(err, db) {
if (err) {
console.log("can't connect", err);
}
else {
console.log('Connected to server. Woohoo!');
var collection = db.collection('todolist');
collection.findOneAndUpdate(
{"title": "Make smoothie"},
{
$set: {
"open": false
}
},
function(err, result) {
if (err) {
console.log(err);
} else {
res.redirect("todolist");
}
db.close();
});
}
});
});
What happens now:
On button click, doc with title "Make Smoothie" changes to "open": false. So button triggers the change I want. Bang! But this is only a partial solution to help me isolate the problem.
What I still need:
On button click, I want the doc's ID whose button was clicked to replace {"title": "Make smoothie"} so that the "open": false change can be made. Something like {_id: "doc ID coming from button blah blah"}.
UPDATE 2
Discovered that I was using Jade syntax not Pug, so instead of this
value="#{todo._id}
I should be using
value=todo._id
So now index.js can console.log the ID the Pug form is passing. Last challenge is to use that ID to change the corresponding mongodb document as described above.
I finally solved it
Last step, I replaced
{"title": "Make smoothie"}
with
{"_id": ObjectId(req.body._id)}
and sure enough, every time I click on a button, the server updates the corresponding document's "open": false
You could just attach a data attribute to the HTML button like this:
button(id="doneButton", data-id=todo._id) Done
Then you would just attach an event listener to this button and send a POST request containing this data-id. Using Jquery it could look like this:
.script
$('#doneButton').on("click", function (element) {
var data = $(this).data("id");
$.ajax({
type: "POST",
url: "your-url",
data: { todoId: data },
success: responseHandler
})
})

Getting select2 to refresh data using ajax on dropdown

I have the following JavaScript to populate dropdown list using select2 https://select2.github.io/
It works fine, and populates the list on the first load of the page.
From then on it does not refresh the list even when data is added because it only does the AJAX call once. Even if I reload the page, the dropdown list is not refreshed and the AJAX call is not triggered (unless I close and reopen the browser, then the AJAX call is fired)
Is there a way to undertake the ajax call each time the dropdown is opened. I tried the .on("select2-open") option but didn't have any luck.
Sorry JavaScript is not something I know much about.
$("#Location").select2({
placeholder: "Select a known location", // Placeholder text
allowClear: true, //Allows deselection of chosen address
ajax: {
url: '/AlertInterface/NewAlertLocations', // Where we want the ajax to call
dataType: 'json', // The datatype we are expecting to be returned
type: "GET", //Just a get method
//Data: allows us to pass a parameter to the controller
data: function (query) {
console.log(query)
return { search: query.term }
},
//processes the results from the JSON method and gives us the select list
processResults: function (data) {
console.log(data)
return {
results: JSON.parse(data)
};
}
}
});
EDIT:
I did try to use
$("#Location").on("select2:open", function () { $("#Location").select2(); })
but that didn't help. :-(
You have a syntax error in your code.
Please check the below code,
$("#Location").select2({
placeholder: "Select a known location", // Placeholder text
allowClear: true, //Allows deselection of chosen address
ajax: {
url: '/AlertInterface/NewAlertLocations', // Where we want the ajax to call
dataType: 'json', // The datatype we are expecting to be returned
type: "GET", //Just a get method
//Data: allows us to pass a parameter to the controller
data: function (query) {
console.log(query)
return { search: query.term }
},
//processes the results from the JSON method and gives us the select list
processResults: function (data) {
console.log(data)
return {
results: JSON.parse(data)
};
}
}
});

Deleting a row from JQuery Jtable Client Side only

I am trying to delete a row from JTable in client side only.But somehow i am not able to get the value of the key of the selected record.See the code below
deleteAction : function (postData) {
var row_id = $('.jtable-data-row').attr('data-record-key');
$('#AuthorTableContainer').jtable('deleteRecord', {
key: row_id,
clientOnly:true
});
}},
The problem is when the table contains the multiple record.then in that case "tr" attributes become
"jtable-data-row jtable-row-even" in that case i am not able to get the value of the data-record-key.
Is there any other way to delete a row from JTable from client side only?
Here it is
deleteAction : function (data) {
$('#AuthorTableContainer').jtable('deleteRecord', {
key: data.keyValue,
clientOnly:true
});
}},
In order to remove a row from a JTable, you will need to remove the target row from the underlying TableModel. If, for instance, your TableModel is an instance of DefaultTableModel, you can remove a row by doing the following:
((DefaultTableModel)myJTable.getModel()).removeRow(rowToRemove);
If you want to delete any record from jtable and you only know key that's what with my case just pass it like below.
$('#detailVoucherTable').jtable('deleteRecord', { key: 0, clientOnly:true });
Regards
mOOn
digitaal.logix#gmail.com

jQuery Autocomplete - Show Data Based on Selection

I have a standard jQuery autocomplete setup similar to the below:
$("input#autocomplete").autocomplete({
source: source,
minLength: 5 ,
select: function( event, ui ) {
alert(ui.item.value);
}
});
What I would like is, when the value is chosen, a data-table within the page appears and get populated with data from a database using the value as a search parameter.
So for instance if I select "RED", the table would then show and display data from a query such as SELECT * FROM TABLE WHERE COLUMN='RED'
The query is simplified but can anyone please point me in the right direction?
For this purpose you should request a kind of search page which will act as JSON endpoint for e.g.
$("input#autocomplete").autocomplete({
source: source,
minLength: 5 ,
select: function( event, ui ) {
var _value = ui.item.value;
$.post('services/populate_table.php', // endpoint URL
{ someParameterToTransmit: _value }, // some data to transmit
function(data) { // on complete handler
$('.result').html(data); // populate retrieved data in any form you need
} // on complete function
); // post
} // on select (autocomplete)
}); // autocomplete
Data from endpoint also can be retrieved as JSON.
You can read documentation for more information about request method.
If I understand you correctly, you're looking for $.post.
For example, your jQuery would be:
$("input#autocomplete").autocomplete({
source: source,
minLength: 5 ,
select: function( event, ui ) {
$.post("autocomplete.php", { option: ui.item.value }, function(data){
$("table").html( data[0] );
// sets the content of a table element to the first matched row
});
}
});
And in autocomplete.php, you would have something like this:
// DB connect
// use $_POST['option'] here for the selected option
$sth = mysql_query("SELECT ...");
$r = mysql_fetch_assoc($sth);
print $r;
What we do here is request the page autocomplete.php and POST the data, which in this case is the selected value. autocomplete.php grabs that POSTed value and searches the database (you can customize that query to fit your needs). The page then prints an array of the matched rows, which is the data received by the jQuery, and can be traversed as a Javascript array.

Resources