Is it possible to delay the moment when the unload method is called on a web page?
I have N pages and each page contains a form. I don't want users to click on a submit button so I simulated a click on the hidden submit button via javascript. This is activated everytime the user change page:
window.onbeforeunload = function() {
document.getElementById('submit_id').click();
}
This doesn't work but if I put an alert after .click ()
window.onbeforeunload = function() {
document.getElementById('submit_id').click();
alert("submitting form");
}
everything works like a charm. This because the alert gives the form the time to actually submit its data; without the alert the page unloads before the form has been submitted and therefore the changes are not saved.
I tried to put a dummy setTimeout after .click()
window.onbeforeunload = function() {
document.getElementById('submit_id').click();
setTimeout(console.log("dummy"), 200);
}
but it didn't work. Any help or feedback on this would be greatly appreciated.
if you use jquery, you can try to save via ajax. and maybe adding async to false, not recomended but could work in your example if save function is really fast.
http://api.jquery.com/jQuery.ajax/
here is how i save:
var $form = $('#formId');
$.ajax({
type: "POST",
url: $form.attr('action'),
data: $form.serialize(),
error: function (xhr, status, error) {
// error
},
success: function (response) {
// sucess
}
});
Related
is there any method in JQuery or Javascript to prevent the page refresh (F5) and then update only some parts of the page with Ajax?
I tried the code below with no results.
$(window).bind('beforeunload', function(event) {
event.preventDefault();
//My ajax refresh code
});
Many thanks for your time.
you can try this with below code:
$('.update').click(function () {
$.ajax({
url: "",
success: function (s, x) {
$('.yourupdatesection').html(s);
}
});
});
You can add update button in that section and then you will click on
it and only that one part will update with ajax
I have parent page where there is an element. Onclick of that element popup window comes. On popup window there is one textbox and submit button. Now I want to refresh parent page when submit button on popup window clicked.
I have solution to refresh parent page:
window.onload = function()
{
window.opener.location.reload();
}
I have added this script in popup jsp page. So whenever I click on element on parent page, popup window comes and parent page gets refreshed(want to skip this), then I add some text in textbox on popup and submit the data, since it is submit button popup again reloads and parent page gets refreshed(which is expected to happen). Since I am using window.onload on popup page, it gets refreshed twice, I want to skip first refresh.
So I decided to perform refresh on click of submit button.
Popup page JSP code:
<td align="center">
<html:submit styleId="btn_add" property="submitButton" onclick="formConfirmOff();" value="Add" />
</td>
Another solution I was trying to skip first refresh:
document.getElementById("btn_add").onclick = function(){
window.opener.location.reload();
}
But using above script it gives me error that cannot set property onclick of null
so it may be because script is getting executed before DOM loads. so I added script in
window.onload = function(){
document.getElementById("btn_add").onclick = function(){
window.opener.location.reload();
}
}
But when did this shows Confirm Navigation dialog with options Leave this page and stay on this page.
What may be the issue. Does the order of function passed to onclick matters ?
I simply want to refresh parent page when data is added on popup child page using submit button.
EDIT:
$(document).ready(function() {
$("#frm_addSpeedData").submit(function(event) {
//event.preventDefault();
$.ajax({
type: "POST", //chose your request type method POST or GET
url: "/webapp/addSpeedDataAction.do", // your struts action url
data: $(this).serialize(),
success: function() {
window.opener.location.reload(); // callback code here
}
})
})
});
Sometimes this code works but sometimes not.
Means when popup opens I submit the data on popup. Then on success parent window gets refreshed. But still I can not see updates on parent page.
what may be the issue ?
You will need to do this manually using AJAX call to your server and on successful execution you will refresh your parent page.
Below is example of using JQuery Ajax :
<script type="text/javascript">
$(document).ready(function() {
$("#form_selector").submit(function(event) {
event.preventDefault();
$.ajax({
type: "POST", //chose your request type method POST or GET
url: "Your_Action", // your struts action url
data: $(this).serialize(),
success: function() {
window.opener.location.reload(); // callback code here
}
})
})
});
</script>
Here is JavaScript version :
var url = "/webfdms/addSpeedDataAction.do";
xmlHttp.open("GET", theUrl, true);
xmlHttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest');
xmlHttp.overrideMimeType("application/octet-stream");
xmlHttp.responseType = "blob";
xmlHttp.onreadystatechange = function() {
if (xmlHttp.readyState == xmlHttp.DONE) {
if (xmlHttp.status == 200) {
window.opener.location.reload();
}
}
};
xmlHttp.send();
I have a page that lets you Add/Edit/Delete "Project Tasks" and Save the data to a database using jQuery's AJAX function to save the POST data.
I currently have 2 buttons on the page.
Button 1 .save-tasks-ajax-redirect - You click it and it makes a regular non-ajax POST to my backend and you are redirected to another Project page. This button does not have a click event yet. Perhaps the best way might be to simply create a new click event for this button class and then have it call my save function but it could pass in a variable to indicate that it needs to redirect? Before I posted this questions I was sort of hoping to have both button share the same click event and everything but perhaps this is a better idea?
Button 2 .save-tasks-ajax - You click it and it uses AJAX to Save the data and you can remain on the page editing more.
Now my goal is to modify how Button 1 works. Instead of making a regular HTTP POST, I would like for it to also make an AJAX save but when it is done, I would like it to redirect to a project page.
So below I have my 2 button HTML codes. Below that I have my jQuery Click event for my AJAX save button (Button 2) and below that I have my ajaxSaveTasks() function that my button calls to make the save.
I would like to modify this function and perhaps all of this code so that my Button 1 can use the same function to make an AJAX save but somehow it needs to differentiate itself so that it can also do a redirect after the AJAX save is complete.
Looking at the basic code below, how could I modify this to do that?
<button type="submit" class="save-tasks-ajax-redirect">Save Tasks and Return to Project</button>
<button type="submit" class="save-tasks-ajax">Save Tasks and Continue Editing</button>
$(window).load(function () {
// AJAX Save and Continue editing
$('#content').on('click', '.save-tasks-ajax', function () {
console.log('AJAX Save and Continue Editing Button Clicked!');
ajaxSaveTasks();
return false; // avoid to execute the actual submit of the form.
});
});
function ajaxSaveTasks(){
console.log('ajaxSaveChanges() Ran and Tasks Saved.');
// Reset Flag that Triggers Un-Saved Alert on page exit
window.unsavedChanges = false;
// Show a Loading/Saving Spinner
jQuery('#project_tasks').showLoading();
// Display a message to the user that we are Saving
flipNotify.show({
message: 'Project Tasks Saved!',
icon: 'tick',
delay: 2,
sticky: false
});
var url = "index.php?module=apoll_Web_Projects";
$.ajax({
type: "POST",
url: url,
data: $("#editTasksForm").serialize(), // serializes the form's elements.
success: function(data)
{
// Hide Header Un-Saved Changes Div
hideTaskUnSavedChangesHeaderBar()
// Hide Loading/Saving Spinner
jQuery('#project_tasks').hideLoading();
}
});
};
$(window).load(function () {
// AJAX Save and Continue editing
$('#content').on('click', '.save-tasks-ajax', function () {
console.log('AJAX Save and Continue Editing Button Clicked!');
ajaxSaveTasks();
return false; // avoid to execute the actual submit of the form.
});
// AJAX Save and redirect
$('#content').on('click', '.save-tasks-ajax-redirect', function () {
console.log('AJAX Save and Redirect Button Clicked!');
ajaxSaveTasks(function(){ window.location.assign("project.php"); });
return false; // avoid to execute the actual submit of the form.
});
});
function ajaxSaveTasks(callback){
... your code ...
$.ajax({
...
success: function(data)
{
// Hide Header Un-Saved Changes Div
hideTaskUnSavedChangesHeaderBar()
// Hide Loading/Saving Spinner
jQuery('#project_tasks').hideLoading();
if (callback)
callback();
}
});
};
i am working on jquery and javascript. and is there any way to make the page refresh and to restore the same link which is clicked. for example. in gmail.com when we open sent items which is in the lefthand side of the window and refresh the page. it get reloaded with the same sent items tab's contents, same things work for inbox and drafts when refreshed. is there anyother method or example to acheive this. if yes. please help. it would be appreciated.
here is my code to make the page refresh on refresh:
<script>
$(window).load(function(){
$(function()
{
$('#submit').click(function()
{
$('.container').show();
$('#login').hide();
$.cookie('shown', true);
});
if ($.cookie('shown')) {
$('#submit').click()
}
});
});
</script>
Here is a sample ajax form submit script.
// this is the id of the submit button
$("#submit").click(function() {
var url = "path/to/your/script.php"; // the script where you handle the form input.
$.ajax({
type: "POST",
url: url,
data: $("#idForm").serialize(), // serializes the form's elements.
success: function(data)
{
alert(data); // show response from the php script.
}
});
return false; // avoid to execute the actual submit of the form.
});
Presuming that you're using Ajax to change your page states, why not look at something like History.js?
I'm designing a rather long form that will auto-save every couple minutes (i.e., using Ajax, the form data will be inserted or updated into the MySQL database). However, if the user decides to exit the page before submitting the form, I want to make sure I delete the row that was inserted into the database. This is easily do-able if the user simply clicks another link or the form's Cancel button. But I'm concerned about what happens when the user: 1) closes the page, 2) reloads the page, or 3) hits the browser's back (or forward) button. I know how to use the unload event to create a confirmation dialog asking the user to confirm they want to leave the page. But what I don't know is how to make an Ajax call (to delete that row from the database) if the user clicks OK ("Press OK to Continue"). Is there any way to call a function if a user clicks the OK button during the unload event?
window.onbeforeunload = function() {
if ($('#changes_made').val() == 'yes') //if user (partially) filled out the form
{
return "Are you sure?"
if (/*user clicks OK */) //What should the if statement evaluate here?
{
//make Ajax call
}
}
};
$(document).ready(function() {
$(':input',document.myForm).bind("change", function() {
setConfirmUnload(true);
}); // Prevent accidental navigation away
});
function setConfirmUnload(on) {
// To avoid IE7 and prior jQuery version issues
// we are directly using window.onbeforeunload event
window.onbeforeunload = (on) ? unloadMessage : null;
}
function unloadMessage() {
if(Confirm('You have entered new data on this page. If you navigate away from this page without first saving your data, the changes will be lost.')) {
$.ajax({
type: "POST",
url: "some.php",
data: "name=John&location=Boston",
success: function(msg){
alert( "Data Saved: " + msg );
}
});
}
}
Make sure you have upgraded version of jQuery. jQuery version 1.3.2 had a bug:
Ticket #4418: beforeunload doenst work correctly
Or use native function:
window.onbeforeunload = function() {....}