Not able to open the Jquery Modal Dialog Again and again - jquery-ui

I have a hyper link at the footer of the page which open a form in the jquery Dialog we call it as M1.Than i enter all the information and click on "create " which creates a user. while creating a new user i show small modal( "we call it as M2") saying " Please wait ..some message"
Now my problem is iam not able to display the ("M2")modal saying " Please wait ..some message" while i keeep on creating a new user everytime when i stay on("M1").
first time it is coming ("M1") and next time it doesnot display again .How ever when closing iam destroying and removing the dialog. (It is due to other issue)
here is Code.
<div id="m2" style="visibility:hidden">
<img src="spinningwheel" border="0" align="middle" hspace="20" vspace="5"/> Creating USER...
</div>
$(document).ready(function() {
displaydialog();
});
function displaydialog(){
$('#m2').dialog({
autoOpen: false,
height: 100,
width: 250,
modal: true,
close: function() {
$(this).dialog('destroy');
$(this).remove();
}
});
}
$("#btncreate").click(function (){
$("#m2").removeAttr('style');
displaydialog();
$("#m2").dialog('open');
//get a json request based on data if suceess
if(success){
$("#m2").dialog('close');
}else{
$("#m2").dialog('close');
}
});

#Derby,
$(document).ready(function() {
displaydialog();
});
function displaydialog(){
$('#m2').dialog({
autoOpen: false,
height: 100,
width: 250,
modal: true,
/* close: function() { // No need to Destroy the dialog
$(this).dialog('destroy');
$(this).remove();
}*/
});
}
$("#btncreate").click(function (){
// $("#m2").removeAttr('style');
// displaydialog();
$("#m2").dialog('open');
//get a json request based on data if suceess
// if you are using ajax post, try to close this box as part of response handler ( success/error).
jQuery.ajax({
data : {somekey : somevalue},
datatype: 'json',
error : function(jqXHR, textStatus, errorThrown) {
$("#m2").dialog('close');
},
success : function(data, textStatus, jqXHR) {
$("#m2").dialog('close');
},
type : 'GET',
url : 'dummyURL'
});
/* if(success){
$("#m2").dialog('close');
}else{
$("#m2").dialog('close');
} */
});
You don't have to destroy and create M2 dialog everytime. just call displaydialog() once on document ready, and then just use open and close on the dialog. You are not seeing the dialog because, dialog(close) would be called just after calling your ajax get request ( in case you are using async : true). So, close M2 dialog on success/error from the ajax request.

If you re using ajax to retrieve the new data, the browser will renderize the web again (not loading, renderize it) so you wont have anymore the dom ready. Try to call displaydialog and then open it. It will work. Anyway, there's a better way to do that, i think your problem is logic. But that solution will work.

Related

Kendo Date Picker failing in MS Edge Browser

I have created this partial view as a pop-up to enable the user to edit the date and save. Kendo date picker fails on Edge browser. All the date fields turn blank when opened in this particular browser(when date picker already has a date assigned to it).Works fine in all the other browsers like Chrome, Mozilla and IE. Kendo UI version is v2013.3.1119.
Can you please suggest any fix?
<script type="text/javascript">
// This method opens the popup window.
function EditMiscDates() {
$('#edit-dca-misc-dates-div').kendoWindow({
width: "1100px",
title: "Milestone Dates",
actions: ["Close"],
draggable: false,
modal: true,
resizable: false,
activate: function () {
// set focus to the first control
$("#mcd-code-check-scheduled").focus();
}
});
// Center the window and open it
$('#edit-dca-misc-dates-div').data("kendoWindow").center();
$('#edit-dca-misc-dates-div').data("kendoWindow").open();
}
function OnMiscDatesSuccess(data) {
//console.log('OnMiscDatesSuccess called.');
// If the service returned with an error message, show the message to the user
if (!data.IsValid) {
console.log("Error (" + data.Messages + ")");
// Allow the user to retry
EnableMiscDatesClose(true); // let them close the window
$("#error-text-misc-dates").html("An error occurred: " + data.Messages);
$("#error-text-misc-dates").show();
return;
}
// The method successfully executed so we can close the popup window and reload the main page.
CloseMiscDatesPopup();
// Redirect back to the Index page to reload the data
window.location = '#Url.Action("Index", "Dca", new { id = Model.OrderId })';
}
// This method allows us to enable or disable the close button on the main window
function EnableMiscDatesClose(enable) {
$('#edit-dca-misc-dates-div').parent().find(".k-window-action").css("visibility", (enable ? "" : "hidden"));
}
// Handle the user clicking the cancel button
function CloseMiscDatesPopup() {
EnableMiscDatesClose(true);
$("#error-text-misc-dates").hide(); // Hide error message (if exists)
$('#edit-dca-misc-dates-div').data('kendoWindow').close();
}
function GetMiscDatesJson() {
// Note: Something prepends "step_" to the front of every id (with the odd exception of the Kendo controls). So I have to
// manually make the ajax call to submit the form (or it can't match the field names with the model parameters)
var orderId = $("#step_mcd-order-id").val();
var mcdCodeCheckScheduled = $("#mcd-code-check-scheduled").data("kendoDatePicker").value();
mcdCodeCheckScheduled = kendo.toString(mcdCodeCheckScheduled, "MM/dd/yyyy");
var o = {
OrderId: orderId,
CodeCheckScheduled: mcdCodeCheckScheduled
};
return o;
}
// This method validates the data entered by the user.
// If it is invalid, it shows a detailed error message; otherwise it submits the form via ajax
function ValidateAndSubmitMiscDates() {
var d = GetMiscDatesJson();
var s = JSON.stringify(d);
console.log(s);
// Submit the form via ajax
$.ajax({
type: 'POST',
url: '#Url.Action("SaveConversionMiscDates", "Dca")',
dataType: 'json',
data: s,
contentType: 'application/json; charset=utf-8',
success: function (data) {
console.log('success!');
OnMiscDatesSuccess(data);
},
error: function (xhr, status, error) {
console.log('error!');
EnableMiscDatesClose(true); // let them close the window
$("#error-text-misc-dates").html("An error occurred: " + error);
$("#error-text-misc-dates").show();
}
});
}
</script>
<div id='edit-dca-misc-dates-div' style='display:none'>
<div class="k-block k-error-colored" id="error-text-misc-dates" style="display: none"></div>
<div class="mcd-label">Scheduled</div>
#Html.Kendo().DatePicker().Name("mcd-code-check-scheduled").Value(Model.CodeCheckScheduled)
</div>
<div style="padding-top:6px;text-align:right">
<button class="k-button" onclick="ValidateAndSubmitMiscDates()">Save</button>
Cancel
</div>
Fixed in the latest build: 2015.2.902.545

jQuery draggable does not work on elements added via ajax call

I have a list of objects that I am up updating through a dialog. When the user clicks the refresh button it reloads the updated list and appends the same table with the list. However, when I reload the updated list, the draggable function for jQuery UI stops working. I have tried inserting a the $('draggable').draggable line inside the ajax success handler and after the ajax call occurs, and neither worked. I also have a jquyer live event handler for the draggable containers that did not work for when the list was refreshed.
Below is my code for initially loading the list, the live function for draggable containers and the function for when the user clicks the refresh button. In my code below I also tried to add the ui-draggable class to the objects and that did not work:
$.ajax({
async: false,
type: 'POST',
url: 'collection.php',
success: function(data) {
$("#collection").append(data);
}
});
$("#refresh_collection").click(function(){
$("#collection").html("");
$.ajax({
async: false,
type: 'POST',
url: 'collection.php',
success: function(data) {
$("#collection").append(data);
$('.draggable_container:not(.ui-draggable)').live("mouseover", function(){
$(".draggable_container").addClass("ui-draggable");
});
}
});
});
$('.draggable_container').live('mouseover',function(){
$(this).draggable({
cursor: "move",
cursorAt: { top: -5, left: -5 },
stop: function(){}
})
});
I was able to get the draggables to work using the on function rather than live, but now I realized that they do not work after I open a jquery UI dialog, close it and then click the refresh button. If I just click the refresh button without opening the dialog first, then everything works fine. However, the draggable turns off if I open the dialog, close it and then click the refresh button, but it does work if I just open the dialog and close it without pressing the refresh button. Any ideas on how to fix this? Will destroying the draggable and then reinitializing it when I close the dialog sound like the solution?
I ultimately want to have the ajax call happen when the dialog closes like this, but this code still was not working. Any help would be greatly appreaciated.
var $dialog = $("#upload_dialog").dialog({
autoOpen: false,
height: 375,
width: 500,
modal: false,
open: function() {
$("body").draggable("destroy");
$tab_title_input.focus();
},
close: function() {
$.ajax({
async: false,
type: 'POST',
url: 'collection.php',
success: function(data) {
$("#collection").html(data);
$("body").on("mouseover", ".draggable_container", function(){
$(".object_container").draggable({
cursor: "move",
cursorAt: { top: -5, left: -5 },
stop: function(){}
})
});
}
});
}
});
Remove the first .live call and change the second .live call to the following:
$('body').on('mouseover', '.draggable_container',
function(){
$(this).draggable({ cursor: "move", cursorAt: { top: -5, left: -5 }, stop: function(){} });
});

jQuery Ajax Form Submit Fails

I am developing an MVC4 mobile app that uses several forms which are loaded into a section on the layout via ajax. I've got jQuery mobile set with Ajax turned off so I can manage the Ajax myself. Most of the forms work fine, the load and submit via ajax as they should. However, so far there is one form that refuses to fire the form submit and submit the form via ajax like the rest. First, the form is loaded when a user clicks to add a contact and this works fine:
// Handle the add contact button click
$('#btnAddNewContact').on('click', function (e) {
e.preventDefault();
// Make sure a location was selected first.
var locationID = $('#cboLocation').val();
if (locationID.length === 0) {
//$('#alertTitle').text('REQUIRED');
$('#alertMsg').html("<p>A Contact must be associated with a Location.</p><p>Please select or add a Location first.</p>");
$('#alertDialogDisplay').click();
} else {
SaveOpportunityFormState();
$.cookie('cmdLocationId', locationID, { path: '/' });
$.mobile.loading('show');
$.ajax({
url: '/Contact/Add',
type: 'GET',
cache: false,
success: function (response, status, XMLHttpRequest) {
$('section.ui-content-Override').html(response);
// Refresh the page to apply jQuery Mobile styles.
$('section.ui-content-Override').trigger('create');
// Force client side validation.
$.validator.unobtrusive.parse($('section.ui-content-Override'));
},
complete: function () {
$.cookie('cmdPreviousPage', '/Opportunity/Add', { path: '/' });
AddContactLoad();
ShowSearchHeader(false);
$.mobile.loading('hide');
},
error: function (xhr, status, error) {
// TODO - See if we need to handle errors here.
}
});
}
return false;
});
Notice that after successfully loading the form the AddContactLoad() function is fired. This works fine and here is that code:
function AddContactLoad() {
$('#contactVM_Phone').mask('(999) 999-9999? x99999');
$('#frmAddContact').on('submit', function (e) {
e.preventDefault();
if ($(this).valid()) {
$.mobile.loading('show');
$.ajax({
url: '/Contact/Add',
type: 'POST',
cache: false,
data: $(this).serialize(),
success: function (response, status, XMLHttpRequest) {
if (!response) { // Success
ReturnToAddOpportunity();
} else { // Invalid Form
$('section.ui-content-Override').html(response);
// Force jQuery Mobile to apply styles.
$('section.ui-content-Override').trigger('create');
// Force client side validation.
$.validator.unobtrusive.parse($('section.ui-content-Override'));
AddContactLoad();
$.mobile.loading('hide');
}
},
complete: function () {
},
error: function (xhr, status, error) {
// TODO - See if we need to handle errors here.
}
});
}
return false;
});
$('#btnCancel').on('click', function (e) {
e.preventDefault();
// See where add contact was called from.
var previousPage = $.cookie('cmdPreviousPage');
if (previousPage.indexOf("Detail") >= 0) {
ReturnToOpportunityDetails();
} else {
ReturnToAddOpportunity();
}
return false;
});
}
If I click the cancel button, that code is fired so I know this is working too. Here is my form code:
#using (Html.BeginForm("Add", "Contact", FormMethod.Post, new { #id = "frmAddContact" }))
{
#Html.ValidationSummary(true)
#Html.AntiForgeryToken()
-- Form Fields Here --
<div class="savecancel" >
<input type="submit" value="Save" data-mini="true", data-theme="b", data-inline="true" />
Cancel
</div>
}
As you can see the form is named frmAddContact and that is what the AddContactLoad() function is attaching the submit event to. To save my sole I cannot figure out why the form does not submit via the ajax post like every other form in the app. Am I missing some kind of initialization, I just don't know. If anyone can please help I'd really appreciate it!!
As it turns out, I had created a custom unobtrusive Ajax validator for a phone number then copied and pasted it to do the same with a zip code. Unfortunately in the process I forgot to rename a variable and thus an error was occurring in the validation script which caused the problem. In the mean time, if you're reading this, you might take a note of the code here and how to inject HTML into a page via Ajax and jQuery mobile. I've never found this in a book or on the web and it contains some very useful methodology and syntax. On the form submit the reason I'm checking for the empty response is I just return null from the controller to validate the form was valid and the save worked in which case I send them to a different HTML injection i.e. that page they originally came from. If null is not returned I inject that page with the HTML containing the original form and error markup so the user can make corrections then resubmit. I'm also calling a form load method that attaches handlers to the HTML once it's injected into the main page. Hope this helps somebody!

Update jquery ui dialog from another jquery ui dialog

I have a jquery dialog and from this one, i open another dialog, where user insert some data. How can I update this user data from the second dialog to the first one, without closing them?
Is this possible? Are some examples in the web?
Thanks in advance
ok so this is my script, which opens the second dialog. I open this dialog with a link, which calls a function in my mvc controller, and this returns the partial view with the datas...
<script type="text/javascript">
$(document).ready(function () {
$("#dialog2").dialog({
bgiframe: false,
autoOpen: false,
height: 200,
resizable: false,
modal: true,
buttons: {
OK: function () {
$("#dialog2 > form").submit();
$(this).dialog('close');
},
Abbrechen: function () {
$(this).dialog('close');
}
}
});
$('#changePW').click(function () {
$('#dialog1').dialog('open')
});
});
</script>
#Roysvork: then I have to but this in the buttons OK function?
As a dialog is simply an html element underneath, you can still access said element using jQuery in the usual fashion:
var dialog1 = $("#dialog1");
var dialog2 = $("#dialog2");
dialog1.dialog("show");
dialog2.dialog("show");
So in your event handler for dialog 1 you can just do :
var value = dialog2.find("#inputbox").val();
dialog2.find("#textbox").val(value) ;
etc...

jQuery UI Dialog Will Not Close

Given the following script:
$(function () {
$(".editLink").button();
$('#editPersonDialog').dialog({
autoOpen: false,
width: 800,
resizable: false,
title: 'Edit Person',
modal: true,
buttons: {
"Save": function () {
$("#update-message").html('');
$("#updatePersonForm").submit();
},
"Close": function () {
$(this).dialog('close');
}
},
close: function (event, ui) {
$(this).dialog('close');
}
});
$(".editLink").click(function () {
var dialogDiv = $('#editPersonDialog');
var linkObj = $(this);
var viewUrl = linkObj.attr('href');
$.get(viewUrl, function (data) {
dialogDiv.html(data);
//validation
var $form = $("#updatePersonForm");
// 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;
});
});
function updateSuccess() {
if ($("#update-message").html() == "True") {
$('#editPersonDialog').dialog('close');
$("#commonMessage").html("Update Complete");
$("#commonMessage").delay(400).slideDown(400).delay(3000).slideUp(400);
}
else {
$("#update-message").show();
}
}
If I click the "X" button on the dialog the form closes fine. If I click the "Close" button then it does not close. I have verified that the code for the "Close" button is being called.
Both the "X" button and the "Close" button are both running the same statement: '$(this).dialog('close');'. Why would one work and the other not work?
As an aside the dialog will not open a second time unless I refresh the page. I imagine that these 2 problems may be related.
I have found many people with similar problems and a number of different solutions that worked for them. Unfortunately none of them worked for me.
Further Info:
The dialog displays a partial view in an Ajax form:
#using (Ajax.BeginForm("Edit", "Person", null,
new AjaxOptions
{
UpdateTargetId = "update-message",
InsertionMode = InsertionMode.Replace,
HttpMethod = "POST",
OnSuccess = "updateSuccess"
},
new { #id = "updatePersonForm" }))
{
#Html.ValidationSummary(true)
<div id="update-message" class="hiddenDiv"></div>
<div class="blockGraygradient">
#Html.Partial("_CreateEditCommon")
#Html.HiddenFor(model => model.SelectedPerson.Id)
#Html.HiddenFor(model => model.SelectedPerson.RowVersion)
#Html.HiddenFor(model => model.SelectedPerson.CreateTime)
</div><p/>
}
Try using this instead.
$(this).dialog('destroy');
We had exactly the same problem. In the end, every time you re-opened the dialog it was actually re-injecting the dialog markup into the DOM. Then, when you click close (for the second time) it only closes the first occurrence of the dialog, but not necessarily the one that's open. You can check this using a run-time DOM inspector like FireBug or Chrome's built-in developer tools.
I found out that the cause of both problems (the close button not working and being unable to show the dialog more than once without refreshing the page) was that I had included references to my script files in both my main page and the partial view being displayed by the dialog. Once I removed the script references from the partial view the problems disappeared.
(As an aside this has now raised another problem to do with an Ajax update back onto the main page when the dialog is closed. I think this is the reason that I put the scripts into the partial view in the first place).
You have too much recursion. You don't need to subscribe to the close event of your jQuery dialog and invoke $(this).dialog('close'); inside it. Simply comment this line or remove completely the close event subscription:
$('#editPersonDialog').dialog({
autoOpen: false,
width: 800,
resizable: false,
title: 'Edit Person',
modal: true,
buttons: {
"Save": function () {
$("#update-message").html('');
$("#updatePersonForm").submit();
},
"Close": function () {
$(this).dialog('close');
}
}
});

Resources