JQuery - removing entry from a cookie - javascript

I have a cookie which I would like to read then remove one entry from it based in the widget ID.
if (thisWidgetSettings.removable) {
$('CLOSE').mousedown(function (e) {
/* STOP event bubbling */
e.stopPropagation();
}).click(function () {
if(confirm('This widget will be removed, ok?')) {
$.ajax({
type: "get",
url: "/controllers/widget.php",
data: {
method: "remove",
widgetID:thisWidget.id,
},
dataType: "json",
});
var mycookie = $.cookie("mypreferences");
//remove based on id here
as suggested...
var cookieName = 'myCookie';
var cookie = $.cookie("preferences");
var cookie = cookie.split('|');
$(cookie).each(function(index){
var thisCookieData = this.split(',');
alert(thisCookieData);
});

use split() to get individual elements from your cookie and than loop through them, and remove it. and then combine the rest of your entries and save it.
split reference:
http://www.w3schools.com/jsref/jsref_split.asp

Related

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

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();
}
}

Jquery on click event is not working when ajax call is running at loop

I have two ajax functions that one is recursively working at loop and other is working when click event invoked. I tested both of the functions that are able to work properly. But when i start recursive function button event is not invoked.
Function that works on click event GET Content from ActionResult (MVC)
function UpdateRequests(url, state, id, cell)
{
$.ajax({
type: "GET",
url: url + id,
success: function (result) {
if (result == "OK")
{
cell.fadeOut("normal", function () {
$(this).html(state);
}).fadeIn();
}
else if(result == "DELETE" || result == "CANCEL")
{
cell.parent().fadeOut("normal", function () {
$(this).remove();
});
}
else
{
$(".modal-body").html(result);
$("#myModal").modal();
}
},
error: function () {
alert("Something went wrong");
}
});
}
Recursive function GET partial view from ActionResult (MVC)
function RefreshRequests()
{
if (isListPage())
{
var id = PageId();
var url = "/Home/List/" + id;
}
else
{
var url = "/Home/Index";
}
$.ajax({
type: "GET",
url: url,
success: function (data) {
$(".ajaxRefresh").html(data);
EditPageHeader();
},
complete: function () {
setTimeout(RefreshRequests, 2000);
}
});
}
Click event
$(".tblRequests").on("click", button, function (e) {
e.preventDefault();
var id = $(this).data("id");
var currentRow = $(this).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
});
Main
$(document).ready(function () {
EditPageHeader();
RefreshRequests();
ButtonEvent(".btnPrepare", "/Home/Prepare/", "PREPARING");
ButtonEvent(".btnApprove", "/Home/Approve/", "APPROVED");
ButtonEvent(".btnCancel", "/Home/Cancel/", "CANCELED");
RefreshRequests();
});
Assumptions:
The Ajax Calls bring you data that end up as HTML elements in the modal body.
These new elements added above need to respond to the click event (the one that doesn't work correctly right now)
If the above 2 are true, than what is happening is you are binding events to existing elements (if any) and new elements (coming from API response) are not bound to the click event.
The statement
$(".tblRequests").on("click", button, function (e) {
...
})
needs to be executed every time new elements are added to the body. A better approach for this would be to define the event handler as an individual method and then bind it to each new element.
var clickHandler = function (e) {
e.preventDefault();
var id = $(this).data("id");
var currentRow = $(this).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
}
// Then for each new record that you add
$(".tblRequests").on("click", button, clickHandler);
It would be helpful if you can try to explain what exactly you are trying to achieve.
Problem is that the $(this) will hold all elements of the selector. And will also now with one as it will be triggered one time and then never again. Also as can be seen from here, delegate events should be at the closest static element that will contain the dynamic elements.
function ButtonEvent(button, url, state)
{
$("body").on("click", button, function (e) {
e.preventDefault();
var button = e.target;
var id = $(button).data("id");
var currentRow = $(button).closest("tr");
var cell = currentRow.children('td.requestState');
UpdateRequests(url, state, id, cell);
});
}

YUI after appending body, on('click') even doesn't work

Hello I have been trying to build my DOM with html templates and js, but i had problem with this code.;
YUI().use(
'aui-modal',
'stylesheet',
'aui-io-request',
function(Y) {
var officers;
Y.io.request('https://demo6120867.mockable.io/cmdOfficers', {
method: 'GET',
dataType: 'json',
on: {
success:function() {
officers = this.get('responseData').officers;
for(var i=0;i<officers.length;i++){
var template = Y.one("#officerTemplate")
var officerName = template.one("#officerName");
var officerDepartment = template.one("#department");
var officerId;
officerName.set('innerText',officers[i].officerName);
officerDepartment.set('innerText',officers[i].department);
var buttonHolder = template.one("#action_buttons")
var officerButtons = buttonHolder.all(".hp");
console.log("Officer Buttons")
console.log(officerButtons[0]);
console.log("Officer Buttons all");
console.log(officerButtons);
officerButtons.each(function(buttonNode,index){
console.log(buttonNode);
officerId = officers[i].id;
var data = buttonNode.getData("id");
// This will not get store in dom.
buttonNode.setData("id",i+"_"+index);
buttonNode.setData("officer_id",officerId);
console.log(buttonNode.getData("id"));
});
var bodyNode = Y.one(document.body);
var newItem = Y.Node.create(template.getContent()).setStyle("display","block");;
newItem.set('id','officer_'+i);
bodyNode.append(newItem);
// when we have template we can insert our data and append to dom.
}
}
}
});
The last line of code as you see is appending body so i am expecting when i call
Y.all(".hp").on("click",function(e){
console.log("clicked");
click function doesn't work, how can i workaround this problem.
Thanks.
Looks like this might be a perfect case for event delegation. Since the elements in questions are not in the DOM yet when the event is bound.
Y.one(document.body).delegate("click", function(e) {
console.log("clicked");
}, ".hp");
The document body can be replaced with the closest parent that contains the .hp elements.
https://davidwalsh.name/event-delegate

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();

Categories