How to update data row in datatables - javascript

I want to get value from the database and showing to the datatables with a condition, and if I change input form value (This input value is a condition for query so if i change the value the data in the datatable will change) but when i use on change it's work but when i try twice to change value they say i reinitialise, any suggestion to make it right?
I already try to that code, it's work but if i change the value again it's error says 'DataTables warning: table id=dataTr - Cannot reinitialise DataTable. For more information about this error, please see http://datatables.net/tn/3
var asset = $('#formasset').find('input[name="ckdasset"]').val();
$(document).ready(function() {
$('#ckdasset').on('change',function(){
var dataTable = $('#dataTr').DataTable( {
"processing": true,
"ajax":{
url :"<?php echo base_url();?>index.php/Logged/get_detail_data/"+kode_asset_new+",
type: "post", // method , by default get
error: function(){ // error handling
$(".employee-grid-error").html("");
$("#dataTr").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display","none");
}
}
} );
});
} );

Try this, You're initializing the datatable again instead of reset/redraw.
var asset = $('#formasset').find('input[name="ckdasset"]').val();
$(document).ready(function () {
var dataTable = $('#dataTr').DataTable({
"processing": true,
"ajax": {
url: "<?php echo base_url();?>index.php/Logged/get_detail_data/" + kode_asset_new + ",
type: "post", // method , by default get
error: function () { // error handling
$(".employee-grid-error").html("");
$("#dataTr").append('<tbody class="employee-grid-error"><tr><th colspan="3">No data found in the server</th></tr></tbody>');
$("#employee-grid_processing").css("display", "none");
}
}
});
$('#ckdasset').on('change', function () {
var Dt = $('#dataTr').DataTable();
Dt.fnDraw();
});
});

Related

fooplugins/Footable - "Cannot read property 'name' of null" when trying to load the table from JSON

I want to use the plugin "FooTable" with ajax calls.
Everything works fine when I hardcode the JSON, or even load it from a JSON file with $.get('....json'). When I try to load the table content from my server, I always get the error message "Cannot read property 'name' of null" shown with details here:
Error message
The image above also shows the JSON logged into the Console. I've tried loading it in a lot of different ways (in back- and front-end), but I just cant get it to work. I left some of my tries commented out in the attached Code.
JavaScript:
$(document).ready(function () {
jQuery(function ($) {
var ft = FooTable.init('.table', {
"columns": $.get('/js/mycols.json'),
//"rows": $.get('/js/myrows.json')
"rows": $.get('/api/GetEvents', function (e) {
console.log(JSON.parse(e.value));
//ft.rows.load(JSON.parse(e.value));
}, "json")
});
//$.ajax({
// url: "/api/GetEvents",
// dataType: "json",
// type: "GET"
//}).done(function (e) {
// console.log(e);
// ft.rows.load(e.value);
//})
});
});
ASP.NET Backend:
List<JObject> objList = new List<JObject>();
foreach (var e in events)
{
JObject jObj = JObject.FromObject(new
{
name = e.Name,
veranstaltungstyp = e.Type,
startzeit = e.StartTime.ToString("H:mm - dd MMMM yyyy"),
ende = e.EndTime.ToString("H:mm - dd MMMM yyyy"),
erstelltvon = e.CreatedBy.FirstName + " " + e.CreatedBy.LastName,
render = "placeholder"
});
objList.Add(jObj);
}
var result = new JsonResult(JsonConvert.SerializeObject(objList));
result.ContentType = "json";
result.StatusCode = 200;
result.SerializerSettings = new JsonSerializerOptions();
return Json(result);
I had a similar issue. It appears that FooTable is trying to load the rows before the table has been fully rendered and so it is not able to properly access the DOM.
Try wrapping your fetch in a on('ready.ft.table').
$(document).ready(function () {
jQuery(function ($) {
var ft = FooTable.init('.table', {
"columns": $.get('/js/mycols.json'),
});
$('.table').on('ready.ft.table', function(e) {
$.ajax({
url: "/api/GetEvents",
dataType: "json",
type: "GET"
}).done(function (e) {
console.log(e);
ft.rows.load(e.value);
})
});
});
});

Cannot read property 'row' of undefined

//anything inside 'pagebeforecreate' will execute just before this page is rendered to the user's screen
$(document).on("pagebeforecreate", function () {
printheader(); //print the header first before the user sees his page
});
$(document).ready(function () {
searchfriend();
function searchfriend() {
var url = serverURL() + "/getcategories.php";
$.ajax({
url: url,
type: 'GET',
dataType: 'json',
contentType: "application/json; charset=utf-8",
success: function (arr) {
_getCategoryResult(arr);
},
error: function () {
validationMsg();
}
});
}
function _getCategoryResult(arr) {
var t; //declare variable t
//loop for the number of results found by getcategories.php
for (var i = 0; i < arr.length; i++) {
//add a new row
t.row.add([ //error
"<a href='#' class='ui-btn' id='btn" + arr[i].categoryID + "'>Category</a>" //add a new [Category] button
]).draw(false);
//We drew a [View] button. now bind it to some actions
$("#btn" + arr[i].categoryID).bind("click", { id: arr[i].categoryID }, function (event) {
var data = event.data;
showcategory(data.id); //when the user clicks on the [View] button, execute showcategory()
});
}
$("#categoryresult").show(); //show the results in the table searchresult
}
function showcategory(categoryID) {
//alert(categoryID);
window.location = "showuser.html?userid=" + userid;
}
});
There is an error on line 33 which stated:
"Uncaught TypeError: Cannot read property 'row' of undefined"
However, it seems that I have no idea where the error is coming from.
Is there anyway I can solve this problem?
You look like you are using a third-party jQuery plugin, DataTables.
Follow the usage of DataTables.
var t; //declare variable t
should be
var t = $("#categoryresult").DataTable();
The variable t is not an object with a property called row.
Try with var t = { row: [] }
Edit: I apologize. I got confused add with push method.
So, you need an object with a method called add and assign that object to t

Issue with setting value to select dropdown in MVC

I am using MVC.
I am having two drop down and one change of 'primaryspec' the 'primarysubspec' should get loaded.
Everything is working fine for passing values to controller and it got saved to DB.
When I am trying to retrieve the saved details,'primarysubspec' saved values are not getting displayed.
But displaying save data for 'primarySpec'.
Here is my .cshtml code:
#Html.DropDownListFor(m => m.PSpec, Model.PSpec, new { id = "ddUserSpec", style = "width:245px;height:25px;", data_bind = "event: {change: primaryChanged}" }, Model.IsReadOnly)
#Html.DropDownListFor(m => m.PSubspec, Model.PSubspec, new { id = "ddUserSubSpec", style = "width:245px;height:25px;", data_bind = "options: primarySubSpec,optionsText: 'Name',optionsValue: 'Id'" }, Model.IsReadOnly)
Here is my JS Code to retrieve the values for :
this.primarySubSpec = ko.observableArray([]);
this.primarySpecChanged = function () {
var val = $("#ddetailsPrimarySpec").val();
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/PlatformUser/GetSpecandSubSpec?primarySpe=' + val+//model.primarySpecID() +'&secondarySpec=';
loadPrimarySubSpec();
};
function loadPrimarySubSpec() {
$.ajax({
type: 'GET',
url: primarySubSpecUrl,
contentType: 'application/json; charset=utf-8',
dataType: 'json',
processdata: false,
cache: false,
success: function (data) {
primarySubSpec = [];
model.primarySubspec('0');
try {
if (data.length == 0) {
primarySubSpeacId.empty();
}
model.primarySubSpec(data);
},
error: function (request, status, error) {
primarySubSpeacId.prop("disabled", true);
}
});
}
Everything is working fine,but facing issue only while displaying the saved values from the DB.
Showing fine for 'primarySpec'
The values showing empty for 'PrimarySubSpec' instead of saved values in dropdown.
Please let me know what is the issue how can i show the saved value as selected value in 'primarySubSpec'dropdown.
The Problem:
when you load the page to view saved values, the change event is never called.
Why:
When your page is loaded with saved values, the select box has the saved value selected before knockout knows anything about it. Hens the change event isn't called.
Simplest solution:
change the primarySpecilaityChanged as follows
this.primarySpecilaityChanged = function () {
var val = $("#ddUserDetailsPrimarySpeciality").val();
if(val){
primarySubStartIndex = 0;
primarySubSpecialityUrl = '/' + NMCApp.getVirtualDirectoryName() + '/PlatformUser/GetSpecialitiesandSubSpecilaities?primarySpeciality=' + val+//model.primarySpecialityUID() +'&secondarySpeciality=';
loadPrimarySubSpecilaities();
}
};
then call primarySpecilaityChanged function after you call ko.applyBindings.
var viewModel = new YourViewModel();
ko.applyBindings(viewModel);
viewModel.primarySpecilaityChanged();

Add html table to content loaded by jQuery

I'm working on an Ajax/PHP-powered sequence of forms. The first form is submitted and, upon successful submission, the page returns a new form using Ajax, PHP and jQuery. This first part works fine. The part where the new form is yielded upon form success, does not.
$('#some_form').submit(function (event) {
event.preventDefault();
var form = $(this);
console.log(form);
var formdata = {
'title': form.find('input[name=title]').val(),
'user': form.find('select').val()
};
$.ajax({
type: 'POST',
url: "some_url",
data: formdata,
dataType: 'json',
encode: 'true',
success: function (res) {
if(res.field_errors) {
// If there are errors: do stuff
}
else {
//No errors, so successful submission, time to load new form
var form_div = $("<div>",{"id":"some_div","class":"col-lg-12"});
var table = fill_table(res.data);
var form_content = form_div.load('page_template.html');
//The line below does not work.
form_content.find("#table-div").append(table);
form_div.append(form_content);
form_div.appendTo("#page-wrapper");
}
},
error: function (jqXHR, errorThrown) {
console.log('jqXHR:');
console.log(jqXHR);
console.log('errorThrown:');
console.log(errorThrown);
}
});
)};
And the fill_table functions (a bit clumsy but it's still work-in-progress):
function create_table_row(row_data){
var tr = $('<tr>');
var first_td = "<td class='checkbox'><label><input type='checkbox' value="+mi.id+" name='mi[]'/></label></td>";
var second_td = "<td>"+row_data.title+"</td>";
var third_td = "<td>"+row_data.description+"</td>";
var fourth_td = "<td class='file'><i style='vertical-align:middle; line-height:30px;' class='fa fa-1x fa-file-pdf-o'></i></td>";
tr.append(first_td);
tr.append(second_td);
tr.append(third_td);
tr.append(fourth_td);
return $(tr);
}
function fill_table(data_pool) {
if(data_pool.length==0){
return "There is no data available yet.";
}
else {
var table = $("<table>",{"class":"mi-list","id":"mi-table"}).append("<tr><th class='checkbox'><label><input type='checkbox' id='bulk' name='data[]'/> </label></th> <th>Title</th><th>Description</th><th>Date</th><th>File</th></tr>");
$.each(data_pool, function(index, val){
table.append(create_table_row(val));
});
return table;
}
}
The table functions work fine, and so does the .load() which correctly loads the static HTML part. However, I can't seem to correctly add the yielded table to the div that was just loaded by.load(). Logging the table data to console shows me that the table is there, with both the static and dynamic table data inside of it.
form_content.find("#table-div").append(table); Does not work. form_content.find("#table-div").html(table); doesn't either.
How do I correctly append this to the new div?
Since the load is async, you need to use a callback which is going to be run once the load process is complete. See jQuery.load() documentation.
Then, your could should look like this:
form_div.load('page_template.html', function() {
form_content.find("#table-div").append(table);
form_div.append(form_content);
form_div.appendTo("#page-wrapper");
});

How to create/find right ID in multiple Form elements of same type $ajax function with jQuery Mobile?

I have a collapsible part of my jQuery Mobile page that are generated from PHP output from a MS Sql databas and content render as I like it to so that part is ok.
in each section I create a form with 3 buttons and they are supposed to have unique Id:s.
All forms are also created to have a unique id created in runtime.
actions.php (renders out my elements into mobilepage i a DIV)
$counter=0; reset counter for ID:s
while (odbc_fetch_row($rs)){
// data output from Db to make like 10 collapsible with different data
$html = "";
$html = "<div data-role='collapsible-set' data-mini='true'>";
$html.="<div data-role='collapsible' data-mini='true'>";
$html.="<h3><span style=float:left;><img src='../_pic/$image' alt='$imageText' /> ".substr($Time,0,16)." $Area</span><span style='float:right;' class='ui-btn-up-c ui-btn-corner-all' cnt> $data </span></h3>";
$html.="<p>ID: $ID $Id $Status<br />$Status $Description)</p>";
$html.="<form method='post' action=''>";
$html.="<button value='action1' id='action1$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action2' id='action2$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<button value='action3' id='action3$counter' data-mini='true' type='Submit'>Take Action1</button>";
$html.="<input type='hidden' id='id$counter' name='id' value='$dataName' />";
$html.="</form>";
$html.="</div>";
$html.="</div>";
echo utf8_encode($html);
$counter++; //upcount to make Id:s unique
} //end While
Then I have this function that listens for a button that submit:
$(':submit').live('click', function() {
var button = $(this).val();
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+$('#id').val(),
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
I cant seem to get another id than the first one since i need to make all ID:s unique in my forms and all I do now is to check: &id='+$('#id').val(). what I would like to have done is to link the button pressed-id number to my hidden field id-number so i get the right data out from it. As of now I only get the first form:s id evaluated...
If someone could point me in the right direction how to make that happen i´d be greatful.
functions.php (a switch statement is pre-testing for submit:ed action
function actions1(){
try {
if(isset($_GET['id'])){
do stuff with 'id'
}else{
do other stuff with 'id'
}
} catch(Exception $e) {
show error
}
}
If some part is unclear or if you feel I missed posting somepart - let me know. /thanks
Within event handlers this referes to the element
$(':submit').live('click', function(){
var id= this.id;
var button = $(this).val();
/* traverse within form to set hidden input, no need to worry about using ID's for them*/
$(this).closest('form').find('input[name=id]').val(id);
/* then in ajax */
data: 'button=' +button+'&id='+id,
})
Not full code....I left some of your code out for simplicity
You can use jQuery .attr() function to get an id or any other attribute value of an element.
$(':submit').live('click', function() {
var button = $(this).val();
var id = $(this).attr("id");
if (button == 'action1') {
$.ajax({
url: '../_php/Functions.php',
data: 'button=' + $(this).val()+'&id='+ id,
async: true,
beforeSend: function() {
$.mobile.showPageLoadingMsg(true);
},
complete: function() {
$.mobile.hidePageLoadingMsg();
},
error: function (request,error) {
alert('error');
}
});
}
return false;
});
The solution was to go by attributes name of my hidden input.
var id = $(this).closest("form").find(':hidden').val();

Categories

Resources