jQuery Modal that can be Queued - javascript

At the moment, I have a simple app that Ajax's to a server, gets some JSON and then does something with it. I'd like to add in messages to show loading images and other info, but I'm struggling with simplemodal at the moment because it doesn't queue modals, so it just fires everything as soon as it comes in. I've tried writing a queue for it, didn't work out so well :)
The app should:
Send ajax request (show modal, stop user clicking anything)
Ajax complete (hide modal, allow clicking)
If [for example] return JSON object has "message" set ( if (strJson.message)) { } ) show message as modal
Allow user to close modal
While they were reading the message, if another ajax call has come and gone, and we have more modals to show, they should be queued to show when the current one is closed.
This seems like the kind of thing that should be out there but I can't see anything that mentions it specifically.
Any ideas? :)

You can take the messages and put them into an array, then when the dialog is closed you can check to see if there is more messages, if there is pull the next message from the array and display it. Here it an example using jQuery UI Dialog.
HTML
<div id="dialog"></div>
JavaScript
var messages = [],
addMessage = function (msg) {
messages.push(msg);
if (!$('#dialog').dialog("isOpen")) {
displayMessage();
}
},
displayMessage = function () {
$('#dialog').html(messages.shift()).dialog('open');
};
$(function () {
$('#dialog').dialog({
autoOpen: false,
modal: true,
close: function () {
if (messages.length > 0) {
displayMessage();
}
}
});
addMessage('First Message');
addMessage('Second Message');
});

Related

How do I show a pop up only once?

my pop up seems to show to my website visitors even if they've hidden the pop up or subscribed previously.
How can I change the following code to only show the pop up once?
setTimeout(function(){
var newsletterModal = $('#newsletterModal');
if (newsletterModal.length && typeof $.cookie('newsletter_modal') === 'undefined') {
if ($.cookie('age_verified') || !$('#verifyAgeModal').length) {
newsletterModal.foundation('open');
$.cookie('newsletter_modal', true, { path: '/' });
}
else {
verifyAgeModal.on('closed.zf.reveal', function() {
newsletterModal.foundation('open');
$.cookie('newsletter_modal', true, { path: '/' });
});
}
}
}, 20000);
I don't use the age verification facility, but I haven't tried removing it in case I opt to include age verification later on.
As a separate question, is there a way to distinguish between those who have hidden the pop up and those who have subscribed (with the aim of re-showing the pop up to non-subscribers a month or so later)?
I can do it by combining with ajax which will save the status of the dialog box in the database. On click of close button, perform ajax request to save view status as 1 or done. In the next loading check view status before displaying the modal.
How to identify the user who viewed the dialog box - save unique identifier in the cookie which will be used for as identifying browser log events.

Jquery - For each wait show modal

I'm testing to create a each loop with an array object. I would like to every element show a modal window with a data and with a question. After response the question the modal hide and show with other array element.
I have read a lot of information and the each loop cann't wait response¿?
Modal:
This interface use to ask user to replace an image.
I'm working in this code:
$.each( arrayExist, function( i, value ) {
if (value == 1) { // Show modal with the old and new image when value is true
alert ('Exist');
$('#overwriteImages').modal('show');
$('#overwriteImages').on('show.bs.modal', function (event) {
$('input[type="submit"]').click(function(event){
$('#btnYes').on('click', function() {
$('#overwriteImages').modal('hide');
});
$('#btnNo').on('click', function() {
$('#overwriteImages').modal('hide');
arrayCod.splice( $.inArray(removeItem,i) ,1 );
alert(arrayCod.length);
});
});
});
}else{
alert ('Not Exist');
}
});
I'm not sure that is possible to do it or it would be a better option... ajax or whatever.
The problem is that the each loop is execute in each modal window. It doesn't wait to response Yes or No. Example:
Select two elements.
Element(1) -> Show Modal and two alerts because the each loop running at two times)
Element(2) -> Show Modal and two alerts because the each loop running at two times)
The correct behaviur would be:
Select two elements.
Element(1) -> Show Modal and an alert only with this element.
Element(2) -> Show Modal and an alert only with this element.
The summary is: I need that the each loop wait to response in modal window to be continue the loop.
Don't use a loop here. Of course, the each function won't wait to return from a "modal" window, because your window isn't modal actually (only alert, prompt and comfirm are authentic modals). Everything goes through events, so declare a variable that holds de index of the element you want to show now, and increment and decrement it as the user clicks "nueva" or "anterior" recovering the element from the array and operating with it.

how to put dialog box inside the page refresh?

i want to put this dialog box inside the page refresh. i mean. when i refresh the page this must be the out put.
<script>
$(function() {
$("#dialog").dialog({
modal: true,
resizable: false,
buttons: {
"I want to Continue the Exam": function() {
$(this).dialog("close");
},
"I Refresh": function() {
$(this).dialog("close");
}
}
});
});
</script>
As far as I know, when you 'refresh' a page then all the JS objects are destroyed (those that are written in script).In other words the script is re-loaded. So you can't persist your script while the page is in transition.
Type I (classical Single Page App)-
So if you simply want to reload a particular part of the Application then use $.ajax() methods like beforeSend() for showing whatever (alert or best a loading spinner/div) you want during the data request or 'page-refresh'. And then you can hide them on done().
Type II (using routers)
JS frameworks like Angular give you options to reload a particular route of your App without reloading/refreshing your entire app - $route.reload(). You can show/hide some div/directive based on manipulation in your controller.
So you have to use some form of asynchronous scripting to deal with this "PROMPT while REFRESH" situation.
Using $.ajax() to simulate (pseudo code)-
$.ajax({
url: "_URL_to_get_or_post_data__",
beforeSend: function( xhr ) {
$popup.show();
}
})
.done(function( data ) {
$popup.hide();
}
});
Browsers have a security feature that will not let a page prevent users from leaving the page. By leaving a page it means closing tab/browser, navigating to a different page or refreshing. The only way to stop the user is to assign a function to onbeforeunload. Like this:
onbeforeunload = function () { return "You have unsaved data. Are you sure you want to exit?"; }
This message is synchronous, it will stop all javascript running on the page. If user presses ok the browser will leave the page (or refresh) else it will stay on the page.
EDIT
Usage: when user have changed something and have unsaved data - you assign a function to onbeforeunload:
onbeforeunload = function () { return "some message"; }
after the data is saved set onbeforeunload to null:
onbeforeunload = null;

Get event after function complete

I have a form where people can delete records;
Delete Record 1
Delete Record 2
Delete Record 3
To ensure they are sure, I am using a "Are you sure" confirmation script (Popconfirm) which gives a nice little popup confirmation.
$(".confirm-action").popConfirm();
If the user clicks cancel, nothing happens. If they click 'yes' - the link is processed and the record deleted. This is working as intended.
Now instead of following the link (when the user clicks 'yes'), I want to fire an ajax request:
$('.confirm-action').click(function(event) {
event.preventDefault();
$.ajax({
// Ajax stuff here
});
});
$(".confirm-action").popConfirm();
The problem is when I try this, the functions are fired in the correct order when expected, except the event is null, so the script fails.
How do I "preventDefault()" when the event is null, and/or manually get the event to prevent the link from being followed by the browser?
Edit: JSFiddle showing the problem.
As noted in the comments, the plugin is horrible and plays with _data(events) IE plays with internal event management of jQuery.
If you aren't concerned about the UI, I would suggest you to go with normal confirm() as used in SO.
I've created this for you while typing this answer:
$.fn.nativeConfirm = function (options) {
return this.click(function () {
var bool = confirm(options.text);
bool ? options.yes.call(this) : options.no.call(this);
});
}
Example:
$('a').nativeConfirm({
yes: function(){
alert('yes');
},
no:function(){
alert('no');
},
text: 'Seriously?'
});

jQuery getJSON doesn't have enough time to execute before dialog close

I am using jQuery's UI Dialog to draw a dialog (my-ui-dialog) to the screen and present the user with some <input>s and other controls. When the user clicks the dialog's OK button, I want the UI dialog to fire an AJAX/JSON message to my server (via getJSON), allow the server to process that call, and then close the dialog after the response is received from the server. Then the user should be redirected (via window.location) to another web page.
Here's my code:
$("#my-ui-dialog").dialog({
modal: true,
autoOpen: false,
height: 255,
width: 300,
buttons: {
"OK" : function() {
var f = $("#fizz").val();
$.getJSON(
"/myserver/do-something",
{
fizz: f
},
function() {
$("#my-ui-dialog").dialog('destroy');
}
);
// When I leave this in the code works great.
// When I comment the alert out, the getJSON call never
// hits the server-side.
alert("Returned from the backend...");
window.location = "/myserver/some-other-url"
$(this).dialog("close");
},
Cancel : function() {
$(this).dialog("close");
}
}
});
When I leave that alert box in, and wait a few seconds (with the alertbox drawn to screen), the getJSON method seems to have enough time to hit the server and return. But if I comment out the alert the request never even hits my server. I can tell this by adding a log message to the beginning of the handler listening at /myserver/do-something. This is also a Java web app and I don't see any evidence of Tomcat receiving the request, and I don't see the HTTP request being generated when using Firebug to debug. All 3 of these indicate that the request is simply not hitting the server at all.
What are my options here? Can I make the jQuery sleep for a few seconds? That feels like an ugly solution; there must be a better way to use the jQuery API... thanks in advance!
Put your dialog close and window.location code in the getJSON callback. That's why there's a callback.

Categories