Django / Ajax / Datatable - ajax

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.

Related

Datatable info is lost after i do a flitered search

I'm having a problem with a data table, whenever I use the search function in my table all the data is lost the moment I input anything on the search bar, I create this data table dynamically using AJAX, first I do a request to the server to get the data for my table.
function traerBecas() {
var ciclo = document.getElementById("ciclo").value;
$.ajax({
url: '/becas/listaBecas',
type: 'GET',
data: {
"ciclo": ciclo,
},
dataType: 'JSON',
success:function(response){
llenarTabla(response);
}
});
}
Once I get the response as a JSON I pass the info to another function to build each table row and insert it into the table.
function llenarTabla(jsonArray) {
var tabla = document.getElementById('becaBody');
tabla.innerHTML = "";
jsonArray.forEach(element => {
var trElement = document.createElement('tr');
var tdCLVBECA = document.createElement('td');
var tdINSTIT = document.createElement('td');
var tdCICLO= document.createElement('td');
var tdSECCION = document.createElement('td');
var tdFECINI = document.createElement('td');
var tdFECFIN = document.createElement('td');
var tdACCIONES = document.createElement('td');
var linkEditar = document.createElement('a');
var linkEliminar = document.createElement('a');
tdCLVBECA.innerText = element.CLV_BECA;
tdINSTIT.innerText = element.INSTIT.toUpperCase();
tdCICLO.innerText = element.CICLO;
tdSECCION.innerText = element.SECCION;
tdFECINI.innerText = element.FEC_INI;
tdFECFIN.innerText = element.FEC_FIN;
linkEditar.setAttribute("href","/becas/editar/"+element.CLV_BECA);
linkEditar.setAttribute("data-bs-toggle", "tooltip");
linkEditar.setAttribute("data-bs-placement", "top");
linkEditar.setAttribute("title", "Eliminar");
linkEditar.innerHTML = "<i class='fas fa-pen'></i>";
linkEliminar.setAttribute("onclick", "eliminacion("+element.CLV_BECA+")");
linkEliminar.setAttribute("data-bs-toggle", "tooltip");
linkEliminar.setAttribute("data-bs-placement", "top");
linkEliminar.setAttribute("title", "Editar");
linkEliminar.innerHTML = " <i class='fas fa-trash'></i>";
tdACCIONES.appendChild(linkEditar);
tdACCIONES.appendChild(linkEliminar);
trElement.appendChild(tdCLVBECA);
trElement.appendChild(tdINSTIT);
trElement.appendChild(tdCICLO);
trElement.appendChild(tdSECCION);
trElement.appendChild(tdFECINI);
trElement.appendChild(tdFECFIN);
trElement.appendChild(tdACCIONES);
tabla.appendChild(trElement);
});
}
Then I have the function to transform my table to a data table, and up to this moment, everything works alright. EDIT: Forgot to mention that this info is run first when the page is loaded, the table at the beginning is empty and then is filled with the info I requested.
$(document).ready(function() {
$('#myTable').DataTable({
responsive: true,
language: {
url: '//cdn.datatables.net/plug-ins/1.10.25/i18n/Spanish.json'
}
});
});
Then, once I have my table built, I try to use the search function that it generates, but then I run into the problem that the table doesn't find the info, loses the data, and doesn't return to the previous state once I delete the prompt on the search bar.
I'm at a loss of what to do, I have other data tables that don't have this problem, however, those tables aren't built using AJAX, they get their info directly from the controller with the compact() function in the PHP controller, and using Blade directives like #foreach loops.
You should open up your browser's dev tools and inspect the network request to your endpoint:
url: '/becas/listaBecas'
It could be a number of things, the network tab will show you if there is an error with the AJAX request. If the AJAX request has no error, you will want to look at your endpoint and debug the query that is being run to see why it's not returning any results.
Would also be a good idea to add a error catch for the AJAX call:
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("There was an error with the request");
}

Cannot using (id) that selected from (select option) and put it into my list object to find price?

i am work on laravel framework i want to get price by selected option , in the script i get (id) but i cannot use this (id) in to my object to get the price.
<script>
$(document).ready(function() {
$('select[name="surgSelect"]').on('change', function() {
var id=document.getElementById("surgSelect").value;
var price={{$list->where('sdf_id',id)->pluck('price')->first()}}
document.getElementById("price").value = price;
});
});
</script>
Error Exception
"Use of undefined constant id - assumed 'id' (this will throw an Error in a future version of PHP)
What you're trying to achieve is not possible because the PHP code is outputted to the HTML on the server side way before the idĀ from your javascript becomes available so what you need to do is to send an Ajax request to get the price like so
$(document).ready(function() {
$('select[name="surgSelect"]').on('change', function() {
var id = document.getElementById("surgSelect").value;
$.post('/getPrice', {id: id})
.done(function(response) {
document.getElementById("price").value = response;
});
});
});
And in the Backend (for example routes\web.php)
Route::post('getPrice', function() {
return $list->where('sdf_id', request('id'))->pluck('price')->first();
});

how to select all records in the grid in order to export the data

I am trying to select all the data present in the jqgrid table in order to export in to an excel file. But the data present in the first page of the grid is only getting exported. i.e., if a total of 25 records are present in the grid and 5 records are present in the first page, then only first 5 records are getting exported.
The following code is responsible for displaying records 'only' in the first page of the grid..
var gridData = $("#list").jqGrid('getRowData');
The following code is responsible for displaying records present in all the pages in the grid..
var gridData1 =jQuery("#list").jqGrid('getGridParam','data');
how to use the above code such that I can select all the records present in the grid. also, I am trying to apply filter on the records present in the grid. In such a case, how to get the filtered number of records in order to export them..?
Thanks,
You can do it server side.
<script type="text/javascript">
$(document).ready(function () {
$('#list').jqGrid({
caption: "test",
// ...
}).navGrid(
// ...
}).jqGrid('navButtonAdd', '#pager', {
caption: "", buttonicon: "ui-icon-print", title: "export",
onClickButton: function () {
$("#list").jqGrid('excelExport', { url: 'path......' });
}
});
});
</script>
excelExport method, sends the current page number, sort field, filtering, etc to the specified url. now you have time to process these parameters and create a new output.
You may want to try below script and function:
<script type='text/javascript'>
var tableToExcel = (function () {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
return function (table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = { worksheet: name || 'Worksheet', table: table.outerHTML }
window.location.href = uri + base64(format(template, ctx))
}
})();
$(document).ready(function () {
...declare & setup the jqGrid with 'big row page', e.g. ...
rowNum: 9999,
rowList: [50, 100, 200, 9999],
.........then add below navigation button after setup the grid...
$("#list").jqGrid('navButtonAdd', pgrid1, {caption:"Download",title:"Download report contents", buttonicon :'ui-icon-circle-arrow-s',
onClickButton:function(){
tableToExcel('list', 'export data')
}
});
}
</script>
Alternatively, another way to exporting can refer to related question:
How to enable jQgrid to Export data into PDF/Excel

Issues with knockout observable array validation

I have an issue with a validation rule that I put on observablearray elements. I'm using a custom message template to display the errors, the issue is that it doesn't get displayed on when the errors are there, however, I can see the '*' against the relevant field. Following is my model:
function ViewModel(item) {
var parse = JSON.parse(item.d);
var self = this;
this.ID = ko.observable(parse.ID).extend({ required: { params: true, message: "ID is required" }});
this.Name = ko.observable(parse.Name);
this.WeeklyData = ko.observableArray([]);
var records = $.map(parse.WeeklyData, function (data) { return new Data(data) });
this.WeeklyData(records);
}
var Data = function (data) {
this.Val = ko.observable(data).extend({
min: { params: 0, message: "Invalid Minimum Value" },
max: { params: 168, message: "Invalid Maximum Value" }
});
Here is the validation configuration I'm using:
// enable validation
ko.validation.configure({
registerExtenders: true,
messagesOnModified: false,
insertMessages: true,
parseInputAttributes: false,
messageTemplate: "customMessageTemplate",
grouping: { deep: true }
});
ko.validation.init();
Any my custom message template goes like this:
<script id="customMessageTemplate" type="text/html">
<em class="errorMsg" data-bind='visible: !field.isValid()'>*</em>
</script>
<ul data-bind="foreach: Errors">
<li class="errorMsg" data-bind="text: $data"></li>
</ul>
With this implementation, I don't see the validation messages in the custom template. But if I remove the configuration deep: true, it doesn't validate the observable array elements, but the other observable(ID) and then the message is displayed properly.
I'm very confused with this and a bit stuck, so appreciate if someone can help/
Thanks in advance.
What i understand from your question is that you are trying to validate your observableArray entries, so that if any entry in your WeeklyData observableArray fails the following condition:
arrayEntry % 15 === 0
you want to show error message. If this is the case, than the following custom validator can do the job for you :
var fminIncrements = function (valueArray) {
var check = true;
ko.utils.arrayFirst(valueArray, function(value){
if(parseInt(value, 10) % 15 !== 0)
{
check = false;
return true;
}
});
return check;
};
And you have to apply this validator on the observableArray (no need to set validation on individual entries of the array). This validator takes array as input and validate its each entry, if any one entry fails the validation it will retrun false and than you will see the error message.
Your viewmodel looks like :
function viewModel() {
var self = this;
self.WeeklyData = ko.observableArray([
15,
40
]).extend({
validation: {
validator: fminIncrements,
message: "use 15 min increments"
}
});
self.errors = ko.validation.group(self);
}
And here is the working fiddle.
the individual item is not showing the message - it's only in the summary - how do you specify the message on the individual textbox ?

ASP MVC3 and Telerik DatePicker control blocking year/month pick after Ajax action

So I'm in big trouble here.
<%: Html.Telerik().DatePicker().Name("dataWprowadzeniaOd").ShowButton(true)%> -
<%:Html.Telerik().DatePicker().Name("dataWprowadzeniaDo").ShowButton(true) %>
I have these two nice DatePickers, a list and some filtering options, all on Ajax. Now when Ajax action occurs (like filtering, refreshing table, changing pages) these two cute little things block in a way user is not able to change month and year there.
Here's beginning of table code:
Html.Telerik().Grid(Model)
.Name("Main")
.DataKeys(keys => keys.Add(p => p.DepozytID))
.Localizable("pl-PL")
.Pageable(paging => paging.Enabled(true).PageSize(20))
I've tried putting:
$('#dataWprowadzeniaOd').tDatePicker({ format: 'yyyy-MM-dd', minValue: new Date(1899, 11, 31),
maxValue: new Date(2100, 0, 1) });
$('#dataWprowadzeniaDo').tDatePicker({ format: 'yyyy-MM-dd', minValue: new Date(1899, 11, 31),
maxValue: new Date(2100, 0, 1) });
at the end of every callback/ajax function, but it removes month/year bar from calendar so I can't check if it works o.O
Tried this:
$('#dataWprowadzeniaOd').attr('disabled', 'disabled');
$('#dataWprowadzeniaOd').attr('disabled', '');
too, but no effect.
function filtruj() {
var newurl = '<%: Url.Content("~/RejestrDepozytow/ListaDepozytow") %>';
var filtr = {};
filtr.typStatusu = $("#typStatusu").val();
filtr.rodzajDepozytuID = $("#rodzajDepozytuID").val();
filtr.dataWprowadzeniaOd = $("#dataWprowadzeniaOd").val();
filtr.dataWprowadzeniaDo = $("#dataWprowadzeniaDo").val();
filtr.podmiotSkladajacyID = $("#podmiotSkladajacyID").val();
filtr.podmiot = $("#podmiot").val();
filtr.sygnaturaSprawy = $("#sygnaturaSprawy").val();
filtr.barcode = $("#barcode").val();
filtr.numerLp = $("#numerLp").val();
filtr.numerRok = $("#numerRok").val();
$.ajax({
type: "POST",
async: false,
url: newurl,
data: filtr,
success: function (dane) {
$("#gridDepozytow").html(dane);
}
});
}
Here's method used just before datepicker getting blocked.

Resources