onbeforeunload doesn't fire - javascript

I have an onbeforeunload event which should fire when I leave the page and run the code I have attached to that event. I have placed this within the scripts tag of the cshtml in my page, so in theory it should only fire if I am on that particular page and move off it(my understanding of the event could be incorrect). However when I go to another page the onbeforeunload event does not seem to want to fire. I have tried setting a breakpoint on it but does not seem to hit it and am not getting any errors on my console in firebug.
I have looked at this post which one of the posters mentioned using this event to detect a page change
Best way to detect when a user leaves a web page?
<script type="text/javascript">
$(document).ready(function () {
window.onbeforeunload = SaveDashboard;
});
function SaveDashboard(){
var gridArray = _.map($('.grid-stack .grid-stack-item:visible'), function (el) {
el = $(el);
var gridID = el.find('.grid-stack-item-content.ui-draggable-handle').first().attr('id');
var node = el.data('_gridstack_node');
return {
id: gridID,
x: node.x,
y: node.y,
width: node.width,
height: node.height
};
});
$.ajax({
url: 'Dashboard/EditWidgets/',
type: 'PUT',
data: {
widget: gridArray
},
success: function (dataset) {
},
failure: function (xhr, error) {
console.log(xhr)
console.log(error)
},
});
}
</script>

you should return a string in the onbeforeunload handler. if you don't return anything, the event won't fire your handler. the text you have to return is the text that will be placed in the prompt the browser will open asking if the user really wants to leave the page.

Related

Issue with ajax success function

Inside an iframe I have the following script:
$("a").on("click", function (e) {
e.preventDefault();
if (e.target.href) {
let link = e.target.href;
$.ajax({
url: "/newOrigin",
data: {
"link": link
},
type: "POST",
success: function (response) {
parent.document.getElementById("oframe").srcdoc = response.site;
parent.document.getElementById("oLink").href = link;
},
error: function (error) {
console.log(error);
}
});
}
});
Which does not work. The prevent default doesnt do it's job, meaning the event itself isnt being triggered. I believe the issue is with the second line in the ajax success function, since the code below works perfectly fine (srcdoc changes and console is logged).
$("a").on("click", function (e) {
e.preventDefault();
if (e.target.href) {
let link = e.target.href;
$.ajax({
url: "/newOrigin",
data: {
"link": link
},
type: "POST",
success: function (response) {
parent.document.getElementById("oframe").srcdoc = response.site;
console.log("Hello");
},
error: function (error) {
console.log(error);
}
});
}
});
oLink is the id of an a tag element (hyperlink) and oframe is the id of another iframe inside the parent of the iframe where this code is.
Does anyone know why this is happening?
EDIT: The site has two iframes and each have a title above them(with each title having an href of the page displayed in each iframe). When a link is clicked in the first iframe, an ajax request is sent with the link and the response has the html of that page which is sent to be displayed in the 2nd iframe (1st line in success function). I now want to change the href of the words above the 2nd iframe to be the link of the link clicked in the 1st iframe. So the two titles and two iframes are inside the same parent component (same level) and the script is inside the first iframe.
The html used is base.html + index.html from here (iframes and titles in index.html): https://github.com/MohamedMoustafaNUIG/AnnotatorVM/tree/master/app/templates
EDIT2: Apparently, the success function is isolated from the rest of the code, meaning it doesnt have access to the "link" variable. I solved this by returning the link in the response and accessing it from there. But the event is still not triggering :(

jQuery onclick event not working upon making multiple ajax requests

I am making few ajax requests in my jQuery file. On success of these jQuery requests, I wrote few on click events which are not working.
This is my code
$(document).ready(function (){
$.ajax ({
type: "POST",
url: 'myServlet',
async: false,
success: function (response) {
id = parseInt(response);
setOutputEvents();
}
});
function setOutputEvents() {
for (var queryNumber = 0; queryNumber <= id; queryNumber++) {
$.ajax({
type: "POST",
url: 'myOtherServlet',
data: {queryNumber: queryNumber},
success: success,
async: false
});
var success = function (response) {
//some code here
generateTable();
}
}
}
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
});
I understand making multiple ajax requests is a bad programming practice but what could be the reason for on click events not getting triggered?
These are the onclick events which are not working.
function pagination(){
$(".class").click(function(event) {
alert();
});
}
$("#me").on("click", function(){
alert("me is triggered");
});
I am using Google Chrome Version 39.0.2171.95 on Windows 7.
Please do let me know if any further information is necessary.
Since you use ajax to load even the initial content it seems, .class / #me html elements likely do not exist on initial page load of the DOM. As you didn't post html, i'm guessing this is the case.
Thus, you need to use a delegated event click handler to respond to it
so, you would change
$("#me").on("click", function(){
to
$(document).on("click", "#me", function(){
and so forth to link it to the parent element that does exist, the document itself.
This would work:
$(".class").on("click", function(){
alert("me is triggered");
});
function generateTable () {
//some code here
pagination();
}
function pagination(){
$(".class").trigger("click");
}
Some notes:
Event handler must be registered before triggering click.
Triggered click selector must match the class which has the click event registered.
Functions must be defined before the usage.

Open javascript popup after jquery response

I have this simple javascript function:
<script type="text/javascript">
$(document).ready(function () {
$(document).on('click', '.check', function(){
$.post('/index.php',
{
article: '1'
},
function(data, textStatus)
{
window.open('https://google.com');
});
});
});
</script>
<button class=".check">Check</buttton>
Although the click is user initiated but the popup is getting blocked by browsers. How to avoid this?
There's no way to unblock it through code.
Most browsers feel popups are very interrupting and that's the reason they block it.
You can only find out if the popup is being blocked and promptly notify the user to unblock it.
var wind = window.open('https://google.com');
if(!wind || wind.closed || typeof wind.closed=='undefined')
{
//POPUP BLOCKED
alert("please enable popups");
}
Your pop-up should be triggered directly by user interaction. But instead it's in an AJAX callback.
So, to prevent the block you should open the pop-up within the click handler. Then make the post..
EDIT: A tricky method would be to open the popup directly, then make the request and finally redirect the popup to the result URL:
$(document).on('click', '.check', function(){
var popup = window.open('/loading.html', 'popup');
$.post('/index.php', { article: '1' },
function (data, textStatus) {
popup.location.href = 'http://new-url';
});
});
You can try this trick:
function(data, textStatus)
{
var anchor = $( '<a/>', {href:'https://google.com',target:'_blank'} ).text( 'TEST' );
$('body').append( anchor );
$('body').find( 'a' ).last()[0].click();
anchor.remove();
};
JS FIDDLE DEMO

jQuery: Can't retrieve an attribute of a dynamically created DOM element

Here's the situation: I'm writing a simple AJAX application that performs CRUD functions. When the user double clicks on a particular element, the element changes into a text box so that they can edit inline. When the text box loses focus (code for which is below), the value of the textbox gets POSTed to a PHP script that updates the database.
All is groovy except for one thing. When I create a new record, which gets popped onto the top of the list with AJAX, I can't edit that record without refreshing the page. I mean, the edit looks like it's been committed, but when you refresh, it reverts back to the original. After refreshing, there are no issues.
To boil it down: When I try to run the following code on newly created rows in my table (both in the database and on the page), the edit appears to be made on the page, but never makes it to the database.
//Make changes on FOCUSOUT
$('#editable').live('focusout', function(){
var parentListItem = $(this).parents('li');
var theText = $(this).val();
var parentListItemID = parentListItem.parents('ul').attr('id');
$(this).remove();
parentListItem.html(theText);
parentListItem.removeClass('beingEdited');
$.post("databasefuncs.php?func=edit", { postedMessage: parentListItemID, fullTextContent: theText },
function(result){
if(result == 1) {
parentListItem.parents('ul').animate({ backgroundColor: 'blue' }, 500).animate({ backgroundColor: '#eeeeee' }, 500);
} else {
alert(result);
}
});
});
I suppose you are not binding the event to the new DOM Element loaded via AJAX.
Your problem is that the post executes but the function you target (func=edit) never fires, the params you are sending after the question mark are never read by your php, you are sending a post request and wanting it to behave like a get by attaching parameters to the URL, change your request to:
$.ajax({
type: "POST",
url: "databasefuncs.php",
data: {func: "edit", postedMessage: parentListItemID, fullTextContent: theText},
success: function(data, textStatus, jqXHR) {
if(textStatus === "success") {
parentListItem.parents('ul').animate({ backgroundColor: 'blue' }, 500).animate({ backgroundColor: '#eeeeee' }, 500);
}
else {
alert(textStatus);
}
}
});
Now in your PHP you have $_POST["func"] = "edit";
Hope this is clear and it helps. Cheers.

jQuery.ajax not working in IE7/8

Something in my script is breaking IE.
I'm looking on a collection of links with a class, and hijacking the URL's.
Clicking a link will animate the height and reveal a message. It also
does an ajax request to mark the message as read.
However, in IE it simply goes to the URL instead of staying on the page and processing the http request.
$('.message .subject .subject_link').click(function(e) {
toggle_message(e)
return false;
});
function toggle_message(m) {
var link = m.target;
var parent = $(link).parent().parent();
console.log(link.href);
$.ajaxSetup({
url: link.href,
dataType: 'json',
timeout: 63000,
type: 'GET',
cache: false
});
if($(parent).hasClass('unread')) {
$(parent).addClass('read').removeClass('unread');
$.ajax({
complete: function(r, textStatus) {
console.log(r.responseText)
}
});
}
if($(parent).find('.body_wrapper').hasClass('collapsed')) {
$(parent).find('.body_wrapper').addClass('expanded').removeClass('collapsed');
$(parent).find('.body_wrapper').animate({
height: 'toggle'
})
} else {
$(parent).find('.body_wrapper').addClass('collapsed').removeClass('expanded');
$(parent).find('.body_wrapper').animate({
height: 'toggle'
})
}
}
any ideas what's causing this issue?
http://support.cooper.krd-design.net/
tester: 12345 if you want to review the page
Thanks
Rich
Adding
e.preventDefault();
before toggle_message in the first function should work, although return false should as well.
I don't have access to IE right now but I think you could try preventing the default click event to fire in your click()-function like so:
$('.message .subject .subject_link').click(function(e) {
toggle_message(e)
e.preventDefault();
});
More on .preventDefault() here: http://api.jquery.com/event.preventDefault/

Categories