I have a jQuery modal dialog with an iFrame in it that shows some content. When a user selects an option in the iFrame, I make an Ajax call, and then I want to close my dialog, however it is not closing for me.
On my parent form I have a div tag:
div id="structureDialog" title="Add Structure"
I open my dialog when the user clicks an element on the parent:
// bind an onclick event onto tiles to display the modal dialogue window
$(".stationTile").bind('click', function () {
var src = "<iframe src="myurl" />";
var locationID = 1;
$("#structureDialog").attr("locationID", locationID);
$("#structureDialog").html(src); //iframe
$("#structureDialog").dialog({
modal: true,
});
});
In my iFrame I have the following:
$(".userOption").bind('click', function () {
$.ajax({
async: false,
type: "POST",
url: "/NewStructure.aspx/Build",
data: "{}",
contentType: "application/json; charset=utf-8",
dataType: "json",
success: buildSuccess
});
});
function buildSuccess(res, dest) {
$("body", window.parent.document).attr("style", "background-color:yellow;");
$("#structureDialog", window.parent.document).attr("style", "background-color:red;");
$("#structureDialog", window.parent.document).dialog('close');
}
In my function buildSuccess, I am able to successfully change my dialog box to red. However, the close function will not close my dialog box. From most examples I have seen so far, this code should work fine, so I’m stumped.
As I wrote in the comment above, the solution is related to the instance of jquery being run. When the dialog object is created, it is in the context of the jquery instance of the parent form. In an iFrame, a second instance of jquery is created, and hence the dialog box is not in scope.
Calling
$("#structureDialog", window.parent.document).dialog('close');searches the DOM of the parent using the local instance of jquery, and so since the dialog box was not initialized there, it cannot be closed there.The solution is to reference the jquery instance of the parent by rearranging the terms as follows:
parent.$("#structureDialog").dialog('close');This points the context to the parent first, and then uses the jquery instance of the parent to find the dialog box and close it.
Kudos to chrismarx1 on this post which pointed me to this solution:
http://forum.jquery.com/topic/trigger-from-iframe-to-parent-window