Refresh ajax datatable - datatable

I'm running the ajax datatable in a JavaScript function that is called from the onblur of input for parameters I send two pieces of information that go into the url ajax and depending on these parameters, different data will be returned.
function abrirModal(idLista,value)
{
var lastIdx = null;
var table = window.parent.$("#tlistaselect").DataTable( {
"order": [[ 1, "asc" ]],
"aProcessing": true,
"aServerSide": true,
"paging": false,
"searching": false,
"retrieve": true,
"stateSave":true,
"ajax": ip+"/datosListaSelect?idLista="+idLista+"&condicion="+value,
...................
}
When I run for the first time Ajax, brings the data you need depending on the values of the parameters but when I try to run again not run the ajax, I just redisplay the data had already consulted earlier.
How I can do to make the ajax to run again when I call the function again with the onblur?

You need to add one more tag in DataTable section:
"destroy": true
I think it will work!

Related

Ideal way to ajax load a view in Drupal 8 with contextual filters

I have a taxonomy called category.
I have a menu with links to each of these taxonomy items.
The Taxonomy page for each of these items has that menu and also contains a view which uses a contextual filter from the URL to filter the content of the view to content with that taxonomy term.
I wanted to Ajax load the view content when one of these menu items is clicked.
I've been able to achieve the desired result by enabling ajax on the view and using the following JavaScript.
(function ($) {
Drupal.behaviors.course_browser = {
attach: function (context, settings) {
// should only be one menu, but guard against 0, and avoid the if statement.
context.querySelectorAll(".menu--categories").forEach((menu) => {
// for each link in the menu
menu.querySelectorAll(".nav-link").forEach((link) => {
// on click
link.addEventListener("click", (event) => {
event.preventDefault();
// fetch the taxonomy term id from menu link
let tid = event.target.dataset.drupalLinkSystemPath.replace(
"taxonomy/term/",
""
);
// make the ajax call
$.ajax({
url: "/views/ajax",
type: "post",
data: {
view_name: "course_browser",
view_display_id: "block_1",
view_args: tid,
},
success: (response) => {
response.forEach((action) => {
// the response contains a number of commands; I'm not sure
if (
action.command === "insert" &&
action.method === "replaceWith"
) {
let viewElement = document.querySelector(VIEW_SELECTOR);
// update the html of the course browser
viewElement.innerHTML = action.data;
// update the url in the browser
window.history.pushState("", "", event.target.href);
// seperate function to adjust my page title
updatePageTitle(event.target.textContent);
// call drupal behaviours passing context to ensure all the other js code gets a chance to manipulate the new content
Drupal.attachBehaviors(viewElement);
}
});
},
error: function (data) {
console("An error occured fetching the course browser");
},
});
});
});
});
},
};
})(jQuery);
I'm looking for feedback on my approach here; my main concern at the moment is the way I handle the response. When I look at the response I receive something like that shown below:
0: {command: "settings", settings: {…}, merge: true}
1: {command: "add_css", data: "<link rel="stylesheet" media="all" href="/core/modules/views/css/views.module.css?qcog4i" />↵"}
2: {command: "insert", method: "append", selector: "body", data: "<script src="/core/assets/vendor/jquery/jquery.min…/js/modules/views/ajax_view.js?qcog4i"></script>↵", settings: null}
3: {command: "insert", method: "replaceWith", selector: ".js-view-dom-id-", data: "The HTML"}
As you can see, I'm manually handling the response by cherry picking the part I want and replacing the HTML of view. Based on what I've seen around Drupal, I think there should be something I can pass this response to that handles it automatically. When I look at the window object of the browser, I can see Drupal.AjaxCommands which looks like it was designed to handle this, but I'm not sure how I should be using this.
I also note that in the case I can simply pass this response to something to have those AjaxCommands executed, the selector ".js-view-dom-id-" isn't right. So I could tweak the response before I pass it, or if someone knows a way to adjust the ajax request to perhaps get the right selector, that would be ideal.
Sorry if this info is readily available somewhere...there are quiet a few resources around related to Drupal and Ajax but I haven't been able to find examples of exactly what I'm doing here, the circumstances always seem to differ enough that I can't use them.
Thanks for any help.

Django / Ajax / Datatable

I am trying to use following code in order to make a GET request to my django-based local server & render the obtained JSON-formatted data as a table:
$(document).ready(function (){
var rows_selected = [];
var table = $('#example').DataTable({
'ajax': $("#active_subscriptions_url").attr("data-ajax-target"),
'cache': true,
'columnDefs': [{
'targets': 0,
'searchable':false,
'orderable':false,
'width':'1%',
'className': 'dt-body-center',
'render': function (data, type, full, meta){
return '<input type="checkbox">';
}
}],
'order': [1, 'asc'],
'cache': true,
'rowCallback': function(row, data, dataIndex){
// Get row ID
var rowId = data[0];
// If row ID is in the list of selected row IDs
if($.inArray(rowId, rows_selected) !== -1){
$(row).find('input[type="checkbox"]').prop('checked', true);
$(row).addClass('selected');
}
}
});
Unfortunately, it can not properly refer to the data, because each time this AJAX function adds a timestamp ad the end of a url:
http://127.0.0.1:8000/accounts/?_=1530637137189
I can not get rid of it - I have tried using 'cache' paremeter in Ajax, but it does not work.
Moreover, I ve tried to extend my urls.py with following position:
url(r'^accounts/(?P<timestamp>\?_=[0-9]*)/$', ShowSubscriptions.as_view(), name='show_subscriptions'),
But it does not match the coming request at all.

Kendo UI: How to get the text input from the Multiselect

I'm trying to use Kendo UI MultiSelect to select some stuff from an API. The API won't return all items because they are too much. It will only return those that contains the searchTerm.
I'm trying to figure out how to send the input text in a Kendo UI Multiselect. When I say the input text, I mean what the user typed in the input before selecting anything from the list. That text has to be passed on to the DataSource transport.read option.
See this Codepen to understand
https://codepen.io/emzero/pen/NYPQWx?editors=1011
Note: The example above won't do any filtering. But if you type "bre", the console should log searching bre.
Use the data property in the read transport options, this allows you to modify the query being sent by returning an object that will later on be serialized in the request.
by default read are GET requests so it will be added to the queryString of your url specified.
If it were to be a POST it would be added to the POST values.
<div id="multiselect"></div>
<script>
$('#multiselect').kendoMultiSelect({
dataTextField: 'first_name',
dataValueField: 'id',
filter: "startswith",
dataSource: {
serverFiltering: true, // <-- this is important to enable server filtering
schema: {
data: 'data'
},
transport: {
read: {
url: 'https://reqres.in/api/users',
// this callback allows you to add to the request.
data: function(e) {
// get your widget.
let widget = $('#multiselect').data('kendoMultiSelect');
// get the text input
let text = widget.input.val();
// what you return here will be in the query string
return {
text: text
};
}
}
}
}
});
</script>

Datatables ajax authenticated data display username

I'm building a datatable using ajax data which is provides customer data after authentication. Is there a way to pickup the username during authentication and display it on the page to clearly indicate that the table contains the customer's personalised data?
Can I have the username stored in the ajax data file as the "dataSrc".
{
"username": [
[
"item1",
"item2",
"item3"
]
]
}
Then it could be picked up as a variable and then displayed on the page.
var oTable = $('#example').DataTable({
"ajax": {
"url": "data/customerdata.txt",
"type": "POST",
"dataSrc": function(...
},
Thank you in advance for your help!
Something like this should work:
"dataSrc": function (json){
console.log(json.username); // Should output your array e.g. ["item1", "item2","item3"]
$.each(json.username, function(k, v){
console.log(k, v) // Should output each element of your array e.g 0 and item1 then 1 and item2 and then finally 2 and item3
// You can display what you want on the page from this data.
});
return json.data; // returns the data to the table so it can be drawn.
}
Hope that that helps.

How to reduce data table load time?

I am working with data table plugin. Initially what I tried is to update the data table plugin from a flat text file. The text file would look like below.
{
"data":[
{
"reference":"#VIP-123",
"application":"Development Aspects",
"applicationType":"Current Application"
},
{
"reference":"#VIP-123",
"application":"Development Aspects",
"applicationType":"Current Application"
}
]
}
I have a HTML file inside this I am writing JavaScript like below.
$(document).ready(function() {
var table=$('#app-table').DataTable( {
"bProcessing": true,
"bPaginate":true,
"bServerSide": false,
"sAjaxSource": "./data/arrays.txt",
"deferRender": true,
"columns": [
{ "data": "reference" },
{ "data": "application" },
{ "data": "applicationType" },
],
"order": [[ 3, "desc" ]],
"ordering": true,
"bFilter": true
} );
The data table is rendering fine until am not having more than 20,000 rows in the table. As the number of rows will increase in the table then data table took more time to load.
What I notices by going through with several site is that we can reduce the load time by using server side processing and for that I need to go with a server which is not possible in my case because I am rendering data from a flat text file. Then I thought to look for static data storage.
So coming to the problem is using indexedDB can we resolve the performance issue and if answer is yes than can anyone let me know how?
I am able to work with indexedDB but unable to integrate with jQuery data table. I mean what I need to make change in the JavaScript. If we can make server side processing with indexedDB then what will be the script?
first read your local file in the following manner:
var rawFile = new XMLHttpRequest();
rawFile.open("GET", file, false);
rawFile.onreadystatechange = function ()
{
if(rawFile.readyState === 4)
{
if(rawFile.status === 200 || rawFile.status == 0)
{
var allText = rawFile.responseText;
}
}
}
Then, use JQuery to parse "allText" into JSON.
Refer this link for parsing into JSON.
Now, create database using "indexedDB API" as mentioned below:
var request = indexedDB.open("<mention_your_db_name_here");
request.onupgradeneeded = function() {
// The database did not previously exist, so create object stores and indexes.
var db = request.result;
var store = db.createObjectStore("books", {keyPath: "reference"});
var titleIndex = store.createIndex("by_reference", "reference", {unique: true});
// Populate with initial data.
store.put({reference: "#VIP-123", application: "Development Aspects", applicationType: "Current Application"});
};
request.onsuccess = function() {
db = request.result;
};
for more details on "indexedDB API", please refer this link

Resources