Clicking a button generated by Javascript with Selenium - javascript

I'd like to use Selenium or other package to automatically click the "Copy" button on one web page.
It seems that the button is generated by Javascript. Is it possible to do so? Thanks in advance!
<script src="media/portal/js/table-maker.js" type="text/javascript"></script>
Here is the piece of code in table-maker.js related to the "Copy" button:
this.generateEntityTable = function(entityName, ajaxDataProperty,
urlSuffix, objectHeadings, objectFields, hiddenFields,
tableSelector, tableId,
emptyMessage) {
if (!emptyMessage) {
emptyMessage = "No data available in table";
}
var oTable = $(tableSelector);
var tableElt = oTable[0];
var tableSource = {
"sourceType" : "json",
"structure" : {
"headings" : objectHeadings,
"fields" : objectFields
}
};
TableUtils.buildTableHtml(tableElt, tableSource.structure.headings);
var tableToolsProps = null;
if ('portalFile' == entityName) { // table does not allow row selection.
tableToolsProps = {
"aButtons" : []
};
} else if ('bspsample' == entityName) {
tableToolsProps = {
"aButtons" : [{
"sExtends": "copy",
"mColumns": "all"
},
{
"sExtends": "csv",
"mColumns": "all"
},
{
"sExtends": "xls",
"mColumns": "all"
}],
"sSwfPath" : "media/table-tools-2.1.5/media/swf/copy_csv_xls.swf"
};
} else {
tableToolsProps = {
"sRowSelect": "single",
"aButtons" : []
};
}
// this is to prevent DataTables from putting warnings or errors in an alert box.
$.fn.dataTableExt.sErrMode = 'throw';
try {
oTable.dataTable({
"bDestroy" : true,
"bRetrieve" : true,
"bJQueryUI" : true,
"bProcessing" : true,
"sPaginationType" : "full_numbers",
"sAjaxSource" : initialUrl + "rest/"+ urlSuffix,
"fnServerData": function ( sSource, aoData, fnCallback ) {
$.ajax( {
"dataType": 'json',
"type": "GET",
"url": sSource,
"success": function(result){fnCallback(result);},
"failure":function(result){alert('failure');}
} );
},
"sAjaxDataProp" : ajaxDataProperty,
"aoColumns" : this.fieldsToColumnProperties(objectFields, objectHeadings,
hiddenFields, entityName, tableSelector, tableId),
"sDom": 'T<"clear">lfrtip',
"oTableTools": tableToolsProps,
"oLanguage": {
"sEmptyTable": "Please wait - Fetching records"
},
fnInitComplete: function(oSettings){
oSettings.oLanguage.sEmptyTable = emptyMessage;
$(oTable).find(".dataTables_empty").html(emptyMessage);
}
});
} catch (err) {
var messageHandler = new MessageHandler();
messageHandler.showError("Internal client error: " + err + " Unable to create table for entity: "
+ entityName);
};
// this is required for row_selected styles to work.
oTable.addClass('display');
oTable.show(); // in case it was hidden
return oTable;
};

Related

Compare data of datatables after reload and highlight row in red if data is unchanged

I have datatable that is being reloaded on every 5 minuts using ajax.reload().
This table has a row named as CIP.
Now on each reload I want to highlight the CIP row where value is unchanged from last value.(Value received on previous ajax call).
function getSkillStats() {
table = $('#example').DataTable( {
"ajax": {
"type" : "GET",
"url" : "../SkillStateManagement",
"dataSrc": function ( json ) {
//Make your callback here.
return json.data;
}
},
colReorder: true,
scrollY: "600px",
scrollX: false,
scrollCollapse: true,
paging: false,
select: true,
'columnDefs': [
{ width: 50, targets: 0 },
{ width: 50, targets: 1 },
{
'targets': 0,
'checkboxes': {
'selectRow': true
}
}
],
fixedColumns: true,
processing:true,
"language": {
"loadingRecords": ' ',
processing: '<i class="fa fa-spinner fa-spin fa-3x fa-fw"></i><span class="sr-only">Loading..n.</span> '
},
columns: [
{ "data" : "calls_Failed" },
{ "data" : "queuer_Threads" },
{ "data" : "calls_In_Progress" },
{ "data" : "skill_Id" },
{ "data" : "calls_Connected" },
{ "data" : "sys_Busy" },
{ "data" : "max_Cip" },
{ "data" : "queuer_name" }
]
} );
}
$(document).ready(function () {
getSkillStats();
setInterval(function () {
table.ajax.reload();
}, 300000);
} );
you can use row callback https://datatables.net/reference/option/rowCallback
The idea, is that you store the previous call and then use the row callback to check if data was unchanged (based on skillId you check the previous Cip value), then if it is you add some special class like "unchanged" ...
$('#example').dataTable( {
....
"rowCallback": function( row, data ) {
if (unchangedCid(data[4], data[7]) ) {
$('td:eq(7)', row).addClass("unchanged"); // unchanged should be defined in css
}
}
} );
and with function unchangedCid like :
var unchangedCid = function(id, cid) {
// search logic goes in search function ...
if(search(id) = cid) {
return true;
}
return false;
}

How to show jQuery Datatable error in a bootstrap alert-warning div rather than the alert box

I am working on an ASP.NET Core 2.1 website and I am using Datatables.net to display my record lists retrieved from a backend API.
This issue I am trying to resolve is that, whenever an error occurs while retrieving the data from the backend API, I want the error message to appear in a Bootstrap alert-error DIV on the same page as the datatable.
I have looked at https://datatables.net/forums/discussion/30033/override-default-ajax-error-behavior and Enable datatable warning alert but I am not strong in javascript so I am having some difficulty determining how to implement this feature.
Currently, I have the datatable set up in my cshtml page as follows;
<script>
jQuery(document).ready(function ($) {
var table = $("#sitelist").DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": false,
"ajax": {
"url": "/Sites/LoadData",
"type": "POST",
"datatype": "json"
},
"columnDefs": [
{ "orderable": false, "targets": 6 },
{ "className": "text-center", "targets": [4, 5] },
{
"targets": [4, 5],
"createdCell": function(td, cellData, rowData, row, col) {
if (cellData) {
$(td).html('<i class="far fa-check-circle text-primary""></i>');
} else {
$(td).html('<i class="far fa-times-circle text-danger""></i>');
}
}
}
],
"columns": [
{ "data": "Id", "name": "Id", "autoWidth": true, "defaultContent": "" },
{ "data": "SiteName", "name": "SiteName", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyId", "name": "CompanyId", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyName", "name": "CompanyName", "autoWidth": true, "defaultContent": "" },
{ "data": "IsAdminSite", "name": "IsAdminSite", "autoWidth": true, "defaultContent": "" },
{ "data": "IsEnabled", "name": "IsEnabled", "autoWidth": true, "defaultContent": "" },
{
"render": function (data, type, full, meta) { return `<i class="far fa-edit text-primary" title="Edit">`; }
}
],
// From StackOverflow http://stackoverflow.com/a/33377633/1988326 - hides pagination if only 1 page
"preDrawCallback": function (settings) {
var api = new $.fn.dataTable.Api(settings);
var pagination = $(this)
.closest('.dataTables_wrapper')
.find('.dataTables_paginate');
pagination.toggle(api.page.info().pages > 1);
}
});
});
</script>
And here is the loaddata action in my SitesController class;
public async Task<IActionResult> LoadData()
{
try
{
await SetCurrentUser();
ViewData["Role"] = _currentRole;
var draw = HttpContext.Request.Form["draw"].FirstOrDefault();
var start = Request.Form["start"].FirstOrDefault();
var length = Request.Form["length"].FirstOrDefault();
var sortColumn = Request.Form["columns[" + Request.Form["order[0][column]"].FirstOrDefault() + "][name]"].FirstOrDefault();
var sortColumnDirection = Request.Form["order[0][dir]"].FirstOrDefault();
var searchValue = Request.Form["search[value]"].FirstOrDefault();
var pageSize = length != null ? Convert.ToInt32(length) : 0;
var skip = start != null ? Convert.ToInt32(start) : 0;
var request = new SitesGetListRequest
{
OrderBy = SetOrderBy(sortColumn, sortColumnDirection),
Filter = SetFilter(searchValue),
PageNumber = (skip / pageSize) + 1,
PageSize = pageSize
};
var tokenSource = new CancellationTokenSource();
var token = tokenSource.Token;
var endpoint = $"api/companies/{SetCompanyId()}/sites/filtered";
var siteData = await _client.GetSiteListAsync(request, endpoint, token);
if (siteData.Sites != null)
{
return Json(new
{
draw,
recordsFiltered = siteData.Paging.TotalCount,
recordsTotal = siteData.Paging.TotalCount,
data = siteData.Sites.ToList()
});
}
//TODO: Find a way to pass error to a Bootstrap alert-warning DIV rather than the jQuery (javascript) alert box
var errorMessage = $"Http Status Code: {siteData.StatusCode} - {siteData.ErrorMessages.FirstOrDefault()}";
return Json(new
{
data = "",
error = errorMessage
});
}
catch (Exception ex)
{
const string message = "An exception has occurred trying to get the list of Site records.";
_logger.LogError(ex, message);
throw;
}
}
As it stands right now, If an error exists in the object returned from the API call, I pass a message to the error property in the returned json and it shows up as an javascript alert popup box on my cshtml page and when I click OK, the datatable displays "No records found", as shown in the images below;
and...
What I want is for the error message to display in a bootstrap alert-danger div at the top of the cshtml page. I so not want the alert popup to appear and I still want the datatable to show "No records found".
I think that what I am looking for is described on Enable datatable warning alert...
Disable the alert popup by using
$.fn.dataTable.ext.errMode = 'none';
And pass the error message to the BootStrap div using
$('#example')
.on( 'error.dt', function ( e, settings, techNote, message ) {
console.log( 'An error has been reported by DataTables: ', message );
} )
.DataTable();
but instead of
console.log( 'An error has been reported by DataTables: ', message );
use something like
$("#error").html(MY ERROR MESSAGE HERE);
and assign id="error" to the bootstrap div.
But, I am having trouble figuring out how to trigger the Ajax call from my loaddata method in the SitesController and also how to correctly add the error event to the beginning of my datatable script.
Before I burn more time trying to work this out, I thought I would put this on SO and see if anyone with javascrit/jquery experience can provide some guidance.
You can add the error property to the ajax call. Probably the best will be to use fnServerData.
jQuery(document).ready(function ($) {
var table = $("#sitelist").DataTable({
"processing": true,
"serverSide": true,
"filter": true,
"orderMulti": false,
"sAjaxSource": "/Sites/LoadData",
"fnServerData": function (sSource, aoData, fnCallback) {
$.ajax({
"dataType": 'json',
"type": "GET",
"url": sSource,
"data": aoData,
"cache": false,
"success": function (data) {
fnCallback(data);
},
"error": function(error){
$("#error").html(error);
}
});
},
"columnDefs": [
{ "orderable": false, "targets": 6 },
{ "className": "text-center", "targets": [4, 5] },
{
"targets": [4, 5],
"createdCell": function(td, cellData, rowData, row, col) {
if (cellData) {
$(td).html('<i class="far fa-check-circle text-primary""></i>');
} else {
$(td).html('<i class="far fa-times-circle text-danger""></i>');
}
}
}
],
"columns": [
{ "data": "Id", "name": "Id", "autoWidth": true, "defaultContent": "" },
{ "data": "SiteName", "name": "SiteName", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyId", "name": "CompanyId", "autoWidth": true, "defaultContent": "" },
{ "data": "CompanyName", "name": "CompanyName", "autoWidth": true, "defaultContent": "" },
{ "data": "IsAdminSite", "name": "IsAdminSite", "autoWidth": true, "defaultContent": "" },
{ "data": "IsEnabled", "name": "IsEnabled", "autoWidth": true, "defaultContent": "" },
{
"render": function (data, type, full, meta) { return `<i class="far fa-edit text-primary" title="Edit">`; }
}
],
// From StackOverflow http://stackoverflow.com/a/33377633/1988326 - hides pagination if only 1 page
"preDrawCallback": function (settings) {
var api = new $.fn.dataTable.Api(settings);
var pagination = $(this)
.closest('.dataTables_wrapper')
.find('.dataTables_paginate');
pagination.toggle(api.page.info().pages > 1);
}
});
});
</script>

How to Update Datatable automatically after dialog box is closed in Javascript

Here I have two JS files in which one is main JS file for parent page which contains Datatable which gets populated through ajax call. And other one is specifically for update functionality in which function is defined to update required values into database. That update is done in dialog box. So after successful update sweet alert comes which shows product is successfully updated. So what I want is updated values should be immediately reflected in Datatable of Parent Page. Currently it is showing old value only untill I refresh my page manually. Below are both JS files. And I am new in Javascript and Jquery. So Please help
var oTable;
var url_data_source;
(function(window, undefined) {
window.lastQuery = null;
function initDataSource(after_id) {
url_data_source = '/event/productlocation/ajax?action=data_source';
oTable = $('#datatable').dataTable({
"sAjaxSource": url_data_source,
"bProcessing": true,
"bServerSide": true,
"bFilter": false,
"bRetrieve": true,
"bScrollCollapse": true,
"iCookieDuration": 60*60*24,
"sCookiePrefix": "tkpd_datatable_",
"sPaginationType": "simple",
"scrollX": true,
"aaSorting": [ [0,'desc'] ],
"iDisplayLength": 20,
"aLengthMenu": [[20, 40, 60, 80, 100], [20, 40, 60, 80, 100]],
"oLanguage": {
"sInfoFiltered": "",
"sProcessing": " "
},
"aoColumns": [
{ "sName": "id", "mDataProp": "id"},
{ "sName": "location_id", "mDataProp": "location_id"},
{ "sName": "product_id", "mDataProp": "product_id"},
{ "sName": "status_str", "mDataProp": "status_str"},
{ "sName": "actions", "mDataProp": "actions"},
],
"fnDrawCallback":function(){
},
"initComplete": function(settings, json) {
$("#datatable_paginate").on("click", "#datatable_next", function(){
var after_id = ""
url_data_source = '/event/productlocation/ajax?action=data_source';
after_id_url = $("#after_id_url").val();
after_id = after_id_url.split("after_id=")
url_data_source += "&after_id="+after_id[1];
redraw();
});
},
"fnServerData": function ( sSource, aoData, fnCallback ) {
aoData.push( {"name": "email", "value": $('#search_email').val()} );
if (after_id != "") {
aoData.push( {"name": "after_id", "value": after_id} );
}
if ($('#search_id_product').val()) {
aoData.push( {"name": "product_id", "value": $('#search_id_product').val()} );
}
$.ajax({
"dataType": 'json',
"type": "GET",
"url": url_data_source,
"data": aoData,
"success": function(result) {
var message_error = result.message_error
if (message_error) {
$('#datatable_processing').css("visibility","hidden");
swal({ title: message_error, type: "error"});
} else if (result.status == "OK") {
result.data = formatingDatatable(result.data)
fnCallback(result)
lastQuery = aoData;
} else {
$('#datatable_processing').css("visibility","hidden");
swal({ title: "Tidak ada hasil", type: "info"});
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
swal({ title: manager.getAjaxError(XMLHttpRequest), type: "error"});
$('#datatable_processing').css("visibility","hidden");
$('.load__overlay').hide();
},
beforeSend: function() {
$('#datatable_processing').css("visibility","visible");
$('.load__overlay').show();
},
complete: function() {
$('#datatable_processing').css("visibility","hidden");
$('.load__overlay').hide();
}
});
}
});
}
function redraw() {
$("#datatable").dataTable().fnClearTable();
}
function formatingDatatable(events) {
var result = [];
var uri_next;
$.each(events.location_products, function(i, productlocation) {
result.push({
id: productlocation.id,
location_id: productlocation.location_id,
product_id: productlocation.product_id,
status_str: productlocation.status_str,
actions:'<button class="btn btn-primary waves-effect waves-light m-b-5 btn-sm m-r-5 btn-sm detail-productlocation" data-target="#modal-event-productlocation-detail" data-toggle="modal" data-id="' + productlocation.id + '" product-id="' + productlocation.product_id + '" location-id="' + productlocation.location_id + '" status-str="' + productlocation.status_str + '"><i class="glyphicon glyphicon-list"></i> Details</button>'
});
})
$("#after_id_url").val(events.page.uri_next)
uri_next = events.page.uri_next
result.after_id_url = uri_next
return result
}
function initFilter() {
$("#filter-form").submit(function() {
url_data_source = '/event/productlocation/ajax?action=data_source';
if(oTable == null){
initDataSource("");
} else {
oTable.fnDraw();
}
return false;
});
}
$('#datatable_paginate').on('click', '#datatable_next', function() {
initDataSource("");
})
$('#datatable').on('click', '.detail-productlocation', function() {
$('.load__overlay').show();
$("#modal-event-productlocation-detail").remove();
$(this).removeAttr("data-target", "#modal-event-productlocation-detail");
$(this).removeAttr("data-toggle", "modal");
//var id = $(this).attr("data-id");
var dt = {
"id": $(this).attr("data-id"),
"product_id": $(this).attr("product-id"),
"location_id": $(this).attr("location-id"),
"status": $(this).attr("status-str"),
}
$.ajax({
"url": '/event/productlocation/ajax?action=show_dialog_details',
"type": 'GET',
"data": dt,
success: function (result) {
$('.load__overlay').hide();
$("body").append(result);
$(this).attr("data-target", "#modal-event-productlocation-detail");
$(this).attr("data-toggle", "modal");
$('#modal-event-productlocation-detail').modal('show');
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
$('.load__overlay').hide();
swal({ title: manager.getAjaxError(XMLHttpRequest), type: "error", });
},
});
});
$(document).ready(function() {
//initDate();
initFilter();
//initCategoryList();
var after_id = "";
initDataSource(after_id);
});
})(window);
event-productlocation-update.js
function sendProductLocationData() {
var jsonData = {};
var formFields = $(":input");
jQuery.each(formFields, function(i, field) { //Accessing all the element of form and get Key and Value
var key = field.name; //Keyname of each Field
var elementid = field.id; //Id of each Field
elementid = "#" + elementid;
var value = $(elementid).val();
jsonData[key] = parseInt(value);
if (key == "status") {
if ($("#event_checkbox_status").is(':checked') == true) {
jsonData.status = 1;
} else {
jsonData.status = 0;
}
}
});
productlocationdetail = JSON.stringify(jsonData); //Creating json Object
$.ajax({
url: '/update/product/productlocation',
type: 'post',
dataType: 'json',
contentType: 'application/json',
data: productlocationdetail,
"success": function(result) {
var message_error = result.message_error
if (message_error) {
$('#modal-event-productlocation-detail').css("visibility", "hidden")
swal({
title: message_error,
type: "error"
});
$('.modal-backdrop').remove();
} else {
$('#modal-event-productlocation-detail').css("visibility", "hidden")
swal({
title: "Product Location Updated Successfully",
type: "info"
});
$('.modal-backdrop').remove();
}
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
swal({
title: manager.getAjaxError(XMLHttpRequest),
type: "error"
});
$('#modal-event-productlocation-detail').css("visibility", "hidden")
$('.modal-backdrop').remove();
$('.load__overlay').hide();
},
beforeSend: function() {
$('#modal-event-productlocation-detail').css("visibility", "visible")
$('.modal-backdrop').remove();
},
complete: function() {
swal({
title: "Product Location Updated Successfully",
type: "info"
});
$('#modal-event-productlocation-detail').css("visibility", "hidden")
$('.modal-backdrop').remove();
$('.load__overlay').hide();
}
});
}
There are a few way you could handle this.
One way you could handle this is to store the item/s in a variable in a jSON array.
When get confirmation back from the server that that the the update was successful you could then create function to update the dataTable with with this function.
function updateDataTable(dataTableObj,jsonArray)
/*
Clears and populates the dataTable with JSON array
*/
dataTableObj.clear();
jsonArray.forEach(function(row){
dataTableObj.row.add(row);
});
dataTableObj.draw();
}
The other way you could update the table is to create a route on your server that sends the jsonArray but this requires an additional request to the server.
Note: If you use the Ajax call be sure to invoke the function inside the the ajax callback function

Reload Datatable with new aaData value

How to refresh the Datatable, When new Json data is sent
POST request Receives data , which is sent to LoadTable function to populate the datatable.
function initializeTable(){
$("#submitbutton").on(
'click',
function(){
$.ajax({
type : 'POST',
url : 'rest/log/events',
data : {
fromTime : $("#fromTime-filter").val(),
toTime : $("#toTime-filter").val(),
Text : $("#search-filter-input").val()
},
success : function(data) {
loadTable(data);
},
error : function(jqXHR, textStatus, errorThrown) {
showAjaxError(jqXHR, textStatus, errorThrown,
$("#error-msg"));
}
});
});
}
'data' is passed to Load function, which loads the data to a table correctly the first time.
When i submit the POST request the second time, i see New 'data' in the browser console, but the Datatable is not refreshed.
But when i Refresh the Page(datatable is cleared) and then do a new POST, new data loads normally. I want the new data to be loaded without the need to refresh the page.
function loadTable(data)
{
$('#report-table').dataTable( {
bProcessing : true,
bJQueryUI : true,
bLengthChange : false,
bDestory : true,
bRetrieve : true,
bStateSave : true,
oTableTools: {
sRowSelect: "multi",
aButtons: [ "select_all", "select_none" ]
},
iDisplayLength : 20,
"aaData": data,
"aoColumns": [
{ "mData" : "date" },
{ "mData" : "name" },
{ "mData" : "type" },
{ "mData" : "section" }
]
} );
}
It looks to me like you're using DataTables v1.9. Here's how I'd do it:
function loadTable(data)
{
var table = $('#report-table');
if ( ! $.fn.DataTable.fnIsDataTable( table[0] ) ) {
table.dataTable( {
bProcessing : true,
bJQueryUI : true,
bLengthChange : false,
bDestory : true,
bRetrieve : true,
bStateSave : true,
oTableTools: {
sRowSelect: "multi",
aButtons: [ "select_all", "select_none" ]
},
iDisplayLength : 20,
"aaData": data,
"aoColumns": [
{ "mData" : "date" },
{ "mData" : "name" },
{ "mData" : "type" },
{ "mData" : "section" }
]
} );
} else {
table.dataTable().fnUpdate(data);
}
}
Another option:
function loadTable(data)
{
var table = $('#report-table');
if ( ! $.fn.DataTable.fnIsDataTable( table[0] ) ) {
table.dataTable( {
bProcessing : true,
bJQueryUI : true,
bLengthChange : false,
bDestory : true,
bRetrieve : true,
bStateSave : true,
oTableTools: {
sRowSelect: "multi",
aButtons: [ "select_all", "select_none" ]
},
iDisplayLength : 20,
"aaData": data,
"aoColumns": [
{ "mData" : "date" },
{ "mData" : "name" },
{ "mData" : "type" },
{ "mData" : "section" }
]
} );
} else {
table.dataTable().fnDestroy();
loadTable(data);
}
}

Chaining methods that have on your body ajax call

I have this class:
function Clazz() {
this.id;
this.description;
}
Clazz.prototype._insert = function(_description, _success, _error) {
this.description = _description;
$.ajax({
type : "PUT",
url : "api/route",
data : JSON.stringify(this),
dataType : "json",
contentType : "application/json;charset=UTF-8",
success : function() {
_success($("#message"), 'OK');
},
error : function() {
_error($("#message"), 'FAIL');
}
});
};
Clazz.prototype._findAll = function(_callback) {
$.ajax({
type : "GET",
url : "api/route",
dataType : "json",
success : function(data) {
_callback(data);
}
});
};
On the button click, I have this:
var clazz = new Clazz();
clazz._insert($("#description").val(), success, error);
clazz._findAll(loadCallback);
Below the loadCallback method:
function loadCallback(data){
var oTable = $('#table').dataTable({
"bRetrieve": true,
"bDestroy" : true,
"bFilter" : false,
"bLengthChange" : false,
"bInfo" : false,
"sDom" : "<'row'<'span5'l><'span5'f>r>t<'row'<'span5'i><'span5'p>>",
"sPaginationType" : "bootstrap",
"oLanguage" : {
"sProcessing" : "Loading ...",
"sZeroRecords" : "No records",
"oPaginate" : {
"sNext" : "",
"sPrevious" : ""
}
},
"iDisplayLength" : 4,
"aaData" : data,
"aoColumnDefs" : [
{ "aTargets" : [0], "mData" : "description", "sTitle" : "My Data" },
{ "aTargets" : [1],
"sWidth" : "20px",
"mData" : "id",
"bSortable" : false,
"mRender" : function ( data ) {
return '<img src="img/img01.png" style="height: 20px; width: 20px;"/>';
}
},
{ "aTargets" : [2],
"sWidth" : "20px",
"mData" : "id",
"bSortable" : false,
"mRender" : function ( data ) {
return '<img src="img/img02.png" style="height: 20px; width: 20px;"/>';
}
},
{ "aTargets" : [3],
"sWidth" : "20px",
"mData" : "id",
"bSortable" : false,
"mRender" : function ( data ) {
return '<img src="img/img03.png" style="height: 20px; width: 20px;"/>';
}
}
],
"fnHeaderCallback" : function( nHead ) {
$(nHead.getElementsByTagName('th')[0]).attr("colspan","4");
for(var i = 1; i <= 3; i++){
$(nHead.getElementsByTagName('th')[1]).remove();
}
},
"fnRowCallback" : function( nRow ) {
$(nRow.getElementsByTagName('td')[1]).attr("width","20px");
$(nRow.getElementsByTagName('td')[2]).attr("width","20px");
$(nRow.getElementsByTagName('td')[3]).attr("width","20px");
}
});
oTable.fnClearTable();
oTable.fnAddData(data);
oTable.fnDraw();
}
I want that the method clazz._findAll(loadCallback); only execute after the clazz._insert finish.
I already tried $.when but it did not work.
$.when should work if clazz._insert returns the $.ajax function call (which it currently does not).
If you return the $.ajax call, you should be able to do something like:
$.when(clazz._insert(...stuff...)).then(clazz._findAll(...stuff...));
Might be a good idea to double-check the documentation on deferred objects.
I solved doing this:
Putting return $.ajax(...stuff...) in the insert method
Using
$.when(clazz._insert($("#description").val())).done(
function(){
clazz._findAll(loadCallback);
}
);
I had to call the _findAll inside an anonimous function.

Categories

Resources