Solved

Close jquery UI Dialog on submit & refresh parent page

Posted on 2011-09-16
28
8,595 Views
Last Modified: 2012-05-12
Hey Experts!!

I'm still learning Jquery and Jquery UI so I have another question.

I have a form that's opened up inside of a dialog. Once the form is submitted, it calls the jquery Ajax code below. What I want, is after it submits and after it displays the message, I'd like to close the dialog and possibly refresh the page I'm on.

Help is much appreciated!
0
Comment
Question by:LZ1
  • 12
  • 12
  • 4
28 Comments
 
LVL 40

Expert Comment

by:gurvinder372
ID: 36550786
In the callback method of ajax submit, you need to close the dialog box'
$(foo).dialog('close')

and at that the close event of the dialog box, reload the page
http://jqueryui.com/demos/dialog/#event-close

Knowing that you are genius yourself, let me know if i answered it correctly :)
0
 
LVL 30

Author Comment

by:LZ1
ID: 36550808
I forgot to paste the code.  DUH! It's Friday and I'm really trying hard not to leave early. ;)  And believe me, I am far from a genius when it comes to Jquery or Javascript. I am learning though.

Here's the code with your modificatoin gurvinder:

$(".submit").click(function() {
		var dataString =  $('form#ideaUpdate').serialize();			   
		//alert (dataString);return false;
			
		$.ajax({
		 type: "POST",
		 url: "/ideaCenter/ideaUpdate.asp",
		 data: dataString,
		 success: function() {
			   $('#ideaDisplay').html("<div id='message'></div>");
			   $('#message').html("<img id='checkmark' src='/images/check.png' /><h3>Status Updated! </h3>")
			   .hide()
			   .fadeIn(500, function() {
					$('#message').append("");		   
				});
			$(this).dialog('close');	
		 }
		}); 
    return false;
	});

Open in new window

0
 
LVL 40

Expert Comment

by:gurvinder372
ID: 36550824
can i see the mark up also?
0
 
LVL 30

Author Comment

by:LZ1
ID: 36550837
Sure thing.
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Submit a New Idea</title>
	
	
	

<link href="/css/reset.css" rel="stylesheet" type="text/css" />
<link href="/css/main.css" rel="stylesheet" type="text/css" />
</head>

<body>
	<div id="container">
		<form name="ideaUpdate" method="post" id="ideaUpdate">

			<div id="ideaDisplay">			
				<img src="images/lightbulb-logo.png" class="indicator" height="64px" />
				<h1>New Idea</h1>
								
					<div id="updStatus">
						
							<img src="../images/icons/32x32/stop.png" class="help" title="Closed"/>
							<span class="txt">Closed</span>
						
					</div><!--end updStatus -->

					<div id="ideaText">		
						Here's a great new idea for you.
					</div><!--end ideaText -->

					
					<span class="submitted">
						Submitted by: <span class="name">John</span><br /> 
						On: <span class="name">8/24/2011 </span>
					</span><!--end submitted -->
					
					<div id="checks">						
						<select name="updStatus" size="1" id="updStatus">
							<option value="pass" >Pass</option>

							<option value="closed" selected="selected">Closed</option>
							<option value="future" >Future</option>
						</select>
						
				</div><!--end checks -->
											
				<div id="buttons">
					<input name="Submit" type="submit" class="submit button start" value="Submit" id="submit">
					<input name="Reset" type="reset" class="reset button" value="Reset" id="reset">
				</div>

				
				<input name="modifiedDate" type="hidden" value="9/16/2011" />
				<input type="hidden" name="MM_recordId" value="44" />
			</div><!--end ideaDisplay -->
		</form>
	</div> <!--end container -->
	
	<script type="text/javascript" src="includes/jquery-1.6.2.min.js"> </script>
	<script type="text/javascript" src="includes/ideaEdit.js"></script>

</body>

</html>

Open in new window

0
 
LVL 40

Expert Comment

by:gurvinder372
ID: 36550915
Thanks, but how/where are you initializing the dialog box.
First
$(this).dialog('close');      
'this' has to be replaced by the id selector

Then, inside the dialog initializer you need to register the close event as suggested in the links above
0
 
LVL 30

Author Comment

by:LZ1
ID: 36550975
I'm initializing the dialog here:
<script type="text/javascript">
	$(document).ready(function () {
	  $('.link').live('click', function (e) {
		e.preventDefault();
		 var page = $(this).attr("href")
		 var pagetitle = $(this).attr("title")
		 var $dialog = $('<div></div>')
		 .html('<iframe style="border: 0px;overflow:hidden; " src="' + this + '" width="100%" height="100%" frameBorder="0"></iframe>')
		 .dialog({
				autoOpen: false,
				modal: false,
				height: 560,
				width: 540,
				maximize:true,
				minimize:true,
				position: ['center','top'],
				title: pagetitle,
				show: 'blind'
			 })
			.dialogExtend({
				"maximize" : true,
				"dblclick" : "maximize",
				"icons" : { 
					"maximize" : "ui-icon-extlink",
					"restore" : "ui-icon-newwin"
				}
			});
		 $dialog.dialog('open');
	  });
	});
</script>

Open in new window


Then if I replace $(this) with $(".ui-dialog"), nothing happens. No errors in Firebug either.

0
 
LVL 40

Expert Comment

by:gurvinder372
ID: 36551020
try replacing line 7 with
var $dialog = $('<div id="dialogId"></div>')

and then $("#dialogId").dialog('close'); \\should close the dialog box

after initializing the box, bind the dialog close event
$( "#dialogId" ).bind( "dialogclose", function(event, ui) {
  location.reload(true);
});

0
 
LVL 30

Author Comment

by:LZ1
ID: 36551190
The dialog opens ok now, but it doesn't close after I hit submit.
<script type="text/javascript">
        $(document).ready(function () {
          $('.link').live('click', function (e) {
                e.preventDefault();
                 var page = $(this).attr("href")
                 var pagetitle = $(this).attr("title")
			  var $dialog = $('<div id="dialogId"></div>')    
			  .html('<iframe style="border: 0px;overflow:hidden; " src="' + this + '" width="100%" height="100%" frameBorder="0"></iframe>')
                 .dialog({
                                autoOpen: false,
                                modal: false,
                                height: 560,
                                width: 540,
                                maximize:true,
                                minimize:true,
                                position: ['center','top'],
                                title: pagetitle,
                                show: 'blind'
                         })
                        .dialogExtend({
                                "maximize" : true,
                                "dblclick" : "maximize",
                                "icons" : { 
                                        "maximize" : "ui-icon-extlink",
                                        "restore" : "ui-icon-newwin"
                                }
                        });
                 $dialog.dialog('open');
			  $("#dialogId").dialog('close'); //should close the dialog box
          });
        });
</script>
<script type="text/javascript">
	$( "#dialogId" ).bind( "dialogclose", function(event, ui) {
		location.reload(true);
	});
</script>

Open in new window

0
 
LVL 25

Expert Comment

by:Kyle Hamilton
ID: 36552731
this:

var $dialog = $('<div id="dialogId"></div>')

the #dialogId div is replaced by the iframe created by the .html(). .html() replaces whatever is in the selector.
So then you can't close #dialogId because it doesn't exist..


replace lines 7 and 8 with:



 
var $dialog = $('<iframe style="border: 0px;overflow:hidden; " src="' + this + '" width="100%" height="100%" frameBorder="0"></iframe>')    
                          .wrap('<div id="dialogId')

Open in new window

0
 
LVL 25

Expert Comment

by:Kyle Hamilton
ID: 36552738
sorry, typo, I do that all the time...

var $dialog = $('<iframe style="border: 0px;overflow:hidden; " src="' + this + '" width="100%" height="100%" frameBorder="0"></iframe>')    
                          .wrap('<div id="dialogId">')

Open in new window

0
 
LVL 25

Expert Comment

by:Kyle Hamilton
ID: 36552741
UGhhhhh, forgot the slash....

.wrap('<div id="dialogId" />')
0
 
LVL 25

Expert Comment

by:Kyle Hamilton
ID: 36552768
If it's still not working...

it would be really helpful if you could post a link to your page. It's kind of hard to look at bits and pieces of code without seeing the whole picture.
0
 
LVL 30

Author Comment

by:LZ1
ID: 36552873
I will try your suggestion on Monday kozaiwaniec.  Thanks and have a great weekend everyone!
0
 
LVL 30

Author Comment

by:LZ1
ID: 36716831
Sorry for the delay in getting back with everyone.  If you are still looking at the question, the dialog box still does not close when submitting the AJAX request.

I did try kozaiwaniec's suggestion, however still no love.

Wouldn't I have to close it within the AJAX request somehow?
$(".submit").click(function() {
		var dataString =  $('form#ideaUpdate').serialize();			   
		//alert (dataString);return false;
			
		$.ajax({
		 type: "POST",
		 url: "/ideaCenter/ideaUpdate.asp",
		 data: dataString,
		 success: function() {
			   $('#ideaDisplay').html("<div id='message'></div>");
			   $('#message').html("<img id='checkmark' src='/images/check.png' /><h3>Status Updated! </h3>")
			   .hide()
			   .fadeIn(500, function() {
					$('#message').append("");		   
				});
			$(".ui-dialog").dialog('close');//Something like this  here????
		 }
		}); 
    return false;
	});

Open in new window

0
Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

 
LVL 25

Expert Comment

by:Kyle Hamilton
ID: 36717777
Here is a working example. In it I had to comment out your ajax code, because I don't have access to your asp file, and it stop the code from runnnig.

(You must have the #ideaDisplay div already on your page, I'm assuming you do, for the box to open in the first place.)

http://candpgeneration.com/EE-close-UI-dialog.php

$(".submit").click(function(e) {
                e.preventDefault();    
                var dataString =  $('form#ideaUpdate').serialize();                        
                //alert (dataString);return false;
                        
               $.ajax({
                type: "POST",
                url: "/ideaCenter/ideaUpdate.asp",
                data: dataString,
                success: function() {
                           $('#ideaDisplay').html("<div id='message'></div>");
                           $('#message').html("<img id='checkmark' src='/images/check.png' /><h3>Status Updated! </h3><br/><div class='close'>close the box</div>")
                           .hide()
                           .fadeIn(500, function() {
                                        $('#message').append("");                  
                                });
                       
                }
                 
                }); 
    return false;
        });
        
        $('#message, .close').live("click", function(){
           $(this).detach();
            
        });

Open in new window

0
 
LVL 30

Author Comment

by:LZ1
ID: 36717846
Close. I want the function to also close the dialog, without any further interaction from the user.
0
 
LVL 25

Expert Comment

by:Kyle Hamilton
ID: 36717960
do you mean wait for user to read message, and then close? You'll need to set an interval. Otherwise it closes immediately, and you don't get a chance to read the message.

let me know...
0
 
LVL 25

Expert Comment

by:Kyle Hamilton
ID: 36718059
add this:

 
/// other code stuff above ////

.fadeIn(500, function() {
                                        $('#message').append("").delay(2000).fadeOut('fast');                  
                                });

Open in new window

0
 
LVL 30

Author Comment

by:LZ1
ID: 36718333
Well I don't mind if there's a small interval, but I'm most concerned about closing the Jquery UI dialog after a successful submit.  It's a simple form, so I'm not worried that anyone will submit the wrong info. I do have validation for that before it submits to the AJAX page.
0
 
LVL 25

Expert Comment

by:Kyle Hamilton
ID: 36718392
I'm not sure why you are opening the dialog box in the first place in that case. If the user doesn't need to see a confirmation message, then just remove the success callback.

Or you can change this:
.delay(2000).fadeOut('fast');

to:

.detach();

this will remove the message as soon as it is generated. But that's sort of redundant...
0
 
LVL 30

Author Comment

by:LZ1
ID: 36718444
The dialog box contains a form the user needs to fill out if they're going to update a record. I'm using the Jquery UI to serve the functionality.

I added the detach function, but all that does is kill the message.  It's not closing the dialog.
0
 
LVL 25

Expert Comment

by:Kyle Hamilton
ID: 36718521
ok, I didn't understand which box you were trying to close.

If the dialog has an id, you should be able to use detach with that id.

See what happens...
success: function() {
                           $('#ideaDisplay').html("<div id='message'></div>");
                           $('#message').html("<img id='checkmark' src='/images/check.png' /><h3>Status Updated! </h3>")
                           .hide()
                           .fadeIn(500, function() {
                                        $('#message').append("");                  
                                });
                           $("#dialogId").detach();
                 }

Open in new window

0
 
LVL 30

Author Comment

by:LZ1
ID: 36718954
Still no go.  Entire code is below:
$.ajax({
	 type: "POST",
	 url: "/ideaCenter/ideaUpdate.asp",
	 data: dataString,
	success: function() {
		  $('#ideaDisplay').html("<div id='message'></div>");
		  $('#message').html("<img id='checkmark' src='/images/check.png' /><h3>Status Updated! </h3>")
		  .hide()
		  .fadeIn(500, function() {
					$('#message').append("");                  
			  });
		  $(".ui-dialog").detach();
		}	
	}); 
return false;
});

Open in new window

0
 
LVL 25

Expert Comment

by:Kyle Hamilton
ID: 36718992
Here's what the problem is. If your form is in an iframe, JavaScript doesn't have access to the script on the main page. As long as the frame source is on the same domain though you can access the parent window by referencing it explicitly.
0
 
LVL 30

Author Comment

by:LZ1
ID: 36719014
I'm on the same domain. It's an intranet and yes it's opening it up in an iframe.
0
 
LVL 25

Accepted Solution

by:
Kyle Hamilton earned 500 total points
ID: 36719597
the other solution would be to use the .load method instead of inserting an iFrame.
so instead of this:

 
var $dialog = $('<div id="dialogId"></div>')    
                          .html('<iframe style="border: 0px;overflow:hidden; " src="' + this + '" width="100%" height="100%" frameBorder="0"></iframe>')

Open in new window


something like this:

 
var link = $(this).attr("href");
var $dialog = $('<div id="dialogId" />')    
               .load(link + ' #container'); // (the space in front of the hash is important)

Open in new window


Then you should be able to use your original line (given it's the correct usage of the plugin of course):

$(".ui-dialog").dialog('close'); //Something like this  here????
0
 
LVL 30

Author Closing Comment

by:LZ1
ID: 36719686
Perfect all the way around. Thanks so much for sticking with me!
0
 
LVL 25

Expert Comment

by:Kyle Hamilton
ID: 36719754
:)))

I'm very pleased that worked. Cheers.
0

Featured Post

6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

Join & Write a Comment

Introduction Chart.js, used properly, can visually add a difference to your charting applications. It engages your visitors and allows them to interact with data they otherwise wouldn't be able to without expensive and complicated systems. For this…
Nothing in an HTTP request can be trusted, including HTTP headers and form data.  A form token is a tool that can be used to guard against request forgeries (CSRF).  This article shows an improved approach to form tokens, making it more difficult to…
The viewer will learn how to dynamically set the form action using jQuery.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)

758 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now