Refresh jquery Data table - javascript

I am trying to refresh the create data table without reloading the whole page. So, everytime I try to search for a result, it will refresh the data table and give a new result and not add a new row instead. If i remove the $('#investmentTable').empty();. It gives me the all the result but it does not refresh my result
$('#investmentTable').empty(); only clears my data table completely and doesn't display any result
<div class="control-group">
<label class="control-label">Enter From Date</label>
<div style="width:40%" class="controls">
<input id="fromDate" type="text" name="fromDate" type="text" data-date-format="dd-mm-yyyy" class="datepicker span11">
</div>
</div>
<div class="control-group">
<label class="control-label">Enter To Date</label>
<div style="width:40%" class="controls">
<input id="toDate" type="text" name="toDate" type="text" data-date-format="dd-mm-yyyy" class="datepicker span11">
</div>
</div>
<div class="form-actions">
<input id="next" class="btn btn-primary" type="button"
value="Search" />
<div id="status"></div>
</div>
$("#next").on("click",function(event) {
$('#investmentTable').empty();
$.ajax({
type: 'POST',
url: app.api+'admin/report/date',
data: {
fromDate: $('#fromDate').val(),
toDate: $('#toDate').val()
},
success: function(data)
{
if (data.result == true) {
for(var i = 0; i < data.data.length; i++){
var item = data.data[i][0];
var x = $('#investmentTable').DataTable({
responsive: true,
bJQueryUI: true,
scrollX: true,
height: "100px",
display: "block",
sPaginationType: "full_numbers",
sDom: '<""l>t<"F"fp>'
});
x.row.add([item.date, item.name, item.email, item.contact.phone, item.account.investedAmount]);
x.draw();
}
}
},
return false;
});

Could you please move the code which creates table out of for loop. Please try below code.
$("#next").on("click",function(event) {
$('#investmentTable').empty();
$.ajax({
type: 'POST',
url: app.api+'admin/report/date',
data: {
fromDate: $('#fromDate').val(),
toDate: $('#toDate').val()
},
success: function(data)
{
if (data.result == true) {
var x = $('#investmentTable').DataTable({
responsive: true,
bJQueryUI: true,
scrollX: true,
height: "100px",
display: "block",
sPaginationType: "full_numbers",
sDom: '<""l>t<"F"fp>'
});
for(var i = 0; i < data.data.length; i++){
var item = data.data[i][0];
x.row.add([item.date, item.name, item.email, item.contact.phone, item.account.investedAmount]);
x.draw();
}
}
},
return false;
});

Related

Javascript DataTables warning, Requested unknown parameter 'Id' for row 0

I'm getting the following error when I'm trying to fill a Datatable using ajax :
Also, I can get all datas in controller and i am returning Json from there. There is no any problem in controller. Just I can't fill datatable.
My javascript code in below :
This is my function
function createDatatable(setting) {
var actionsColumn = {
sortable: false,
searchable: false,
class: 'text-center',
render: function (data, type, row, meta) {
return '<a class="btn btn-outline-primary btn-sm" href="/' + setting.controller + '/Edit/' + row[setting.primaryKey] + '" title="Düzenle"><i class="icon-pencil"></i></a> <a class="btn btn-outline-danger btn-sm" href="/' + setting.controller + '/Delete/' + row[setting.primaryKey] + '" title="Sil"><i class="icon-trash"></i></a>';
}
};
if (setting.hasCostumActionsColumn === undefined || setting.hasCostumActionsColumn == false) {
setting.columns.push(actionsColumn);
}
if (setting.defaultSortingColumn === undefined) {
setting.defaultSortingColumn = 0;
}
if (setting.defaultSorting === undefined) {
setting.defaultSorting = "desc";
}
if (setting.queryString === undefined) {
setting.queryString = "";
}
var url = '/' + setting.controller + '/' + setting.action;
if (setting.queryString != undefined && setting.queryString != "") {
url += '?' + setting.queryString;
}
var table = $('#' + setting.tableId).DataTable({
info: false,
dom: '<"toolbar">frtip',
deferRender: true,
fnInitComplete: function () {
$("#table1_paginate").remove();
handlePaging();
$('#next-btn').on('click', function () {
table.page('next').draw('page');
updateCurrentPageInput();
});
$('#previous-btn').on('click', function () {
table.page('previous').draw('page');
updateCurrentPageInput();
});
$("#goto-page").on('click', function () {
var page = parseInt($("#pagination-current-page").val());
if (page < 1) {
page = 1;
} else if (page > table.page.info().pages) {
page = table.page.info().pages;
}
var index = page - 1;
table.page(index).draw('page');
updateCurrentPageInput();
});
$("#pagination-row-count").change(function () {
table.page.len($("#pagination-row-count").val()).draw();
updateCurrentPageInput();
});
},
"drawCallback": function (settings) {
updateCurrentPageInput();
},
responsive: true,
processing: true,
serverSide: true,
orderCellsTop: true,
autoWidth: true,
deferRender: true,
lengthMenu: [[10, 20, 50, 100, -1], [10, 20, 50, 100, "Tümü"]],
ajax: {
type: "POST",
url: url,
contentType: "application/json; charset=utf-8",
async: true,
headers: {
"RequestVerificationToken": document.querySelector('[name="__RequestVerificationToken"]').value
},
data: function (data) {
let additionalValues = [];
data.AdditionalValues = additionalValues;
return JSON.stringify(data);
}
},
columns: setting.columns,
columnDefs: setting.columnDefs,
order: [setting.defaultSortingColumn, setting.defaultSorting]
});
$("#filter-table").on('click', function () {
$(".table-filter").each(function (k, item) {
var index = $(item).data('index');
var val = $(item).val();
if (val != "") {
table.column(index + ':visible').search(val);
} else {
table.column(index + ':visible').search('DisableSearch');
}
});
table.draw();
});
$("#clear-filter-table").on('click', function () {
document.getElementById("filter-form").reset();
$(".table-filter").each(function (k, item) {
var index = $(item).data('index');
table.column(index + ':visible').search('');
});
table.draw();
});
$(".table-title").prependTo($("#table1_wrapper"));
function updateCurrentPageInput() {
console.log('table pager');
var currentPage = table.page() + 1;
$("#pagination-current-page").val(currentPage);
if (table.page() === 0) {
$('#previous-btn').attr("disabled", true);
} else {
$('#previous-btn').prop("disabled", false);
}
if (table.page.info().pages === currentPage) {
$('#next-btn').attr("disabled", true);
} else {
$('#next-btn').prop("disabled", false);
}
$("#pagination-current-page").prop('max', table.page.info().pages);
$("#table-info-div").html(`Toplam ${table.page.info().pages} sayfanın ${table.page() + 1}. sayfasındasınız. Toplam ${table.page.info().recordsTotal} kayıt bulunmaktadır.`);
}
function handlePaging() {
$('div.toolbar').html(`
<span id="table-info-div">Toplam2 ${table.page.info().pages} sayfanın ${table.page() + 1}. sayfasındasınız. Toplam ${table.page.info().recordsTotal} kayıt bulunmaktadır.</span>
<div class="input-group">
<button id="previous-btn" class="btn btn-success btn-sm paginate_button previous" style="margin-right:5px">< Önceki</button>
<input type="number" id="pagination-current-page" class="form-control" value="1" min="1" step="1" style="padding:5px; width:50px;margin-right:5px;" />
<button id="goto-page" class="btn btn-info btn-sm" style="margin-right:5px">Git</button>
<button id="next-btn" class="btn btn-success btn-sm paginate_button next" style="margin-right:5px">Sonraki ></button>
<div class="kayitSayisi">
<select id="pagination-row-count" class="form-control">
<option value="10">10</option>
<option value="25">25</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</div>
</div>`);
$("#pagination-current-page").prop('max', table.page.info().pages);
if (table.page() === 0) {
$('#previous-btn').attr("disabled", true);
} else {
$('#previous-btn').prop("disabled", false);
}
if (table.page.info().pages === 1) {
$('#next-btn').attr("disabled", true);
} else {
$('#next-btn').prop("disabled", false);
}
}
return table;
}
Here, I am calling the function :
createDatatable({
tableId: 'table1',
controller: 'User',
action: 'LoadTable',
columns: [
{
data: "Id",
name: "eq",
visible: true,
searchable: true
},
{
data: "FirstName",
name: "co",
searchable: true
},
{
data: "LastName",
name: "co",
searchable: true
},
{
data: "UserName",
name: "co",
searchable: true
},
{
data: "Email",
name: "co",
searchable: true
},
{
sortable: false,
class: 'text-center',
searchable: false,
render: function (data, type, row, meta) {
return '<a class="btn btn-outline-success btn-sm" href="/User/ChangePassword/' + row["Id"] + '" title="Şifre Değiştir"><i class="icon-lock"></i></a> <a class="btn btn-outline-primary btn-sm" href="/User/Edit/' + row["Id"] + '" title="Düzenle"><i class="icon-pencil"></i></a> <a class="btn btn-outline-danger btn-sm" href="/User/Delete/' + row["Id"] + '" title="Sil"><i class="icon-trash"></i></a>';
}
}
],
primaryKey: "Id",
hasCostumActionsColumn: true
});
Update :
I added html code :
<div class="content">
<div class="card-group-control card-group-control-right">
<div class="card">
<div class="card-header">
<h6 class="card-title">
<a data-toggle="collapse" class="collapsed text-default" href="#filter-collapse" style="display:block">Filtrele</a>
</h6>
</div>
<div id="filter-collapse" class="collapse">
<div class="card-body">
<form id="filter-form">
<div class="form-group row">
<div class="col-md-3">
<label class="col-form-label col-lg-12">Id</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="0" />
</div>
</div>
<div class="col-md-3">
<label class="col-form-label col-lg-12">Adı</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="1" />
</div>
</div>
<div class="col-md-3">
<label class="col-form-label col-lg-12">Soyadı</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="2" />
</div>
</div>
<div class="col-md-3">
<label class="col-form-label col-lg-12">Kullanıcı Adı</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="3" />
</div>
</div>
<div class="col-md-3">
<label class="col-form-label col-lg-12">E-Posta</label>
<div class="col-lg-12">
<input type="text" class="form-control table-filter" data-index="4" />
</div>
</div>
</div>
<div class="form-group row">
<div class="col-md-12">
<div class="col-lg-12">
Listele
Temizle
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div class="card">
<div class="card-body">
<div class="table-title">Kullanıcılar</div>
<table id="table1" class="table table-bordered table-hover datatable-ajax datatable-responsive">
<thead>
<tr>
<th >Id</th>
<th data-priority="1">Adı</th>
<th data-priority="2">Soyadı</th>
<th>Kullanıcı Adı</th>
<th>E-posta</th>
<th style="width: 210px;"></th>
</tr>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>

jQuery validation not working when input fields are empty

I think this is not complex one but I can't do it by myself. I am very thankful for your help.
I am going to submit a form with validation. It seems like my validations are not working properly. Because when the input fields are empty it's not showing an error message. And also when clicking the submit button it's not showing error message. This incident only happens when input fields are empty.
Here is my HTML:
<form name="department" id="department">
<div class="form-group">
<label for="example-text-input">Department Name</label>
<span id="errfnCustomer"></span>
<input class="form-control" type="text" placeholder="Enter Department Name" id="textDepartmentName" name="textDepartmentName1">
</div>
<div class="form-group">
<label for="example-text-input">Registation Number</label>
<span id="errfnCustomer2"></span>
<input class="form-control" type="text" placeholder="Enter Department Registation Number" id="textRegistationNumber" name="textRegistationNumber">
</div>
<div class="form-group">
<label for="example-text-input">Web Site</label>
<input class="form-control" type="text" placeholder="Web Site" id="textWebsite" name="textWebsite1">
</div>
<div class="form-actions">
<div class="form-group">
<input type="button" value="Register" class="btn pull-right" id="btnsubmit" style="background-color:#1e90ff; width: 100px; color: white; font-weight: bold" />
</div>
</div>
</div>
And jQuery:
$('#department').validate({
rules: {
textDepartmentName1: {
required: true,
minlength: 3,
},
textRegistationNumber: {
required: true,
minlength: 3
},
textWebsite1: {
required: true,
minlength: 3
}
},
submitHandler: $("#btnsubmit").click(function (form) {
var submitData = {
DepartmentId: saveStat,
DepartmentName: $('#textDepartmentName').val().trim(),
RegistationNumber: $('#textRegistationNumber').val(),
Website: $('#textWebsite').val(),
Email: $('#textEmail').val(),
Telephone01: $('#textTelephone01').val(),
Telephone02: $('#textTelephone02').val(),
Fax: $('#textFax').val(),
BranchId: $('#cmbGetBranch').val()
}
if (saveStat == 0) {
$.ajax({
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
async: false,
type: 'POST',
data: "{submitData:" + JSON.stringify(submitData) + "}",
url: "/Department/AddDepartment",
success: function (saveDepartment) {
if (saveDepartment.saveDepartment.DepartmentId != 0) {
refresh();
alert(saveDepartment.saveDepartment.DepartmentName + " Saved succesfully...!!!");
} else {
alert('warning' + " Department saving unsucsessful...!!!");
}
},
error: function (xhr, errorThrown) {
alert('Error...!!! Internal - 01');
}
});
} else {
$.ajax({
dataType: 'json',
contentType: 'application/json; charset=utf-8',
cache: false,
async: false,
type: 'POST',
data: "{submitData:" + JSON.stringify(submitData) + "}",
url: "/Department/UpdateDepartment",
success: function (updateDepartment) {
if (updateDepartment.updateDepartment.DepartmentId != "") {
alert(updateDepartment.updateDepartment.DepartmentName + " updated succesfully...!!!");
refresh();
} else {
alert("Department update error...!!!");
}
},
error: function (xhr, errorThrown) {
alert('Error...!!!');
}
});
}
grid();
})
});
First of all make register buttom type submit:
<input type="submit" value="Register" class="btn pull-right" id="btnsubmit" style="background-color:#1e90ff; width: 100px; color: white; font-weight: bold" />
And make submit handler something like this:
submitHandler:function (form) {
}
See more here (Jquery validation).

Contents of Div Dialog Content shows even when Jquery Dialog isn't open

I am using Grails 3.1.9 as the platform, my problem is that when the button Add Item has not been clicked, I can see the contents of the dialog box at the bottom of the page, and when the button is clicked, the contents disappear from the bottom. How do I prevent this from happening? Any help you can provide will be greatly appreciated.
Before Clicking Add Item Button
After Clicking Add Item Button
show.gsp Code is:
<div id="dialogEntry" title="Item Entry">
<fieldset class="form">
<form id="entryForm" action="" method="post" ><input type="hidden" name="_method" value="PUT" id="_method" />
<input type="hidden" name="invoice.id" value="${invoice.id}" />
<div class="fieldcontain required">
<label for="product">
<g:message code="orderItem.product.label" default="Product" />
<span class="required-indicator">*</span>
</label>
<input type="text" name="product" value="" required="" id="product" />
<input type="hidden" id="prodid" value="" />
<div class="fieldcontain">
<label for="quantityInStock">
Quantity in Stock
</label>
<input type="text" id="quantityInStock" value="" readonly="true" />
</div>
</div>
<div class='fieldcontain required'>
<label for='quantity'>Quantity
<span class='required-indicator'>*</span>
</label><input type="number" name="quantity" value="1" required="" min="1" id="quantity" />
</div>
<div class='fieldcontain required'>
<label for='price'>Price
<span class='required-indicator'>*</span>
</label><input type="number" name="price" value="" required="" step="0.01" min="1.00" id="price" />
</div>
<div class="fieldcontain">
<label for="totalAmount">
Total Amount
</label>
<input type="null" name="totalAmount" value="" id="totalAmount" />
</div>
</form>
</fieldset>
</div>
<script>
var editId;
document.getElementById("add").onclick = function() {myFunction()};
function myFunction() {
document.getElementById("add").innerHTML =
$( "#dialogEntry" ).dialog({
autoOpen: true,
modal: true,
width: 500,
buttons: [
{
text: "Save",
click: function() {
var quantity = $('#quantity')[0].value;
var quantityInStock = $('#quantityInStock')[0].value;
if (quantity.length == 0) {
alert('Quantity is required');
$('#quantity')[0].focus();
return;
}
if (parseInt(quantity) > parseInt(quantityInStock)) {
alert('Quantity cannot be served as Quantity in Stock is just ' + quantityInStock);
$('#quantity')[0].focus();
return;
}
$( this ).dialog( "close" );
var price = $('#price')[0].value;
var prodid = $("#prodid")[0].value;
// submit to server
//var form = $('#entryForm')[0];
if (editId != 0) {
$.ajax({
type: "POST",
url: "${resource(dir:'orderItem/updatex')}/" + editId,
data: {'productid':prodid, 'quantity':quantity, 'price':price},
async: true,
cache: false,
success: function (result) {
//alert('OK ' + result.success.message)
update(editId)
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
} else {
$.ajax({
type: "POST",
url: "${resource(dir:'orderItem/savex')}/" + editId,
data: {'productid':prodid, 'quantity':quantity, 'price':price, 'invoiceid':${invoice.id}},
async: true,
cache: false,
success: function (result) {
var id = result.success.id
//alert('OK ' + id)
update(id)
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + " " + errorThrown);
}
});
}
}
},
{
text: "Cancel",
click: function() {
$( this ).dialog( "close" );
}
}
]
});
}
</script>
<div id="dialogEntry" title="Item Entry">
Change this to:
<div id="dialogEntry" title="Item Entry" style="display:none;">
Change this:
document.getElementById("add").innerHTML =
$( "#dialogEntry" ).dialog({
to
document.getElementById("add").innerHTML =
$( "#dialogEntry" ).show().dialog({
Change this to:
text: "Cancel",
click: function() {
$( this ).dialog( "close" ).hide();
}

how to get a value based on a selection in knockoutjs

I'm using knockout to get some data from an API to fill my textboxes. I want to get the unit price from the API when you select a drug. How can I do this?
<div class="control-group">
<label class="control-label">Drug:</label>
<div class="form-horizontal">
<select id="Drug_ddl" data-bind="options: drugs, optionsText: function (item) { return item.Description; }, value: selectedDrug" class="input-xlarge"></select>
</div>
</div>
<div class="control-group">
<label class="control-label">Unit Price:</label>
<div class="form-horizontal">
<input type="number" data-bind="value: unitPrice" step="0.01" class="input-xlarge" id="UnitPrice_txt" />
</div>
</div>
<div class="control-group">
<label class="control-label">Quantity:</label>
<div class="form-horizontal">
<input type="number" data-bind="value: quantity" step="1" class="input-xlarge" id="Qty_txt" />
</div>
</div>
<div class="control-group">
<label class="control-label">Cost:</label>
<div class="form-horizontal">
<input type="text" data-bind="value: drugcost" readonly="readonly" step="0.01" class="input-xlarge" id="Cost_txt" />
<input type="button" id="AddDrugs_btn" data-bind="click: addDrug" class="btn btn-primary" value="Add" />
</div>
</div>
This is the code for the viewModel:
var claimEntryViewModel = function () {
var drugs = ko.observableArray([]);
var unitPrice = ko.observable('0.00');
var quantity = ko.observable('1');
var drugcost = ko.computed(function () {
return quantity() * unitPrice();
});
var loadDrugs = function () {
url = apiServerUrl + "Items/";
$.ajax({
url: url,
headers: { 'Access-Control-Allow-Origin': '*' },
contentType: 'application/json',
dataType: 'json',
type: 'GET',
crossDomain: true,
success: function (data) {
drugs(data);
},
error: function (data) {
console.log("Is not answered");
console.log(data);
}
});
}
var selectedDrug = ko.observable();
var addDrug = function () {
var match = ko.utils.arrayFirst(claimDrugs(), function (item) {
return selectedDrug().ID === item.Id;
});
if (!match) {
claimDrugs.push({
Id: selectedDrug().ID,
Description: selectedDrug().Description,
unitPrice: selectedDrug().SalesPrice,
quantity: quantity(),
drugcost: drugcost(),
});
} else {
errorMessage("Already exists!");
}
}
return {
drugs: drugs,
addDrug: addDrug,
selectedDrug: selectedDrug,
unitPrice: unitPrice,
quantity: quantity,
drugcost: drugcost,
}
}
someone kindly provide me with a code that can do this, i'm fairly new to knockout and don't really know how to go about this. thanks
super cool is right, subscribing is a good way to handle this.
selectedDrug.subscribe(function (newValue) {
neededInfo(getSelectedDrugInfoFromApi(newValue));
});
This will call the getSelectedDrugInfoFromApi() every time the selectedDrug observable value changes, and update the neededInfo observable.
Keep in mind not to update the selectedDrug value inside the subscribe function though, as it will create a loop.

Posting data using AJAX while using knockout bindings

I am finding it difficult to send data to the controller through Ajax post since the object to be sent to the controller cannot be used within the ajax post because of the structure of my code.I am using knockout for data-binding the click event of the Update button.
This is my code
$(document).ready(function () {
var provider = function () {
var self = this;
self.providerID = ko.observable(providerEditInfo.ProviderID);
self.firstName = ko.observable(providerEditInfo.FirstName);
self.lastName = ko.observable(providerEditInfo.LastName);
self.contactEmail = ko.observable(providerEditInfo.ContactEmail);
self.NPI = ko.observable(providerEditInfo.NPI);
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: { providerForUpdate }, -- Cant send this
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
self.cancelEdits = function () {
if (confirm("Are you sure you want to Cancel?")) {
window.location.href = "/Provider/ShowTheListOfProviders";
}
};
}; //End of Constructor.
var providerForUpdate = new provider();
ko.applyBindings(providerForUpdate);
});
On the clck of Update Button,I am calling the 'updateProviderDetails' method.
HTML
#model Greenway.Demo.DataAccess.Entity.Provider
<body>
<div class="container">
<h1 class="col-sm-offset-2">Edit Provider Details:</h1>
<br />
<form class="form-horizontal" role="form" id="editProviderDetailsForm">
<div class="form-group">
<label class="col-sm-2 control-label labelfont">First Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" autofocus="autofocus" placeholder="Enter the First Name" id="firstName" name="firstName" data-bind="value:firstName , event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label labelfont">Last Name:</label>
<div class="col-sm-6">
<input type="text" class="form-control" placeholder="Enter the Last Name" id="lastName" name="lastName" data-bind="value:lastName ,event: { keypress: allowOnlyAlphabets }">
</div>
</div>
<div class="form-group text-center">
<button type="Submit" data-bind="click: updateProviderDetails" class="btn btn-primary">Update</button>
<button type="button" data-bind="click: cancelEdits" class="btn btn-primary">Cancel</button>
</div>
</form>
</div>
</body>
<script type="text/javascript">
var providerEditInfo = #Html.Raw(Json.Encode(Model));
</script>
<script type="text/javascript" src="../../App_Scripts/Shared/Functions.js"></script>
Could someone guide me on how I can send the data to the controller with this code structure.I can't put updateProviderDetails outside the constructor because otherwise, I can't bind it.
Use ko.toJSON to serialize your view model to json:
self.updateProviderDetails = function () {
$.ajax({
url: "/Provider/UpdateProviderDetails/",
type: "POST",
data: ko.toJSON(self),
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
if (result.url) {
location.href = result.url;
}
}
});
};
This is also in the Knockout Tutorial

Categories

Resources