On confirm delete? - ajax

i have this mootools code that on click of a button deletes the record,now i want when the user clicks the delete button a confirm dialog pop up asking am i sure that i want to delete the record with the answers yes and no...here is my code...if the user answers yes to continue this request if he answers no dont continue,it would be also great if i had another message saying that the record was deleted after he clicked yes...
<script>
window.addEvent('domready',function() {
$$('a.delete').each(function(el) {
el.addEvent('click',function(e) {
e.stop();
var parent = el.getParent('div');
var request = new Request({
url: '/delete.php',
link: 'chain',
method: 'get',
data: {
'delete': parent.get('id').replace('record-',''),
ajax: 1
},
onRequest: function() {
new Fx.Tween(parent,{
duration:300
}).start('background-color', '#fb6c6c');
},
onSuccess: function() {
new Fx.Slide(parent,{
duration:300,
onComplete: function() {
parent.dispose();
}
}).slideOut();
}
}).send();
});
});
});
</script>

it's simple.
if (confirm('message')){
// code when yes
}
else {
// code when no
}
hence.
$$('a.delete').each(function (el) {
el.addEvent('click', function (e) {
e.stop();
var parent = el.getParent('div');
if (confirm('are you sure you want to delete this?')) {
new Request({
url: '/delete.php',
link: 'chain',
method: 'get',
data: {
'delete': parent.get('id').replace('record-', ''),
ajax: 1
},
onRequest: function () {
new Fx.Tween(parent, {
duration: 300
}).start('background-color', '#fb6c6c');
},
onSuccess: function () {
new Fx.Slide(parent, {
duration: 300,
onComplete: function () {
parent.dispose();
}
}).slideOut();
}
}).send();
} // confirm
});
});

Related

Manual custom Ajax Add to Cart One time payment subscription

Good day, I am trying to manual ajax this
Add to cart
What this does is, It will add to the cart the one-time purchase option from the woocommerce subscription. I am trying to ajax it so it won't refresh the page when you click on it.
I found an idea how to manually ajax it by using these lines of codes. Reference here
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
$thisbutton.removeClass('added').addClass('loading');
},
complete: function(response) {
$thisbutton.addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);
The codes above work and it does ajax however, it displays the monthly subscription, not the one-time purchase. It should display the one-time purchase because of the &convert_to_sub_55337=0 which means the one-time subscription option is selected.
Also, I am getting an error after clicking the button on the console log
Uncaught TypeError: $button is undefined
I am a newbie to handling ajax so I am unsure about the issue
Thank you in advance!!
you can try this code i hope it will helped.
(function($) {
$(document).on('click', '.testing', function(e) {
var $thisbutton = $(this);
try {
var href = $thisbutton.prop('href').split('?')[1];
if (href.indexOf('add-to-cart') === -1) return;
} catch (err) {
return;
}
e.preventDefault();
var product_id = href.split('=')[1];
var data = {
product_id: product_id
};
$(document.body).trigger('adding_to_cart', [$thisbutton, data]);
$.ajax({
type: 'post',
url: wc_add_to_cart_params.wc_ajax_url.replace(
'%%endpoint%%',
'add_to_cart'
),
data: data,
beforeSend: function(response) {
jQuery('.testing').removeClass('added').addClass('loading');
},
complete: function(response) {
jQuery('.testing').addClass('added').removeClass('loading');
},
success: function(response) {
if (response.error & response.product_url) {
window.location = response.product_url;
return;
} else {
$(document.body).trigger('added_to_cart', [
response.fragments,
response.cart_hash
]);
$('a[data-notification-link="cart-overview"]').click();
}
}
});
return false;
});
})(jQuery);

Ajax serialize with extra data MVC

I use a webgid so to display records that have to do with the user. I load this webgrid in a partilal view after the user clicks on an ajax actionlink.
#Ajax.ActionLink(" ", "AddUserElements", "Users", new { username = item.UserName }, new AjaxOptions() { UpdateTargetId = "add_research"}, new { #class = "glyphicon glyphicon-link" })
In this webgrid I have a delete action. When I click the delete a modal appears so to ask for verification. I click on yes and the record is being deleted but the webgrid in the partial view doesn't being refreshed. To update the partial view I use in my ajax code
$("#add_research").load('/Users/AddUserElements');
I tried to pass the username with serialize to controller but no lack
My ajax code
$(function () {
$.ajaxSetup({ cache: false });
$("a[data-modal]").on("click", function (e) {
$('#myModalContent').load(this.href, function () {
$('#myModal').modal({
keyboard: true
}, 'show');
bindForm(this);
});
return false;
});
});
function bindForm(dialog) {
$('form', dialog).submit(function () {
$('#progress').show();
var data = $(this).serialize() + '&' + $.param({ 'username': '#Model.UserName' }, true);
$.ajax({
url: this.action,
type: "POST",
data: data,
cache: false,
success: function (result) {
if (result.success) {
$('#myModal').modal('hide');
$('#progress').hide();
$("#add_research").load('/Users/AddUserElements');
} else {
$('#progress').hide();
$('#myModalContent').html(result);
bindForm();
}
}
});
return false;
});
}
My controller
public ActionResult AddUserElements(string username)
Any idea?
thank you

Kendo UI reload treeview

I load a complex treeview with kendo ui via ajax because I need to load the tree with one request (works fine):
$(document).ready(function() {
buildTree();
});
function buildTree(){
$.getJSON("admin_get_treedata.php", function (data) {
$("#treeview").kendoTreeView({
select: function(item) { editTreeElement(item,'tree'); },
dataSource: data
});
})
}
If I try to reload the complete tree after changing some data via ajax the new build tree does not work correct and does not update the text.
$.ajax({
type: 'POST',
url: 'ajax/ajax_update_layer.php',
data: {
layerid:id,
...
},
success: function(data){
buildTree();
}
});
What can Ido?
Thanks
Sven
try this on ajax success callback
var data = $("#treeView").data('kendoTreeView');
data.dataSource.read();
I got mine to work.
This is what I did:
Function that creates the tree view:
function CreateNotificationTree(userId)
{
var data = new kendo.data.HierarchicalDataSource({
transport: {
read: {
url: "../api/notifications/byuserid/" + userId,
contentType: "application/json"
}
},
schema: {
model: {
children: "notifications"
}
}
});
$("#treeview").kendoTreeView({
dataSource: data,
loadOnDemand: true,
dataUrlField: "LinksTo",
checkboxes: {
checkChildren: true
},
dataTextField: ["notificationType", "NotificationDesc"],
select: treeviewSelect
});
function treeviewSelect(e)
{
var $item = this.dataItem(e.node);
window.open($item.NotificationLink, "_self");
}
}
Modification & data source refresh:
$('#btnDelete').on('click', function()
{
var treeView = $("#treeview").data("kendoTreeView");
var userId = $('#user_id').val();
$('#treeview').find('input:checkbox:checked').each(function()
{
var li = $(this).closest(".k-item")[0];
var notificationId = treeView.dataSource.getByUid(li.getAttribute('data-uid')).ID;
if (notificationId == "undefined")
{
alert('No ID was found for one or more notifications selected. These notifications will not be deleted. Please contact IT about this issue.');
}
else
{
$.ajax(
{
url: '../api/notifications/deleteNotification?userId=' + userId + '&notificationId=' + notificationId,
type: 'DELETE',
success: function()
{
CreateNotificationTree(userId);
alert('Delete successful.');
},
failure: function()
{
alert('Delete failed.');
}
});
treeView.remove($(this).closest('.k-item'));
}
});
});
Hope that helps.

Issue in JQuery Confirmation Dialog inside form submit

In a JQuery dialog I have four fields. When I click on Save button I needs to check and validate the following
Validate all required fields ( On submit of form using validate.js and unobstrusive.js )
Check the value of dropdown and if it is of a partcular type ie (Redundant), Show user a confirmation dialog.
If the user confirm by pressing Yes, then close the confirmation dialog and call Ajax
But the problem is when I confirm by clicking Yes button on confirmation dialog, the dialog closes but the execution is not going down.
ie, Serializing the form data and make an Ajax call to call the webservice.
Please can anyone help.
$(function () {
$('form').submit(function () {
$('#result').html(" ");
var redunt = null;
redunt = $(ClientCrud_StatusCodeId).find('option:selected').text();
if ($(ClientCrud_StatusCodeId).find('option:selected').text() == "Redundant") {
$('#clientRedundantMessage2').html("Client once made redundant cannot be reactivated. Are you sure ?");
$("#RedundantMessage2").dialog(
{
autoOpen: false,
height: 170,
width: 420,
modal: true,
resizable: false,
title: "Confirmation for Redundant",
Content: "Fields cannot be left blank.",
buttons: {
"Yes": function () {
redunt = "Active";
$('#RedundantMessage2').dialog('close');
},
"No": function () {
$(this).dialog("close");
return false;
}
}
}) //.dialog("widget").draggable("option", "containment", "none");
$("#RedundantMessage2").dialog("open");
}
if ($(this).valid())
{
debugger;
if (redunt == "Active") {
$.ajax({
url: this.action,
type: this.method,
async: false,
cache: false,
data: $(this).serialize(),
error: function (request) {
$("#result").html(request.responseText);
// event.preventDefault();
},
success: function (result) {
if (result == "success") {
$.ajax({
url: "/Client/ClientGrid",
type: 'POST',
data: { "page": 0 },
datatype: 'json',
success: function (data) {
$('#grid').html(data);
},
error: function () {
alert('Server error');
}
});
$('#myEditClientDialogContainer').dialog('close');
$('#myEditClientDialogContainer').remove()
}
else {
clearValidationSummary();
var a = '<ul><li>' + result + '</li></ul>';
$('#result').html(a);
}
}
});
}
}
$("#griderrormsg1 li").hide().filter(':lt(1)').show();
return false;
});
editallowed = true;
});
I think you have a issue with the sequence of code, when the function $("#RedundantMessage2").dialog( ...... ); execute don't wait for the user response in this case "yes" or "no" so... your flag redunt = "Active" don't make sense.
the buttons option has function that execute when the opcion is choosen, so you must call a function to execute the post
$(function () {
$('form').submit(function () {
$('#result').html(" ");
var redunt = null;
redunt = $(ClientCrud_StatusCodeId).find('option:selected').text();
if ($(ClientCrud_StatusCodeId).find('option:selected').text() == "Redundant") {
$('#clientRedundantMessage2').html("Client once made redundant cannot be reactivated. Are you sure ?");
$("#RedundantMessage2").dialog(
{
autoOpen: false,
height: 170,
width: 420,
modal: true,
resizable: false,
title: "Confirmation for Redundant",
Content: "Fields cannot be left blank.",
buttons: {
"Yes": function () {
redunt = "Active";
trySend();
$('#RedundantMessage2').dialog('close');
},
"No": function () {
$(this).dialog("close");
return false;
}
}
}) //.dialog("widget").draggable("option", "containment", "none");
$("#RedundantMessage2").dialog("open");
}
$("#griderrormsg1 li").hide().filter(':lt(1)').show();
return false;
});
editallowed = true;
});
the other js function
function trySend(){
if ($('#IdOfYourForm').valid())
{
debugger;
if (redunt == "Active") {
$.ajax({
url: this.action,
type: this.method,
async: false,
cache: false,
data: $(this).serialize(),
error: function (request) {
$("#result").html(request.responseText);
// event.preventDefault();
},
success: function (result) {
if (result == "success") {
$.ajax({
url: "/Client/ClientGrid",
type: 'POST',
data: { "page": 0 },
datatype: 'json',
success: function (data) {
$('#grid').html(data);
},
error: function () {
alert('Server error');
}
});
$('#myEditClientDialogContainer').dialog('close');
$('#myEditClientDialogContainer').remove()
}
else {
clearValidationSummary();
var a = '<ul><li>' + result + '</li></ul>';
$('#result').html(a);
}
}
});
}
}
}

jQuery dialog for a partial view is not opening modal

I have built a jquery dialog to show a partial view for entering data.
I have built the action link:
#Html.ActionLink("Add New Service Provider", "PartialNewCust", "Customer", null, new { #class = "addServiceProviderLink" })
I have the controller action:
public ActionResult PartialNewCust()
{
return PartialView();
}
And the div / jQuery code:
<div id="AddServiceProvDialog" title="Add Service Provider"></div>
<script type="text/javascript">
var linkObj;
$(function () {
$(".addServiceProviderLink").button();
$('#AddServiceProvDialog').dialog(
{
autoOpen: false,
width: 400,
resizable: false,
modal: true,
buttons:
{
"Add": function () {
$("#addProviderForm").submit();
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$(".addServiceProviderLink").click(function () {
linkObj = $(this);
var dialogDiv = $('#AddServiceProvDialog');
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//validation
var $form = $("#addProviderForm");
// Unbind existing validation
$form.unbind();
$form.data("validator", null);
// Check document for changes
$.validator.unobtrusive.parse(document);
// Re add validation with changes
$form.validate($form.data("unobtrusiveValidation").options);
//open dialog
dialogDiv.dialog('open');
return false;
});
});
});
The partial view renders fine but opens a new page and does not come up as a modal dialog.
What am I doing wrong.
On a side note: my autocomplete code is also not working by my jQuery datetime picker is...
$(document).ready(function()
{
$(".date").datepicker();
}
);
$(document).ready(function () {
$("#CustByName").autocomplete(
{
source: function (request, response) {
$.ajax(
{
url: "/Cases/FindByName", type: "GET", dataType: "json",
data: { searchText: request.term, maxResults: 10 },
contentType: "application/json; charset=utf-8",
success: function (data) {
response($.map(data, function (item) {
return {
label: item.CustomerName,
value: item.CustomerName,
id: item.CustomerID
}
})
);
}
});
},
minLength: 3
});
});
My guess is that you misplaced the return false statement in the button's click handler, thus the default behavior is not prevented as you expect, and the link is simply followed:
$(".addServiceProviderLink").click(function () {
...
$.get(viewUrl, function (data) {
dialogDiv.html(data);
...
dialogDiv.dialog('open');
// this return statement should be in the "click" handler,
// not in success callback of the .get() method !
return false;
});
});
Your code should then be:
$(".addServiceProviderLink").click(function () {
...
$.get(viewUrl, function (data) {
...
});
// return here to prevent default click behavior
return false;
});

Resources