process a page on UnLoad? - javascript

I need for a php file to process when the user click a link/go back/exits a page. Its part of a saving user info process. if i do a jquery unload how would I fire the php file to load and process.
jQuery(window).bind("unload", function() {
// what should i add?
});

$(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() {....}

I'm guessing a synchronous AJAX call might work.
$.ajax({
async: true,
url: '/foo/',
success: function(data) {
// Finished.
}
});
Of course, keep in mind there's no guarantee any of this will ever happen. My browser may crash. My computer may even power down. And of course I may disable JavaScript. So you'll definitely need a server-side way of handling this in case the convenient JavaScript technique doesn't actually work.

You should use the beforeunload event. You can fire a synchronised ajax request in there.
$(window).bind('beforeunload', function() {
$.ajax({
url: 'foo',
async: false,
// ...
});
});
Be aware that onbeforeunload is not supported by some older browsers. Even if this technique works, I'm not sure how long you can (should?) block this event. Would be a pretty bad user experience if that request would block a few seconds.
A good trade-off is probably to tell the user that something has changed what was not saved yet. Do this with a few boolean checks and finally return a string value in the onbeforeunload request. The browser will then gracefully ask the user if he really wants to leave your site, also showing the string you provided.

Related

ajax post working on chrome but not working on firefox and safari

I've encountered an issue where a jquery ajax post method works on chrome but does not work on safari or firefox. I've looked through all the other similar posts and they don't solve the problem. Whenever I run the ajax code, it just returns the entire HTML of the page the form is found on.
Here's my javascript:
$("#piece-form").submit(function(e)
{
e.preventDefault();
// gets which submit button was clicked
var selectedButton = $(this).find("input[type=submit]:focus");
var url = selectedButton.attr("name");
var formData = new FormData(this);
$.ajax
(
{
type: "POST",
url: url,
data: formData,
cache: false,
processData: false,
success: function(data)
{
if(data == "Success!")
{
$("#error-box").css("display", "none");
$("#success-box").html("Success! Publishing...");
$("#success-box").css("display", "block");
}
else
{
$("#success-box").css("display", "none");
$("#error-box").html(data);
$("#error-box").css("display", "block");
}
}
}
)
});
No matter the content of the PHP file the function points to, it doesn't work as planned. I've tried making a PHP file with a single echo line and I still run into the same problem. I've implemented an error block in the ajax as well and it returns nothing. I also don't receive an error in the console other than: "Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user’s experience. For more help http://xhr.spec.whatwg.org/" in Firefox
Edit: I've added contentType:false and it still isn't functioning properly on Firefox and Safari
Have you tried wrap your code in document ready?
Also as much as i know now it is correct to use on():
$( document ).ready(function() {
$("#piece-form").on('submit', function(e){
//your main code here
});
});
For now it does not looks like there would be any issue. ..
I finally found the answer.
The error is in the following line of code:
var selectedButton = $(this).find("input[type=submit]:focus");
var url = selectedButton.attr("name");
For some reason, Firefox and Safari don't properly get the value of "selectedButton" (although Chrome does) resulting in the url variable being incorrectly set. In order to circumvent this, I did the following:
$(".piece-button").click(function (){
url = $(this).attr("name");
})
I needed the submittedButton method because I had two submit buttons for the form and was trying to find which one was clicked. This alternate method does that and is transferrable across all three browsers I have tested. This may not be an optimal solution to the two button submit issue but it worked for me and now the ajax works without a hitch.
Though you have got the solution but from interest I am sharing mine as I have just encountered same problem and got the workaround by adding event.preventDefault(); after success. Example code is given
$(document).ready(function() {
$('form').on('submit', function(event) {
$.ajax({
data: {
name: $('#nameInput').val(),
email: $('#emailInput').val()
},
type: 'POST',
url: '/post_for_db',
success: function(data) {
console.log(data)
$("body").html(data);
// This will navigate to your preferred location
document.location = '/render_table_from_db';
},
event.preventDefault(); // solution is this for me
});
});

$(window).on('unload', ... prevents url change

I am trying to execute a function when the user tries to change url, close tab etc. The issue is that when user refreshes/clicks on hyperlink/changes url, the url is updated but the page remains exactly the same.
The problem is especially severe with latest Firefox (did not notice it before for some reason). Chromium on the other hand will wait a few seconds before closing the tab, giving it an awkward, laggy feeling.
The code as it is:
$(window).on('unload', function() {
$.ajax({
type: 'POST',
url: 'ajax/whattodo.php',
async: false,
data: {
method: 'iquit',
exitdata1: exitdata1,
exitdata2: exitdata2
}
});
});
If I remove "async:false" the problem is no longer there. But neither are functions executed. What to do?
The page not redirecting is especially annoying, and confusing for the user.

Cancel Autocomplete request when space is entered, and fire it only when the user stops typing

I tried searching all over the Internet and found no simple answer, which I believe exists for two problems I'm having. My Jquery UI Autocomplete is below:
$('#moviename').autocomplete({
// URL is parsed by my framework
source:"<?=URL::route('MovieAutocomplete')?>",
minLength:2,
dataType:"json",
select:function(event,ui){
// set artist id
$('#movieid').val(ui.item.id);
$('#moviename').prop('disabled',true);
$('#moviedetails').prop('disabled',false);
$('#movieclear').html('Clear');
$('#moviehint').toggle();
}
});
This code works. However, I am looking at the performance. I have two questions:
My controller cancels the request if it sees a blank term. However, I would like to check this condition even before the request is sent. I have played with beforeSend, but it doesn't work somehow. Can someone help me accomplish this one?
I would also like to fire the AJAX request only when the user stops typing, say give it a time of 500ms to wait before it can send request to the server. Is there any easy way to do this? I am guessing "call autocomplete inside a keyup event which will be bound to the field I want". Please help me.
It would be great if someone can look into this one for me.
I recently have been working with the jQuery UI autocomplete. This is the logic I used & it works well.
onKeydownMethod: function(event) {
if ($(this).val().length >= App.autocompleteMinLength)
{
if ($(this).val().length >= YOUR_MIN_LENGTH) {
$('selector').autocomplete({
minLength: YOUR_MIN_LENGTH, // min number of chars before request is made.
delay: YOUR_DELAY, // mum of miliseconds to wait before making request.
source: function(request, callback) {
$.ajax({
type: 'get',
contentType: 'application/json',
url: 'YOUR_URL' + ANY_PARAMS,
dataType: 'json',
timeout: 50000
}).done(function(response) {
callback(response); // I used a callback to send data back to the parent function. Handle the response however you like here.
}).fail(function(error) {
switch (error.statusText)
{
case 'OK':
// handle response.
break;
default:
// handle response
break;
}
});
}
});
}
}

Javascript / Ajax Redirect Issues

Very new to code in general so apologies in advance if i dont explain myself properly,
But I have a form, that actions a piece of JavaScript on submit.
If the form validates successfully then it calls a php file for server side processing.
Once the server side processing is complete the php file returns some data (a url) which the user is then redirected to (client side)
This all works fine on desktop (chrome, IE, FF) and via modern mobile devices, however the redirect is not working on some devices (blackberry for one), and a i assume other older devices. Instead of the redirect URL going straight into the address bar, it is being placed after the url of the original page - as such causing the user to be redirected to a page that of course doesnt exist.
Below is the script that is called on submit. Again apologies if none of the above makes sense...I am very new to all this:
$(function () {
$('#wait').hide();
$('form#leads_form').on('submit', function (e) {
if (validateFrm()) {
$(":submit", this).attr("disabled", true);
$('#wait').show();
var jqxhr = $.ajax({
type: 'post',
timeout: 300000,
url: 'sell-save-leads.php',
cache: false,
data: $('form').serialize(),
success: function (data) {
//alert("Submit success: " + data);
window.top.location.href = data;
}
});
} else {
//alert("validation errors");
$('#wait').hide();
}
e.preventDefault();
});
});
If anyone is able to help or offer some advice that would be great.
As your form is located in an iFrame I suggest you to use this jQuery plugin to send messages from an iframe to its parent:
http://benalman.com/projects/jquery-postmessage-plugin/
With this you could send a message from inside your success function, containing the new url, and catch it in the parent window.
You can also use
window.top.location.assign(data);
Ref: https://developer.mozilla.org/en-US/docs/Web/API/Window.location

JQuery to load Javascript file dynamically

I have a very large javascript file I would like to load only if the user clicks on a certain button. I am using jQuery as my framework. Is there a built-in method or plugin that will help me do this?
Some more detail:
I have a "Add Comment" button that should load the TinyMCE javascript file (I've boiled all the TinyMCE stuff down to a single JS file), then call tinyMCE.init(...).
I don't want to load this at the initial page load because not everyone will click "Add Comment".
I understand I can just do:
$("#addComment").click(function(e) { document.write("<script...") });
but is there a better/encapsulated way?
Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.
You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:
$('#add_comment').click(function() {
if(typeof TinyMCE == "undefined") {
$.getScript('tinymce.js', function() {
TinyMCE.init();
});
}
});
Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)
I realize I am a little late here, (5 years or so), but I think there is a better answer than the accepted one as follows:
$("#addComment").click(function() {
if(typeof TinyMCE === "undefined") {
$.ajax({
url: "tinymce.js",
dataType: "script",
cache: true,
success: function() {
TinyMCE.init();
}
});
}
});
The getScript() function actually prevents browser caching. If you run a trace you will see the script is loaded with a URL that includes a timestamp parameter:
http://www.yoursite.com/js/tinymce.js?_=1399055841840
If a user clicks the #addComment link multiple times, tinymce.js will be re-loaded from a differently timestampped URL. This defeats the purpose of browser caching.
===
Alternatively, in the getScript() documentation there is a some sample code that demonstrates how to enable caching by creating a custom cachedScript() function as follows:
jQuery.cachedScript = function( url, options ) {
// Allow user to set any option except for dataType, cache, and url
options = $.extend( options || {}, {
dataType: "script",
cache: true,
url: url
});
// Use $.ajax() since it is more flexible than $.getScript
// Return the jqXHR object so we can chain callbacks
return jQuery.ajax( options );
};
// Usage
$.cachedScript( "ajax/test.js" ).done(function( script, textStatus ) {
console.log( textStatus );
});
===
Or, if you want to disable caching globally, you can do so using ajaxSetup() as follows:
$.ajaxSetup({
cache: true
});

Categories