How can I implement a wait mechanism until receiving confirm dialog response? - javascript

Here is my code:
$(function () {
$(document).on('click', '.fa-times', function(e){
e.stopPropagation();
var result = ConfirmDialog('Are you sure?');
if (result) {return false}
var row = $(this).closest('tr');
row.css('opacity','0.3');
var word = $(this).closest('td').siblings('.word').text();
$.ajax({
url : '../../te_addStopWord',
type : 'GET',
data: {word : word},
dataType : 'JSON',
success : function () {
row.remove();
}, // success
error : function ($a,$b,$c) {
alert($b);
row.css('opacity','1');
}
}); // ajax
})
function ConfirmDialog(message) {
$('<div></div>').appendTo('body')
.html('<div><h6>'+message+'?</h6></div>')
.dialog({
modal: true, title: 'Delete message', zIndex: 10000, autoOpen: true,
width: 'auto', resizable: false,
buttons: {
Yes: function () {
$(this).remove();
return true;
},
No: function () {
$(this).remove();
return false;
}
},
close: function (event, ui) {
$(this).remove();
}
});
};
})
But my code run that ajax request without waiting for the response of ConfirmDialog(message) function. How can I force it to wait?

You have 2 functions which get triggered depending on which confirm button is selected. Handle your ajax code from there.
I liked how Abhijit's answer abstracted out the code, but I think he missed something.
$(function() {
$(document).on('click', '.fa-times', function(e) {
e.stopPropagation();
function getConfirmHandler(element){
return function handleConfirm(result) {
if (result) {
return false
}
var row = element.closest('tr');
row.css('opacity', '0.3');
var word = element.closest('td').siblings('.word').text();
$.ajax({
url: '../../te_addStopWord',
type: 'GET',
data: {
word: word
},
dataType: 'JSON',
success: function() {
row.remove();
}, // success
error: function($a, $b, $c) {
alert($b);
row.css('opacity', '1');
}
}); // ajax
}
}
ConfirmDialog('Are you sure?', getConfirmHandler($(this)))
});
function ConfirmDialog(message, callback) {
$('<div></div>').appendTo('body')
.html('<div><h6>' + message + '?</h6></div>')
.dialog({
modal: true,
title: 'Delete message',
zIndex: 10000,
autoOpen: true,
width: 'auto',
resizable: false,
buttons: {
Yes: function() {
$(this).remove();
callback(true);
},
No: function() {
$(this).remove();
callback(false);
}
},
close: function(event, ui) {
$(this).remove();
}
});
};
})

Try move ajax into your ConfirmDialog:yesfunction. Or Try to use promise.
buttons: {
Yes: function () {
var row = $(this).closest('tr');
row.css('opacity','0.3');
var word = $(this).closest('td').siblings('.word').text();
$.ajax({
url : '../../te_addStopWord',
type : 'GET',
data: {word : word},
dataType : 'JSON',
success : function () {
row.remove();
}, // success
error : function ($a,$b,$c) {
alert($b);
row.css('opacity','1');
}
}); // ajax
$(this).remove();
return true;
},
No: function () {
$(this).remove();
return false;
}
},

Related

Delay jquery ui dialog close until after callback is finished

I am calling up a confirm box using jQuery UI Dialog like so:
function tps_show_confirm(cTitle, cContent, noClose = true, dwidth = 300, callback=null) {
if (noClose == true) {
var dClass = 'no-close';
} else {
var dClass = '';
}
var confirmDiv = '<div class="tps-confirm-modal">'+cContent+'</div>';
var maxHeight = window.innerHeight * .80;
$( confirmDiv ).dialog({
title: cTitle,
dialogClass: dClass,
modal: true,
width: dwidth,
maxHeight: maxHeight,
draggable: false,
resizable: false,
create: function(event, ui) {
$('body').css({ overflow: 'hidden' })
},
beforeClose: function(event, ui) {
$('body').css({ overflow: 'inherit' })
},
buttons: {
Ok: function() {
if (typeof callback === 'function') {
callback();
}
$( this ).dialog('close');
},
Cancel: function() {
$(this).dialog('close');
}
}
});
}
I am trying to figure out how to delay the .dialog('close') action when the OK button is clicked until the callback() function is finished. I've tried various combinations of .done() an/or .finish() and .when() but I don't quite understand those and they don't seem to be for this case.
Any ideas how to achieve this?
Hopefully jquery.when will be useful
Ok: function() {
if (typeof callback === 'function') {
$.when(callback()).then(function() {
$(this).dialog('close');
}.bind(this));
}else{
$( this ).dialog('close');
}
}
This snippet can be useful. I am passing a callback back function.Inside a callback function there is an asynchronous call.Now when you will click on ok button the callback function will start executing but the dialog will be closed only when there is a response from async operation
function tps_show_confirm(callback = null) {
var confirmDiv = '<div class="tps-confirm-modal">Hello Test</div>';
var maxHeight = window.innerHeight * .80;
$(confirmDiv).dialog({
title: 'test',
dialogClass: 'dClass',
modal: true,
width: 300,
maxHeight: 300,
draggable: false,
resizable: false,
create: function(event, ui) {
$('body').css({
overflow: 'hidden'
})
},
beforeClose: function(event, ui) {
$('body').css({
overflow: 'inherit'
})
},
buttons: {
Ok: function() {
if (typeof callback === 'function') {
$.when(callback()).then(function(data) {
console.log(data)
$(this).dialog('close');
}.bind(this));
} else {
$(this).dialog('close');
}
},
Cancel: function() {
$(this).dialog('close');
}
}
});
}
function test() {
var root = 'https://jsonplaceholder.typicode.com';
return $.ajax({
url: root + '/posts/1',
method: 'GET'
}).then(function(data) {
return data;
});
}
tps_show_confirm(test)
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css">
<script src="//code.jquery.com/jquery-1.12.4.js"></script>
<script src="//code.jquery.com/ui/1.12.1/jquery-ui.js"></script>

JQuery UI Dialog and duplicated form elements

I am using a JQuery UI Dialog and the ajax submit plugin from malsup.com.
The issue is that the UI Dialog (I believe that is the culprit) is duplicating the fields of the form. It would not be such an issue except that this form is for uploading multiple files. The form uses a DataTable.
Apart from the duplicating fields the process is fine.
I am not re-using the dialog, which would duplicate the fields (see this )
The page gets the form and submits it through ajax: here is the code:
function smxTableDialogForm ( aURL, tableId, row ) {
var lData = "";
var lURL = aURL.split("?");
var lDialog;
if (lURL.length == 2){
lData = lURL[1];
lURL = lURL[0]
};
$.ajax({
type: "POST",
url: lURL,
data: lData,
dataType: "json"
}).
done( function(response){
if ( response.success ){
lDialog = $("<div></div>").dialog( {
height: "auto",
maxHeight: 800,
width: 750,
autoOpen: false,
buttons: [
{ text: "Save",
icons: {primary: "ui-icon-check" },
click: function () {
smxAjaxSubmit(response.formid);
$(this).dialog("close");
}
},
{ text: "Cancel",
icons: {primary: "ui-icon-close"},
click: function() {
$(this).dialog("close");
}
}],
close: function (event, ui) {
$(this).remove();
},
resizable: false,
modal: true
});
lDialog.html(response.content);
lDialog.dialog("open");
}
else {
$.alert(response.message, response.title);
};
}).
fail( function(jqXHR, textStatus, errorThrown) {
$.alert("Sorry, no info to display.", "oops");
});
};
function smxAjaxSubmit (aFormId) {
$("#" + aFormId).ajaxSubmit({
dataType: "json",
beforeSend: function(){
$.blockUI({ message: '<h3><img src="/sysimages/ajaxloader.gif" /> Just a moment...</hr>' });
},
complete: function(){
$.unblockUI();
},
success: function(response) {
alert(response);
},
error: function(jqXHR, textStatus, errorThrown) {
$.alert("Problem. status: " + textStatus + "; error: " + errorThrown, "oops");
}
});
};
Any ideas gratefully received. Thanks.

Bootstrap Popover with Ajax call not showing data

I can't seem to update the popovers contents with Ajax result.
ASP.Net (MVC4):
public ActionResult GetEmployeeDetails(string employeeId)
{
var contract = UnitOfWork.ContractRepository.ContractBusinessManager.GetContract(int.Parse(employeeId), DateTime.Now);
return PartialView("_EmployeeDetails", contract);
}
Html:
<a data-toggle-popup-employee-id="#evaluation.EmployeeId" >#evaluation.Employee.FullName.ToTitle()</a>
Javascript:
$(document).ready(function () {
$('[data-toggle-popup-employee-id]').popover(
{
html: true,
placement: 'top',
title: 'Title',
container: 'body',
content: function () {
//$(this).off('hover');
var employeeId = $(this).data('toggle-popup-employee-id');
$.ajax({
async: false,
url: '#Url.Action("GetEmployeeDetails", "Evaluation")',
data: { employeeId: employeeId },
success: function (result) {
return result;
//var html = result;
//$(this).contents.html = result;
},
error: function (xhr) {
alert(xhr.responseText);
}
})
},
trigger: 'hover'
});
});
The call works fine and gives back the partial result as html but the popovers content is still empty...
UPDATE:
It appears that every time I hover over the link, 10 [Object, HTMLAnchorElement]
are added directly to the $('[data-toggle-popup-employee-id]').
Each object has InnerText and InnerHtml set to the employees name...?
I'd personally do something like the following...
$(document).ready(function () {
$('[data-toggle-popup-employee-id]').on({
mouseenter: function () {
var originator = $(this);
var employeeId = originator.data('toggle-popup-employee-id');
$.get('#Url.Action("GetEmployeeDetails", "Evaluation")', { employeeId: employeeId }, function (data) {
originator.popover({
html: true,
placement: 'top',
title: 'Title',
container: 'body',
content: data,
}).popover('show');
})
},
mouseleave: function () {
//
// Destroy so the data will referesh
//
$(this).popover('destroy');
}
});
});
This way we are initialising the popover in the callback of the ajax request.
Hope this makes sense.
$('.popover.in .popover-inner').html(data);

Delete record animation isn't working with dialog-confirm

Okay, what I have here is a Ajax delete record. I've tried to add jquery dialog-confirm instead of using javascript confirm. The delete function works but the problem is the animation of deleting row was not working.
Here's what I have right now. http://jsfiddle.net/altaire/YJC44/
Any help will appreciate. Thanks!
Php
while($row = $result->fetch_assoc()){
echo'<tr class="records">';
echo'<td>'.$i++.'</td>
<td align="center"><img src="images/del.png" border="0" width="10" height="10" title="Delete"></td>
<tr>;
Jquery/Ajax
$(".delbuttons").click(function () {
//e.preventDefault();
var element = $(this);
var del_id = element.attr("name");
var info = 'prdelete=' + del_id;
$("#dialog").dialog({
buttons: {
"Confirm": function () {
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function () {}
});
$(this).parents(".records").animate({
backgroundColor: "#fbc7c7"
}, "fast")
.animate({
opacity: "hide"
}, "slow", function () {
setTimeout(function () {
window.location.reload();
}, 1000);
});
$(this).dialog("close");
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$("#dialog").dialog("open");
});
You have to add a js as "//code.jquery.com/ui/1.11.0/jquery-ui.js". see below demo.
<html>
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"> </script>
<script src="//code.jquery.com/ui/1.11.0/jquery-ui.js"></script>
<script>
$(document).ready(function(){
$( "#effect" ).animate({backgroundColor: "#aa0000",color: "#fff",width: 500},5000);
});
</script>
</head>
<body>
<div id="effect"style="border:1px solid red;height:100px;width:100px;position:absolute;">
</div>
</body>
</html>
Try this
$('a[name="'+del_id+'"]').parents(".records")...
instead of $(this).parents(".records")...
You are trying to animate the $("#dialog") if you use $(this).
DEMO : http://jsfiddle.net/yeyene/YJC44/1/
$(".delbuttons").click(function () {
//e.preventDefault();
var element = $(this);
var del_id = element.attr("name");
//alert(del_id);
var info = 'prdelete=' + del_id;
$("#dialog").dialog({
buttons: {
"Confirm": function () {
$.ajax({
type: "GET",
url: "delete.php",
data: info,
success: function () {
// $(this).parents(".records")
$('a[name="'+del_id+'"]').parents(".records")
.css({'background': '#fbc7c7'})
.animate({
opacity: 0
}, 1000, function () {
setTimeout(function () {
window.location.reload();
}, 1000);
});
$(this).dialog("close");
}
});
},
"Cancel": function () {
$(this).dialog("close");
}
}
});
$("#dialog").dialog("open");
});

Why does the Jquery dialog keep crashing on $(this)?

I am having a hell of a time trying to figure out why the code below crashes when the dialog is closed or cancelled. It errors on lines that use ($this) in the dialog button function.
For some reason if I hard code values into addTaskDialog.html(AddTaskForm); it works. I have even hardcoded the returned ajax form and it worked... This problem happens in all browsers.
$(function ()
{
/*
* Initializes AddTask Dialog (only needs to be done once!)
*/
var $dialog = $('<div></div>').dialog(
{
width: 580,
height: 410,
resizable: false,
modal: true,
autoOpen: false,
title: 'Basic Dialog',
buttons:
{
Cancel: function ()
{
$dialog.dialog('close');
},
'Create Task': function ()
{
}
},
close: function ()
{
$dialog.dialog('close');
}
});
/*
* Click handler for dialog
*/
$('#AddTask').click(function ()
{
/* Ajax request to load form into it */
$.ajax({
type: 'Get',
url: '/Planner/Planner/LoadAddTaskForm',
dataType: 'html',
success: function (AddTaskForm)
{
$dialog.html(AddTaskForm);
$dialog.dialog('open');
}
});
});
});
});
Ok I think I know what is going on. On your success callback you are referencing $(this) in AddTaskDialogOptions the problem is that the in this scope $(this) no longer refers to $("#AddTask") so you will need to set a variable to keep a reference to $(this) like so:
var that;
$('#AddTask').click(function ()
{
that = $(this);
/* Ajax request to load form into it */
$.ajax({
type: 'Get',
url: '/Planner/Planner/LoadAddTaskForm',
dataType: 'html',
success: function (AddTaskForm)
{
var addTaskDialog = $('<div></div>');
addTaskDialog.dialog(AddTaskDialogOptions);
addTaskDialog.html(AddTaskForm);
addTaskDialog.dialog('open');
}
});
});
var AddTaskDialogOptions = {
width: 580,
height: 410,
resizable: false,
modal: true,
autoOpen: false,
title: 'Basic Dialog',
buttons:
{
Cancel: function ()
{
that.dialog('close');
},
'Create Task': function ()
{
}
},
close: function ()
{
that.dialog('destroy').remove();
}
}
I figured it out. I'm not sure where I got this code, but it was causing the problems, so I took it out and it all works fine.
close: function ()
{
$dialog.dialog('close');
}

Categories

Resources