We help IT Professionals succeed at work.

how to raise JQUERY event and make AJAX call when user shy away from the present page

chaitu chaitu
on
Medium Priority
592 Views
Last Modified: 2012-05-11
In the following scenarios overlay should come in the main page and parallely one ajax call should be happened and insert the data in DB.

our requirement is client wants to know howmany users leaving the main page without entering

main data.at that time this overlay should come and in the background ajax DB call should be

happened.

1)when user leaves the page.(e.g. type other address in the address bar).bascially user shy away from the browser.
2)clicks browser close button.

I have some clarifications in jquery  Is there any events are there in jquery if user do

above screnarios and how to make AJAX calls.
Comment
Watch Question

I believe the only way is to use the window.onbeforeunload() method.

http://api.jquery.com/unload/
Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019
Commented:
Unlock this solution and get a sample of our free trial.
(No credit card required)
UNLOCK SOLUTION

Author

Commented:
"The problem is to have time to do the ajax call, generaly(depending the browser) if the user use the browser close button, you don't have this time."

if the use the browser close button then the main page should not close.on top of main page overlay should pop come and simultaneously in the back ground AJAX class should happen.

I am telling you once again whenever user shy away from the main application,the browser shouldn't close only overlay should come.that is my requirement.
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
You will never haver this power with javascrip

Author

Commented:
tell me one thing.

forget about AJAX call;when user choose file -- exit-- option to close window at that time can't we show the overlay on the main page?the main page should not close...

does below link serve my purpose??

http://www.mkyong.com/jquery/how-to-stop-a-page-from-exit-or-unload-with-jquery/
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
>does below link serve my purpose??
It work fine on IE8, FF3.6,  Chrome 10 but not Opera 11

Author

Commented:
as of now we will leave Opera 11.if it works in other browsers it will be ok.in ur previous comments you said that 'You will never haver this power with javascrip '.

I am afraid that our project resolves around this functionality only.if this works then our main problem will be solved.

whenever user shy away(if uses close brower button,type some address and hit reload etc..) from the browser then we call  the below function and in the function call our overlay and after that call the AJAX for DB insertion.

$(window).bind('beforeunload', function(){
 //we will call our overlay and parallely call the AJAX for DB insertion
var jqxhr = $.post("example.php", function() {
      alert("success");
    })
});
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
>as of now we will leave Opera 11 if it works in other browsers it will be ok

I don't have the complete list of browsers, sorry.

We use the time the user take to click on the button (from the confirm box) ... if we're LUCKY the call reach successfully to the server
$(window).bind('beforeunload', function(){
        $.post("example.php");
	return '>>>>>Before You Go<<<<<<<< \n Your custom message go here';
})

Open in new window

Author

Commented:
you may be thinking that we are showing only confirm box in the overlay pop up.as per ur assumption if user clicks OK or CANCEL we may not have time to execute AJAX call.but its not like that;

we will show one overlay and in the back ground main application will be greyed out.
this overlay consists of some text fields and some buttons will be there and  in the mean time we will execute AJAX call.what do you say??
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
>what do you say??

do a try and check if you css popup stop the browser.
You will need a browser popup box (alert, prompt, confirm (your or the one coming from onbeforeunload)

you know you need to use onbeforeunload event (simple js or jquery)
now implement your code and you will see what happen

Author

Commented:
i will try in the mean time but tell me one thing.as you said we need to pop up css oveylay only.

my concern is how to prevent the browser from closing(e.g.when user chooses browser X button) when css overlay comes up?hav you comes across this kind of implementation before?
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
>as you said we need to pop up css oveylay only.

You will need a browser popup box (alert, prompt, confirm (your or the one coming from onbeforeunload)

Author

Commented:
if we go for browser popup box can you hide the minimize button and maximize buttons.i dont think so.

i think whenever you call this event "onbeforeunload" i am afraid that whatever you click(any buttons,links etc..) in the main page then this overlay will come.but one scenario is in the main form we have multiple buttons,if we click one of the button then only we need to show this overlay.


our client already sent sample overlay.it doesnot look like browser pop up box.it will have only X button at the top.

we should call this overlay in the below scenarios only.


1)close the page, or navigate to a different web site.
2)click one of the button in the form.
3)when session times out .(if we make it works above scenarios.i think we can do this as well.)
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
Do you need something else?

Author

Commented:
need lot of confirmation.

"with browser pop up can we do this thing?"
can we hide the minimize button and maximize buttons?

"i think whenever you call this event "onbeforeunload" i am afraid that whatever you click(any buttons,links etc..) in the main page then this overlay will come."

Is this true?
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
>can we hide the minimize button and maximize buttons?
you can do what you want with a css popup
no, go for css popup

>onbeforunload = function
if the function return something, you got a message (a pure javascript confirm box) else you left the page

Author

Commented:

sorry for replying late.i am working kind of POC for our requirement.i am using jquery modal window(http://jqueryui.com/demos/dialog/#modal-form) .when i click "Create new user" overlay comes parallely i need to make an ajax call to insert some data in database.

i have little bit confusation on where to put the code for AJAX call.

at which place i need make an ajax call in the below code ?

<meta charset="utf-8">
	
	<style>
		body { font-size: 62.5%; }
		label, input { display:block; }
		input.text { margin-bottom:12px; width:95%; padding: .4em; }
		fieldset { padding:0; border:0; margin-top:25px; }
		h1 { font-size: 1.2em; margin: .6em 0; }
		div#users-contain { width: 350px; margin: 20px 0; }
		div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
		div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
		.ui-dialog .ui-state-error { padding: .3em; }
		.validateTips { border: 1px solid transparent; padding: 0.3em; }
	</style>
	<script>
	$(function() {
		// a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
		$( "#dialog:ui-dialog" ).dialog( "destroy" );
		
		var name = $( "#name" ),
			email = $( "#email" ),
			password = $( "#password" ),
			allFields = $( [] ).add( name ).add( email ).add( password ),
			tips = $( ".validateTips" );

		function updateTips( t ) {
			tips
				.text( t )
				.addClass( "ui-state-highlight" );
			setTimeout(function() {
				tips.removeClass( "ui-state-highlight", 1500 );
			}, 500 );
		}

		function checkLength( o, n, min, max ) {
			if ( o.val().length > max || o.val().length < min ) {
				o.addClass( "ui-state-error" );
				updateTips( "Length of " + n + " must be between " +
					min + " and " + max + "." );
				return false;
			} else {
				return true;
			}
		}

		function checkRegexp( o, regexp, n ) {
			if ( !( regexp.test( o.val() ) ) ) {
				o.addClass( "ui-state-error" );
				updateTips( n );
				return false;
			} else {
				return true;
			}
		}
		
		$( "#dialog-form" ).dialog({
			autoOpen: false,
			height: 300,
			width: 350,
			modal: true,
			buttons: {
				"Create an account": function() {
					var bValid = true;
					allFields.removeClass( "ui-state-error" );

					bValid = bValid && checkLength( name, "username", 3, 16 );
					bValid = bValid && checkLength( email, "email", 6, 80 );
					bValid = bValid && checkLength( password, "password", 5, 16 );

					bValid = bValid && checkRegexp( name, /^[a-z]([0-9a-z_])+$/i, "Username may consist of a-z, 0-9, underscores, begin with a letter." );
					// From jquery.validate.js (by joern), contributed by Scott Gonzalez: http://projects.scottsplayground.com/email_address_validation/
					bValid = bValid && checkRegexp( email, /^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))@((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i, "eg. ui@jquery.com" );
					bValid = bValid && checkRegexp( password, /^([0-9a-zA-Z])+$/, "Password field only allow : a-z 0-9" );

					if ( bValid ) {
						$( "#users tbody" ).append( "<tr>" +
							"<td>" + name.val() + "</td>" + 
							"<td>" + email.val() + "</td>" + 
							"<td>" + password.val() + "</td>" +
						"</tr>" ); 
						$( this ).dialog( "close" );
					}
				},
				Cancel: function() {
					$( this ).dialog( "close" );
				}
			},
			close: function() {
				allFields.val( "" ).removeClass( "ui-state-error" );
			}
		});

		$( "#create-user" )
			.button()
			.click(function() {
				$( "#dialog-form" ).dialog( "open" );
			});
	});
	</script>



<div class="demo">

<div id="dialog-form" title="Create new user">
	<p class="validateTips">All form fields are required.</p>

	<form>
	<fieldset>
		<label for="name">Name</label>
		<input type="text" name="name" id="name" class="text ui-widget-content ui-corner-all" />
		<label for="email">Email</label>
		<input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
		<label for="password">Password</label>
		<input type="password" name="password" id="password" value="" class="text ui-widget-content ui-corner-all" />
	</fieldset>
	</form>
</div>


<div id="users-contain" class="ui-widget">
	<h1>Existing Users:</h1>
	<table id="users" class="ui-widget ui-widget-content">
		<thead>
			<tr class="ui-widget-header ">
				<th>Name</th>
				<th>Email</th>
				<th>Password</th>
			</tr>
		</thead>
		<tbody>
			<tr>
				<td>John Doe</td>
				<td>john.doe@example.com</td>
				<td>johndoe1</td>
			</tr>
		</tbody>
	</table>
</div>
<button id="create-user">Create new user</button>

</div><!-- End demo -->



<div class="demo-description">
<p>Use a modal dialog to require that the user enter data during a multi-step process.  Embed form markup in the content area, set the <code>modal</code> option to true, and specify primary and secondary user actions with the <code>buttons</code> option.</p>
</div><!-- End demo-description -->

Open in new window

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
$(window).bind('beforeunload', function(){
	return $.ajax({ "url":"example.php", "data":"field="+encodeURIComponent($("#field").val()), "async":false }).responseText;
})

Open in new window

Author

Commented:
leakim971,

I have clarification here.if i abandon the browser then i should call beforeunload event.but in this case its just button right.

actually what i thougth was may be I need to incorporate  AJAX call in the below method.

do you think that even for simple button can we call beforeunload event like you mentioned above?

                                                     $( "#create-user" )
                  .button()
                  .click(function() {
                        $( "#dialog-form" ).dialog( "open" );
                  });
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
IMHO it's a bad idea, rewrite and update the code for the button

Author

Commented:
so can i make AJAX call in the method??

                                                     $( "#create-user" )
                  .button()
                  .click(function() {
                        $( "#dialog-form" ).dialog( "open" );
                  });
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
$( "#dialog-form" ).dialog( {
   close: function(event, ui) { ajax call here }
}

check the event tab here : http://jqueryui.com/demos/dialog/#event-close

Author

Commented:
i made JSON call  like below and output is coming ike this but its going to error function.
when i print alert(e.responseText); its printing whole code in window.why is it so??

[{employees:'ABCD' }]

function callAJAX()
		{

 alert("callAJAX")

		 $.ajax({	
						url: "${flowExecutionUrl}&_eventId=proceed",
						dataType: "json",
						data: $('#frm').serialize(),
					    success: function(data){ alert(data.employees.length)
						     alert("success")  },   
						error: function(e, xhr){  alert(e.responseText);
   }

				
					});
		}

Open in new window

leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
We're off topic, you should open a new question

Author

Commented:
this is final question in this post??

Author

Commented:
I have modified the modal window code for our requirement.I will close this Q if its ok.

<html>
<head>
<title>appcache_display_template</title>
<style type="text/css">
.dialog{
display:none;
}
</style>
<link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8.5/themes/smoothness/jquery-ui.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.9/jquery-ui.min.js"></script>
<meta charset="utf-8">
<style>
        body { font-size: 62.5%; }
        label, input { display:block; }
        input.text { margin-bottom:12px; width:95%; padding: .4em; }
        fieldset { padding:0; border:0; margin-top:25px; }
        h1 { font-size: 1.2em; margin: .6em 0; }
        div#users-contain { width: 350px; margin: 20px 0; }
        div#users-contain table { margin: 1em 0; border-collapse: collapse; width: 100%; }
        div#users-contain table td, div#users-contain table th { border: 1px solid #eee; padding: .6em 10px; text-align: left; }
        .ui-dialog .ui-state-error { padding: .3em; }
        .validateTips { border: 1px solid transparent; padding: 0.3em; }
    </style>
    <script>
    $(function() {
        // a workaround for a flaw in the demo system (http://dev.jqueryui.com/ticket/4375), ignore!
        $( "#dialog:ui-dialog" ).dialog( "destroy" );
        
        $( "#dialog-form" ).dialog({
            autoOpen: false,
            height: 550,
            width: 350,
            modal: true,
            buttons: {
                "Create an account": function() {
                    var bValid = true;
              
                  $( this ).dialog( "close" );
                },
                Cancel: function() {
                    $( this ).dialog( "close" );
                }
               
            }
          /*  close: function() {
                allFields.val( "" ).removeClass( "ui-state-error" );
            }*/
           
        });

function callAJAX()
		{
		   $.ajax({	
						url: "url",
						dataType: "json",
						data: $('#frm').serialize()+"&ssn="+$("#ssn").val(),
						contentType: "application/json; charset=utf-8",
					    success: function(data){ 
							   alert(data.employees.length)
						         alert("success")  
								},   
							error: function(e, xhr){ 
								   alert("error");
							}
					});
		}


        $( "#create-user" )
            .button()
            .click(function() {
                $( "#dialog-form" ).dialog( "open" );
					$( "#fname" ).val($( "#fname1" ).val());
					$( "#lname" ).val($( "#lname1" ).val());
					$( "#email" ).val($( "#email1" ).val());
					$( "#zipcode" ).val($( "#zipcode1" ).val());
					callAJAX();
            });
    });
    </script>


<body>
<div class="demo">

<div id="dialog-form" title="Create new user">
    <p class="validateTips">All form fields are required.</p>

    <form id='frm'>
    <fieldset>
        <label for="name">First Name</label>
        <input type="text" name="name" id="fname"  class="text ui-widget-content ui-corner-all" />
        <label for="email">Email</label>
        <input type="text" name="email" id="email" value="" class="text ui-widget-content ui-corner-all" />
        <label for="zipcode">Zip Code</label>
        <input type="text" name="zipcode" id="zipcode" value="" class="text ui-widget-content ui-corner-all" />
        <label for="lname">Last Name</label>
        <input type="text" name="lname" id="lname" value="" class="text ui-widget-content ui-corner-all" />
    </fieldset>
	    </form>
</div>


<div id="users-contain" class="ui-widget">
    <h1>Existing Users:</h1>
    <table id="users" class="ui-widget ui-widget-content">
        <thead>
            <tr class="ui-widget-header ">
                <td>First Name</td><td>   <input type="text" name="fname1" id="fname1"  /></td>
                <td>Last Name</td><td>   <input type="text" name="lname1" id="lname1"  /></td>
            </tr>
        </thead>
        <thead>
          <tr class="ui-widget-header ">
                <td>Zip Code</td><td>   <input type="text" name="zipcode1" id="zipcode1"  /></td>
                <td>Email</td><td>   <input type="text" name="email1" id="email1"   /></td>
            </tr>
        </thead>
		  <thead>
            <tr class="ui-widget-header ">
                <td>SSN</td><td>   <input type="text" name="ssn" id="ssn"  /></td>
                <td>DOB</td><td>   <input type="text" name="dob" id="dob"  /></td>
            </tr>
        </thead>
        <thead>
          <tr class="ui-widget-header ">
                <td>Address</td><td><input type="text" name="addr" id="addr"  /></td>
                <td>City</td><td>   <input type="text" name="city" id="city"  /></td>
            </tr>
        </thead>
    </table>
</div>
<button id="create-user">Create new user</button>
<a href="${flowExecutionUrl}&_eventId=proceed">Proceed</a>
</div><!-- End demo -->
<!--  
<body>
<form>
<table>
<tr>
<td>
First Name:
</td>
<td>
<input type='text' id='fname'>
</td>
<td>
Last Name:
</td>
<td>
<input type='text' id='lname'>
</td>
</tr>
<tr>
<td>
Zip Code:
</td>
<td>
<input type='text' id='zipcode'>
</td>
<td>
Email:
</td>
<td>
<input type='text' id='email'>
</td>
<tr>
<td>
Home Street Address:*
</td>
<td>
<input type='text' id='homeaddr'>
</td>

<td>
Home Apt/Suite#:
</td>
<td>
<input type='text' id='homeapt'>
</td>
</tr>

<tr>
<td>
Date of Birth:*
</td>
<td>
<input type='text' id='dob'>
</td>
<td>
Social Security Number:*
</td>
<td>
<input type='text' id='ssn'>
</td>
</tr>

<tr>
<td>
Employer City:
</td>
<td>
<input type='text' id='empcity'>
</td>
<td>
Employer State:
</td>
<td>
<input type='text' id='empstate'>
</td>
</tr>
<tr>
<td>
<input type='submit' id='SAVE' value='SAVE' onclick='popup()'>
</td>
</tr>
</table>
</form>-->

</body>
</html>

Open in new window


leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
You're the only one to say if it run as you want
leakim971Multitechnician
CERTIFIED EXPERT
Distinguished Expert 2019

Commented:
Thanks for the points!
Unlock the solution to this question.
Thanks for using Experts Exchange.

Please provide your email to receive a sample view!

*This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.

OR

Please enter a first name

Please enter a last name

8+ characters (letters, numbers, and a symbol)

By clicking, you agree to the Terms of Use and Privacy Policy.