Asynchronous call confirmation dialog in event - javascript

I want to return a boolean value from a jQuery confirmation dialog and return that value to an event (to either continue or stop default execution of an event). I know about asynchronous calls but I really can't get around this. This is what I have until now:
function moveConfirmation() {
var defer = $.Deferred();
$('#dialog-move-confirm').dialog({
resizable: false,
width: 400,
height: 200,
autoOpen: true,
modal: true,
buttons: {
'Move Separately': function() {
$(this).dialog('close');
defer.resolve(true);
},
'Move Together': function() {
$(this).dialog('close');
defer.resolve(false);
},
Cancel: function() {
$(this).dialog('close');
defer.resolve(false);
}
}
});
return defer.promise();
}
scheduler.attachEvent('onBeforeEventChanged', function(id, ev) {
// if move contemporaneous exams, alert user to choose if move together or separately
var state = scheduler.getState();
var saveEvent = false;
if (state.drag_mode === 'move') {
moveConfirmation().then(function(move) {
saveEvent = move;
});
}
return saveEvent;
}
What is happening is that saveEvent is still false and returning before the promise. What should I do? I also tried another promise.. but it still comes back to the same thing. Anyone sees a workaround for this?

You must know that the return statement within onBeforeEventChanged will always return false, since moveConfirmation().then(...) is async.
You will probably have to always cancel the onBeforeEventChanged event like you are doing, but rather than simply setting saveEvent = move; within the moveConfirmation handler, you will have to re-trigger the attempted operation programmatically in case the user wanted to proceed (perhaps using updateEvent).
Please also note that you need a mechanism in place to avoid having the re-triggering process to invoke your dialog box again (e.g. if onBeforeEventChanged is fired when calling updateEvent).
EDIT: Note that you can also do the opposite if it looks better on the UI, always accept event changes, but undo them if needed as per the moveConfirmation's response.

Related

How to prevent executing javascript code before data is entered in jquery dialog form

I'm trying to develop reusable function based on a jQuery dialog form, as a replacement for JS prompt. I need user to input data before other JS code is executed (the AJAX request that follows depends on the input of the user).
The function should read one text field and return the value entered if OK button or Return are pressed.
I managed to create the function with callback and it is working, except it doesn't wait for the user to react and the code after the function is executed.
I understand that jQuery calls are asynchronous and tried versions with deferred option, but that didn't work either.
Is there any way to make my code wait for the user input before it continues executing? Of course, the ideal solution would be to use like var userInput = getTxtField(....);
Update:
The function getTxtField is triggered by other user actions (buttons): renameFile, renameFolder, addFile etc.
Update #2 Problem solved
Thanks to #SuperPrograman's suggestion I started thinking with the logic of asynchronous execution. The original code was developed with value = prompt(...) approach and the AJAX code was at the bottom of the single function. I simply took the AJAX code in a separate function and now it works as expected. I've updated the JS code at the bottom.
My code is the following
....
<div class='hidden' id='dialog-newName' title=''>
<label id='label-txtField' for="txtField"></label>
<input type="text" name="txtField" id="txtField" value="" class="text ui-widget-content ui-corner-all">
</div>
....
function getTxtField (title, label, defVal, callBack) {
$('#label-txtField').text(label);
$('#txtField').val(defVal);
$( '#dialog-newName' ).dialog({
modal: true, closeOnEscape: false,
height: 200, width: 500,
title: title,
buttons: {
OK: function() {
callBack('OK', $('#txtField').val());
$(this).dialog( "close" );
},
Cancel: function() {
$('#txtField').val('');
//callBack('Cancel', ''); // not necessary
$(this).dialog( "close" );
}
},
});
}
...
switch (action) {
case 'action1':
// user pressed button for Action1
console.log('before dialog getTxtField ');
getTxtField('Action1', 'Label1', 'defaultValue1', function(buttonP, result) {
console.log(buttonP + ' value=' + result); // prints OK
});
// executed before input finished
console.log('after dialog getTxtField returnVal=' + newName + ')');
break;
case 'action2':
// ....
break;
}
// proceed with AJAX request for selected action
...
//=========================
// working code
//=========================
$('.selector').click ( function() {
var frmId = $(this).closest('form').attr('id');
var action = $(this).attr('ajaxAction');
var form = $('#theForm')[0];
var ajaxData = new FormData(form);
switch action {
case 'actions that do not require function getTxtField':
ajaxData.append(specific data for the action);
ajaxCall (frmId, ajaxData);
break;
case 'actions that with function getTxtField':
getTxtField('Titlexx', 'Labelxx', 'defaultValuexx', function(buttonP, result) {
// process result
ajaxData.append(specific data for the action);
ajaxCall (frmId, ajaxData);
});
break;
}
})
function ajaxCall (id, data) {
// standard ajax code
}
Since my comment helped, I'll add answer for quick access.
Basically you want to format code so everything that comes after dialog runs inside callback directly or is initiated from the callback.
So assuming a simple getTxtField prompt method taking a message and a callback function, instead of:
stuffBeforePrompt();
getTxtField('stuff', function() { });
stuffAfterPrompt();
You'll just need:
stuffBeforePrompt();
getTxtField('stuff', function() {
stuffAfterPrompt();
});
Perhaps you could make some solution using 'threads' or workers where you run prompt on separate thread and sleep main until result (or vice versa); but I doubt that would be worth the slight usage convenience.

stop and later persue javascript event in jquery ui modal dialog

I want to stop an event show a modal dialog and if the user presses yes persue this event. event.run() brings an error in firefox.
jQuery(element).click(function(event) {
event.preventDefault();
dialog.dialog({
buttons: {
'Ja': function() {
event.run();
},
'Nein': function() {
jQuery(this).dialog('close');
}
}
}).dialog('open');
});
Thanks to a friend and hashbrown I managed to solve this problem. An event cannot be paused and persued. If it is paused it will block the whole DOM. Try:
jQuery(link).click(function(){while(true)});
When using jQuery its possible to set additional event parameters what I did:
jQuery(element).click(function(event, show_dialog) {
var that = jQuery(this);
if(!show_dialog) {
dialog.dialog({
buttons: {
'Yes': function() {
that.trigger(event.type, [true]);
},
'No': function() {
jQuery(this).dialog('close');
}
}
}).dialog('open');
return false;
} else {
dialog.dialog('close');
return true;
}
});
First click show_dialog is undefined and modal dialog is shown. Clicking on Yes in modal dialog triggers the event.type (click) with the additional parameter true for show_dialog. http://api.jquery.com/trigger/#trigger-eventType-extraParameters
It was not possible to that.trigger(event, [true]);. I think cause events default action was prevented before.
That is because immediately after creating the popup the function returns and the event expires.
What you'll have to do is .trigger() a new event.
Note: set some sort of global variable to ignore this second event firing in your anonymous function (infinite loop problem).
Can I ask why you want to do this; what would click go off and do if you let it?
If it just fires off a different function, why not just call that function instead of attempting event.run()?

get result for jquery confirmation to return in function

I need to convert from a javascript confirm into utilizing jquery ui confirmation dialog. Problem is, where I need to call and open the confirmation dialog - I need to return a true/false based on what button a user click (OK/Cancel). I know javascript is asynchronous , but I'm stuck how to do this? can anyone point me in the right direction?
$(document).ready(function() {
$('#dialog:ui-dialog').dialog('destroy');
$('#confirm-delete-quote').dialog({
autoOpen: false,
modal: true,
buttons: {
OK: function() {
$(this).dialog('close');
callback(true);
},
Cancel: function() {
$(this).dialog('close');
callback(false);
}
}
});
$('div.multiRowCheckboxMenu').checkboxMenu({
menuItemClick: function(text, count) {
$('#confirm-delete-quote').dialog('open');
// return confirm('Are you sure you want to ' + text + ' the selected ' + count + ' quote(s)?');
// HOW DO I RETURN WHAT THE USER CLICKED IN THE DIALOG HERE?
return callback();
}
});
});
You have started off correctly, except that you cannot expect to have a return value.
The native confirm() is a blocking script. That is to say, the execution thread waits for the user's input. Which is why you can return a value.
However, while using a custom dialog, you need to move the code for whatever you intend to do with the return value into the callbacks for Ok and Cancel.
buttons: {
OK: function() {
$(this).dialog('close');
callback(true);
//You know user clicked true, so do something here itself
},
Cancel: function() {
$(this).dialog('close');
callback(false);
//Similarly here
}

Custom confirm dialog with JavaScript

I would like to create a JavaScript function similar to confirm() that shows a dialog (a div with a question and 2 buttons) and returns true if the user clicks "Ok" or false otherwise.
Is it possible to do that using JavaScript/jQuery but without plugins (e.g. jQuery UI or Dialog)? Because I'm trying to reduce size and round trip times...
I tried to write this code, but I don't know how to make the function "wait" for the user click.
I would like to use my function in this way:
answer=myConfirm("Are you sure?")
In this way I could use the same function in several contexts, simply changing the question passed as a parameter. This is the same behavior of confirm()
Rather than waiting for the user's input and then returning from the function, it is more common in JavaScript to provide a callback function that will be called when the action you're waiting for is complete. For example:
myCustomConfirm("Are you sure?", function (confirmed) {
if (confirmed) {
// Whatever you need to do if they clicked confirm
} else {
// Whatever you need to do if they clicked cancel
}
});
This could be implemented along the lines of:
function myCustomConfirm(message, callback) {
var confirmButton, cancelButton;
// Create user interface, display message, etc.
confirmButton.onclick = function() { callback(true); };
cancelButton.onclick = function() { callback(false); };
}
If using jQuery, why not implement jQueryUI? And use the Dialog function as follows:
as a 2 part:
HTML
<div id="dialog-confirm" title="ALERT">
<p><span class="ui-icon ui-icon-alert" style="float:left; margin:0 7px 20px 0;"></span>Are you sure?</p>
</div>
Script
$( "#dialog-confirm" ).dialog({
resizable: false,
modal: true,
buttons: {
"OK": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
All in Script:
$(function() {
$("<div />").attr("id", "dialog-confirm").append(
$("<p />").text('Are you sure?').css("text-align", "center").prepend(
$("<span />").addClass("ui-icon ui-icon-alert").css({
float: 'left',
margin: '0 7px 20px 0'
})
)
).dialog({
resizable: false,
modal: true,
title: "ALERT",
buttons: {
"OK": function() {
answer=1;
$(this).dialog("close");
},
"Cancel": function() {
answer=0;
$(this).dialog("close");
}
}
});
});
jsFiddle
This really should be done with a callback. The closest thing to what you're after would be to use a publish and subscribe model with some custom events.
To do so:
When a user clicks the yes button, trigger a custom event called clickedYes. Do the same for "no"
$('#yesbtn').click(function(){
$(document).trigger('clickedYes');
});
$('#nobtn').click(function(){
$(document).trigger('clickedNo');
});
Now we need to "listen" or subscribe for those events and execute the appropriate action in context.
Lets create a hypothetical situation: Your user clicks delete and you want to confirm that choice.
First setup what you want to happen if they click yes:
$(document).unbind('clickedYes'); //Unbind any old actions
$(document).bind('clickedYes',function(){
//Code to delete the item
//Hide the popup
});
then what you want to happen if they click no:
$(document).unbind('clickedNo'); //Unbind any old actions
$(document).bind('clickedNo',function(){
//Hide the popup and don't delete
});
So we've setup actions that are listening for clickedYes or clickedNo. Now we just need to show the user the popup so that they have to click yes or no. When they do, they'll trigger the events above.
so your myConfirm() function will just do the following:
function myConfirm(msg){
//change the message to 'msg'
//Show the popup
}
So the order would be:
Bind triggers for the custom events to the yes and no buttons
Before prompting - unbind any old actions and attach your new ones
Present the user with a popup that'll cause them to trigger on of your actions.
This will allow you to call the function like this myConfirm('Are you sure'); It's not quite what you're after...but I don't think it's possible to do exactly what you want.

Change the asynchronous jQuery Dialog to be synchronous?

Currently, I'm working to replace "alert'/"confirm" with the jquery dialog.
But most of legacy codes is written in some asynchronous way, which make it difficult to change. Is there any way to make jquery dialog work in a synchronous way? ( don't use loop or callback function )
For example:
function run()
{
var result = confirm("yes or no");
alert( result );
\\more codes here
}
In this example the alert and other codes will be executed after user's choice.
If we use jquery dialog
var result = $dialog.open()
It will continue to execute the alert, which is asynchronous.
Currently, my solution is to use call back function in the OK|Cancel function.
For example:
OK: function ()
{
$dialog.close();
alert("yes");
//more codes here
}
This method works but it is difficult to make all the synchronous codes become asynchronous, which requires a lot of change (see the following example). So I'm looking for the synchronous jQuery Dialog, is it possible??
For example: ( The real codes are much more complicated than the following example)
function f1()
{
if ( confirm("hello") ) f2();
alert("no");
}
function f2()
{
if( confirm("world") ) f3();
alert("no");
}
function f3()
{
return confirm("!") ;
}
Another example:
vendorObject.on('some-event', function() {
if(confirm("Do you really want to do that?")) {
return true;
}
else {
return false; // cancel the event
}
});
... here the vendor object fires an event, which has to be cancelled if the user confirms. The event can only be cancelled if the event handler returns false - synchronously.
The short answer is no, you won't be able to keep your code synchronous. Here's why:
In order for this to be synchronous, the currently executing script would have to wait for the user to provide input, and then continue.
While there is a currently executing script, the user is unable to interact with the UI. In fact, the UI doesn't even update until after the script is done executing.
If the script can't continue until the user provides input, and the user can't provide input until the script is finished, the closest you'll ever get is a hung browser.
To illustrate this behavior, debug your code and set a break point on the line following a line that changes the UI:
$("body").css("backgroundColor", "red");
var x = 1; // break on this line
Notice that your page background is not yet red. It won't change to red until you resume execution and the script finishes executing. You are also unable to click any links in your page while you've got script execution paused with your debugger.
There is an exception to this rule for alert() and confirm(). These are browser controls, and are treated differently than actual web page UI elements.
The good news is that it really shouldn't be very hard to convert your code. Presumably, your code currently looks something like this:
if (confirm("continue?")) {
// several lines of code if yes
}
else {
// several lines of code if no
}
// several lines of code finally
Your asynchronous version could create a function ifConfirm(text, yesFn, noFn, finallyFn) and your code would look very much the same:
ifConfirm("continue?", function () {
// several lines of code if yes
},
function () {
// several lines of code if no
},
function () {
// several lines of code finally
});
Edit: In response to the additional example you added to your question, unfortunately that code will need to be refactored. It is simply not possible to have synchronous custom confirmation dialogs. To use a custom confirmation dialog in the scenario where an event needs to either continue or cancel, you'll just have to always cancel the event and mimic the event in the yesFn callback.
For example, a link:
$("a[href]").click(function (e) {
e.preventDefault();
var link = this.href;
ifConfirm("Are you sure you want to leave this awesome page?", function () {
location.href = link;
});
});
Or, a form:
$("form").submit(function (e) {
e.preventDefault();
var form = this;
ifConfirm("Are you sure you're ready to submit this form?", function () {
form.submit();
});
});
I'm not exactly sure what the motivation behind not using callbacks is so it is hard to judge what solution might satisfy your requirements, but another way to delay execution is through jQuery's "deferred" object.
http://api.jquery.com/category/deferred-object/
You could set up a function that opens the jquery dialog and add code that "waits" for dialog to close. This ends up working in a fairly similar way to a callback in the case you've laid out but here is an example:
function confirm () {
var defer = $.Deferred();
$('<div>Do you want to continue?</div>').dialog({
autoOpen: true,
close: function () {
$(this).dialog('destroy');
},
position: ['left', 'top'],
title: 'Continue?',
buttons: {
"Yes": function() {
defer.resolve("yes"); //on Yes click, end deferred state successfully with yes value
$( this ).dialog( "close" );
},
"No": function() {
defer.resolve("no"); //on No click end deferred successfully with no value
$( this ).dialog( "close" );
}
}
});
return defer.promise(); //important to return the deferred promise
}
$(document).ready(function () {
$('#prod_btn').click(function () {
confirm().then(function (answer) {//then will run if Yes or No is clicked
alert('run all my code on ' + answer);
});
});
});
Here it is working in jsFiddle: http://jsfiddle.net/FJMuJ/
No, you can't do anything sync in Javascript (alert is breaking the rules, in fact). Javascript is built with "single threaded, async" in the core.
What you can do, though, is disable functionality of the underlying page (lightbox-like) so no event get triggered from the page until you don't take the dialog action, be it OK or Cancel. Thought this does not help you to get your sync code working. You have to rewrite.
Here's some ideas - what you actually want is to block your async event to make it look like sync. Here's some links:
Queuing async calls
Mobl
Narrative JavaScript
Hope this helps you further!!
To answer David Whiteman's more specific question, here's how I'm implementing a "deferred" postback for a LinkButton Click event. Basically, I'm just preventing the default behaviour and firing the postback manually when user feedback is available.
function MyClientClickHandler(event, confirmationMessage, yesText, noText) {
// My LinkButtons are created dynamically, so I compute the caller's ID
var elementName = event.srcElement.id.replace(/_/g, '$');
// I don't want the event to be fired immediately because I want to add a parameter based on user's input
event.preventDefault();
$('<p>' + confirmationMessage + '</p>').dialog({
buttons: [
{
text: yesText,
click: function () {
$(this).dialog("close");
// Now I'm ready to fire the postback
__doPostBack(elementName, 'Y');
}
},
{
text: noText,
click: function () {
$(this).dialog("close");
// In my case, I need a postback when the user presses "no" as well
__doPostBack(elementName, 'N');
}
}
]
});
}
You can use a real modal dialog.
[dialog] is an element for a popup box in a web page, including a modal option which will make the rest of the page inert during use. This could be useful to block a user's interaction until they give you a response, or to confirm an action.
https://github.com/GoogleChrome/dialog-polyfill
I don't really see why you are opposed to using Jquery callbacks to achieve the behavior in your example. You will definitely have to rewrite some code but something like:
function f1() {
$( "#testdiv" ).dialog({
modal: true,
buttons: {
"OK": function() {
$( this ).dialog( "close" );
f2();
},
Cancel: function() {
$( this ).dialog( "close" );
alert('no');
}
}
});
}
function f2() {
$( "#testdiv2" ).dialog({
modal: true,
buttons: {
"OK": function() {
$( this ).dialog( "close" );
f3();
},
Cancel: function() {
$( this ).dialog( "close" );
alert('no');
}
}
});
}
function f3() {
$( "#testdiv3" ).dialog({
modal: true,
buttons: {
"OK": function() {
$( this ).dialog( "close" );
},
Cancel: function() {
$( this ).dialog( "close" );
}
}
});
}
<div id="testdiv" title="Hello"/>
<div id="testdiv2" title="World"/>
<div id="testdiv3" title="!"/>

Categories