How to catch end of html manipulations in KendoGrid after read()? - javascript

I have KendoGrid and want to detect end of all manipulations (including manipulations with html) after read(). How can I catch this event?
I have tried to use RequestEnd event with type "read", but after catching this event Kendo changes some html code in page.
Update after adding databound
I have KendoSortable, binded to KendoGrid, which contains column with positions. After position changes (onChange function), I need to block page (showLoader func) and update positions. As positions have changed, grid data (column with positions) must be reload by read(). And AFTER read() I need to unblock page by hideLoader. So, now, if I don't unbind onDataBound, my page is unblocked after remove/insert.
function onDataBound(e) {
if (ir == 0) {
updatePostion();
}
else {
hideLoader();
}
ir++;
}
function onChange(e) {
var grid = $("#TestQuestionAnswerList").data("kendoGrid");
grid.unbind("dataBound");
var newIndex = e.newIndex;
var dataItem = grid.dataSource.getByUid(e.item.data("uid"));
grid.dataSource.remove(dataItem);
grid.dataSource.insert(newIndex, dataItem);
grid.bind("dataBound", onDataBound);
showLoader();
updatePostion();
}
function updatePostion() {
if (#Model.Type == 3) {
var positions = [];
grid._data.forEach(function (entry) {
positions.push(entry.ID);
});
var dataToPost = { positions: positions, questionID: #Model.ID };
$.ajax({
url: '#Url.Action("ChangePositions", "Testing")',
type: 'POST',
data: JSON.stringify(dataToPost),
datatype: 'json',
cache: false,
contentType: "application/jsonrequest; charset=utf-8",
success: function (data) {
grid.dataSource.read();
},
error: function () {
hideLoader();
alert("error");
}
});
}
else {
grid.dataSource.read();
}
}

Related

Add ajax to existing page with jquery-ui

I need help with an advanced search I implemented into a new existing page system.
It seems there is a problem with the existing jquery ui on the page:
<script src="js/jquery-ui-1.10.4.custom.js"></script>
<script type="text/javascript" src="js/jquery.lazy.min.js"></script>
When I enter my code the page isn't working properly anymore.
My code:
$(document).ready(function() {
// Icon Click Focus
$('div.icon').click(function(){
$('input#warenkorb_suche_feld').focus();
});
// Live Search
// On Search Submit and Get Results
function search() {
var query_value = $('input#warenkorb_suche_feld').val();
$('b#search-string').text(query_value);
if(query_value !== ''){
$.ajax({
type: "POST",
url: "search.php",
data: { query: query_value },
cache: false,
success: function(html){
$("ul#results").html(html);
}
});
}return false;
}
$("input#warenkorb_suche_feld").live("keyup", function(e) {
// Set Timeout
clearTimeout($.data(this, 'timer'));
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string == '') {
$("ul#results").fadeOut();
$('h4#results-text').fadeOut();
}else{
$("ul#results").fadeIn();
$('h4#results-text').fadeIn();
$(this).data('timer', setTimeout(search, 100));
};
});
});
The search script works fine but I need to add
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
And after this page stops working. What can I do to get this stuff working?
Consider the following. I was not able to test it.
$(function() {
function search(term, callback) {
$('b#search-string').text(term);
$.ajax({
type: "POST",
url: "search.php",
data: {
query: term
},
cache: false,
success: function(html) {
$("ul#results").html(html);
if(callback && (typeof callback == "function")){
callback();
}
}
});
return false;
}
$('div.icon').click(function() {
$('input#warenkorb_suche_feld').focus();
});
$("input#warenkorb_suche_feld").on("keyup", function(e) {
// Set Search String
var search_string = $(this).val();
// Do Search
if (search_string.length > 0) {
$("ul#results, h4#results-text").fadeOut(400, function() {
search(search_string, function() {
$("ul#results, h4#results-text").fadeIn();
});
});
}
});
});
This makes use of the complete callback for .fadeOut(). So once it has faded, it will then run the search. I added a Callback in the search so that once the AJAX has completed, it will reveal the results with .fadeIn().
You may want to consider adjusting the length condition. This ensures

Slickgrid changes the ID from my data and dont clean up the empty row

Im trying to update my grid without the need for refreshing! Right now, it updates only the grid, but dont know why, it changes the id to the last one inserted and dont "clean up" the empty row! When I try to insert data, it clears it .
Im kinda new with ajax and slickgrid! I've tried to see the ajax example from slickgrid, but I got some errors!
Do I need to re-upload the onCellChange and so on ? I just wanted to update th grid with the new data.
Any help?
Thanks in advance
So, I've tried re-draw the table re-using my actual drawning code, but im failling to re-draw with correct data.
Function to re-draw grid
function desenhaGrid() {
$("#myGrid").ready(function () {
$(function () {
$.ajax({
type: "GET",
url: '/SlickGrid/GetData',
dataType: 'json',
success: function (jsonResult) {
for (var key in jsonResult) {
if (jsonResult.hasOwnProperty(key)) {
//print table
var d = (data[key] = {});
for (var i = 0; i < data.length; i++) {
d["#"] = i + 1;
}
d["id"] = jsonResult[key].id;
d["t_nome"] = jsonResult[key].t_nome;
d["t_prof"] = jsonResult[key].t_prof;
d["t_data"] = jsonResult[key].t_data;
d["t_morada"] = jsonResult[key].t_morada;
d["t_percCompleto"] = jsonResult[key].t_percCompleto;
}
}
grid = new Slick.Grid("#myGrid", dataView, columns, options);
dataView.beginUpdate();
grid.invalidateAllRows();
dataView.setItems(data);
grid.render();
dataView.endUpdate();
}
});
});
});
}
and this is my onAddNewRow
grid.onAddNewRow.subscribe(function (e, args) {
var idData = jsonResult[key].id + 1;
var item = { "id": idData, "t_nome": '', "t_prof": '', "t_data": '', "t_morada": '', "t_percCompleto": '' };
$.extend(item, args.item);
dataView.addItem(item);
//if user press enter
grid.onKeyDown.subscribe(function (e) {
var keyPressed = event.keyCode || event.which;
if (keyPressed == 13) {
alert("add");
var myJSON = JSON.stringify(item);
$.post("/SlickGrid/addGridEnter", $("input[name=mydata]").val(myJSON));
console.log(myJSON);
desenhaGrid();
}
});
});
I expected it to re-draw my grid with all the data. Instead, its changing all the id's to the last one inserted and when I try to insert data in the last row, wont let me (it clears it after I leave the cell).
UPDATE:
I've udpate the function to draw the grid
function desenhaGrid() {
$("#myGrid").load(function () {
$(function () {
$.ajax({
type: "GET",
url: '/SlickGrid/GetData',
dataType: 'json',
success: function (jsonResult) {
dataView.beginUpdate();
grid.invalidateAllRows();
dataView.setItems(jsonResult);
dataView.endUpdate();
grid.render();
}
});
});
});
}
I don't think this is a SlickGrid issue. There are all kind of problems with the javascript. For example:
why are you using $("#myGrid").ready( ? the ready event only fires when the DOM has finished loading
the entire copy operation from jsonResult to data just ends up with the same data. why not use jsonResult directly?
the section for (var i = 0; i < data.length; i++) { d["#"] = i + 1; }
runs once for each row added to data, it should just run once at the end, outside of the loop
you are subscribing to the keydown event once for each row added to the grid. you should just subscribe once. listening for an Enter key is also a very poor method of determining if a row has been entered. what if someone clicks on another row before pressing Enter?
Slickgrid is a client-side grid. This means data does not need to be persisted after every change. It's a common approach to use a 'save' button, or detect if the active row has changed.

How to re-oder serial numbers after remove deleted row from datatable

After i deleted row the serial number column number are not re-ordered
I have Delete button in each row on click calling Ajax to delete record from data. It's deleting record from data base, after deleted recording I want to display remain data and remove particular row in table but it's changing pagination and refreshing the whole table.
var owner_table = null;
$(document).ready(function () {
owner_table = $('#owners_table').DataTable();
});
function deletehouseowner(oid, rid) {
$.ajax({
dataType: "HTML",
type: "POST",
data: {
"oid": oid
},
url: "houseowner_delete.php",
success: function (msg) {
if (msg === "failure") {
} else {
event.preventDefault();
var table = 'owners_table';
var row = $(this).closest('tr');
var id = row.attr("id");
setTimeout(function () {
var siblings = row.siblings();
owner_table.row($('#row_' + rid)).remove().draw();
siblings.each(function (index) {
$(this).children().first().text(index + 1);
});
}, 100);
}
}
});
}
Screenshot:
SOLUTION
API method draw() accepts optional parameter that controls how the table should be updated.
Pass false to draw() function to preserve current page, see the code below:
owner_table.row($('#row_'+rid)).remove().draw(false);
DEMO
See this jsFiddle for code and demonstration.

Adding Gritter Message After Second Deletion

I'm trying to find out why when a user is deleted by clicking on the ajax-delete class icon and performs the deletion process it shows the gritter message after deletion however if you were to immediately delete another user afterwards it removes the previous gritter message but doesn't show another for that second deletion. Any ideas on why this could be?
EDIT: I have figured out that the issue belongs to the $.gritter.removeAll(); code line. When there is another existing notification it removes it but doesn't add the next notification.
Any ideas what I should do here?
var rowToDelete = null;
var basicTable = null;
var api_url = null;
$(document).ready(function() {});
$(document).on('click', '.ajax-delete', function(e)
{
console.log(basicTable);
e.preventDefault();
//defining it like this captures and optimizing the need to cycle over the DOM more than once
//in subsequent calls to the element specifically
$elem = $(this);
$parentElem = $elem.closest('tr');
rowToDelete = $parentElem.get(0);
api_url = $elem.attr('href');
runConfirmation($('td:eq(1)', $parentElem).text());
});
function runConfirmation(nameSting)
{
$mymodal = $('#myModal');
$('.modal-body p', $mymodal).html('Are you sure you want to delete this <strong>'+nameSting+'</strong>?');
$mymodal.modal('show');
}
$('#myModalConfirm').on('click', function(e) {
$.ajax({
type: 'post',
url: api_url,
data: { _method: 'DELETE' },
dataType: 'json',
success: function(response) {
$.gritter.removeAll();
var className = 'growl-danger';
if (response.status == "SUCCESS") {
className = 'growl-success';
basicTable.fnDeleteRow(basicTable.fnGetPosition(rowToDelete));
rowToDelete = null;
api_url = null;
}
$.gritter.add({
position: 'top-right',
fade_in_speed: 'medium',
fade_out_speed: 2000,
time: 6000,
title: response.title,
text: response.message,
class_name: className,
sticky: false
});
}
});
$('#myModal').modal('hide');
});
Replace the following line:
$.gritter.removeAll();
With
$('.gritter-item-wrapper').remove();

javascript async request blocks user interaction

I have got a 2d map for a game and every time the user moved the map, new data is reloaded from the server. While the (asynchronous!) ajax request is loading, every user interaction with the map is ignored. So if i want to move the map and do a mousedown -> mousemove -> mouseup, these events are just ignored.
I tried it both with jQuery 1.5.1 and 1.6.4.
My code:
$map_outer.mousedown(function(e) {
e.preventDefault();
engine.map.mouse_down_coords = {x: e.pageX, y: e.pageY};
engine.map.mouse_is_down = true;
engine.map.mouse_down_offset = $map.offset();
}).mouseup(function(e) {
if (!engine.map.mouse_is_down) return;
$.ajax({
type: 'post',
data: {
//...
},
success: function(data) {
//....
},
dataType: 'json',
async: true
});
engine.map.mouse_is_down = false;
}).mouseleave(function() {
engine.map.mouse_is_down = false;
}).mousemove(function(e) {
e.preventDefault();
if (!engine.map.mouse_is_down) return;
//... move the map
});
Why does this block the browser for some hundred milliseconds? (sometypes 300ms on localhost!)
Thanks in advance,
levu

Categories