Ajax method does not fire on initial page load - javascript

Note: Please see edit at the bottom after reading this question.
This issue is only happening in IE 11, and only started occurring after a recent Windows update. There were 5 updates, one of which was specific to IE, so I uninstalled that one. However, the issue still exists. Before I consider rolling back the remaining updates, is there something inherently wrong in my code? The following is inside the document ready function:
$('#leftmenu>li').click(function () {
var clickedId = this.id;
$.ajax({
url: "Session/Index/",
cache: false,
success: function (result) {
if (result.length > 0)
{
performListItemAction(clickedId);
}
else
{
window.location.href = 'Home/Index/'
}
}
});
});
And the following is the performListItemAction method (a separate function not in document.ready):
function performListItemAction(item)
{
alert("clicked");
$(".tabui").each(function ()
{
$(this).hide();
});
$(".listitem").each(function ()
{
$(this).css("background", "transparent");
});
$(document.getElementById(item)).css("background-color", "#C8C8C8");
var targetId = $(document.getElementById(item)).data('target');
var target = $(document.getElementById(targetId));
target.show();
}
The alert clicked never appears when this problem happens, and that is how I concluded the ajax call is not working.
A few other notes:
This issue isn't happening on Firefox.
This only happens if I directly login to the page with a direct URL. If I log in via the application's home screen, and then go to the page that uses the above javascript, the issue doesn't occur.
Thank you.
EDIT: I just now see that the same issue is now occurring in Firefox as well. It's just much less frequent.

After trial and error, I think I fixed the issue by adding a forward slash to the beginning of each of the URLs, and added the type: "POST", to the ajax call. I don't know why it was working fine before, but now this works in all my attempts.

Related

IE is not refresh after call the download function

In the jsp, I use javascript, jquery and json to call a function for download, once the the download is finished, it will return the the current page.
However the problem is although the download is complete, I can able to download and view the file. In the screen, it still show the message indicate it is downloading.
I read this post, the accepted solution mentioned to disable the cache with ajaxSetup. I read my code, I have already include it in the code, however the Internet Explorer still not return to proper page when the download finished. Is there any method I can use to solve the problem. Thank you.
function startDownload() {
$.blockUI({ message: '<h1>Downloading, please wait...</h1>' });
var i = setInterval(function() {
$.ajaxSetup({ cache: false });
$.getJSON("ThePage/downloadProgress?jsoncallback=?",function(download_token) {
if (download_token.fileDownloadToken == "finished" ) {
$.unblockUI();
clearInterval(i);
}
});
}, 1000);
}
Update
I mentioned it occurs on IE because our company is mainly using IE for the web browser. So I intend to make to code works on the IE first. Sorry for the inconvenience that I have made.

Internet Explorer issues running code if debugger closed

Yesterday I encountered an interesting issue with Internet Explorer. A script runs perfectly on Chrome, Firefox, Safari, but with Internet Explorer 11 it doesn't do anything. If I open the debugger it runs smoothly and everything is as it should, but the moment I close the debugger it stops working and I have no idea why is this. My first thought was the IE extensions, but I disabled them to no veil. I tried running in safe-mode, with admin rights, but nothing seems to work.
To summarize everything: IE - script runs ONLY while the debugger is On. No error is produced, it just doesn't work.
I would be really glad for any ideas what can I do regarding this. Thank you in advance.
--------------EDIT---------------
Here is the script that doesn't run.
for (var i = 0; i < AllStrategyGrids.length; i++) {
try {
isChange = true;
var data = $("#objectives").data("kendoGrid").select().data();
if (AllStrategyGrids[i].ID == data.uid) {
var jsonData = new Object();
jsonData.StrategicID = "1";
jsonData.ObjectiveID = $("#ObjectiveID").val();
jsonData.HeaderID = "00000000-0000-0000-0000-000000000000";
jsonData.PeriodID = "00000000-0000-0000-0000-000000000000";
jsonData.Strategic = "Please enter strategic";
jsonData.TaskStatus = "";
jsonData.TaskStatusID = "1";
jsonData.Position = "";
jsonData.Sorted = "1";
jsonData.SessionID = "00000000-0000-0000-0000-000000000000";
tmpGrid = AllStrategyGrids[i].Grid.data("kendoGrid");
var dataRows = tmpGrid.items();
var rowIndex = dataRows.index(tmpGrid.select());
$.ajax({
url: "CreateStrategy",
type: 'POST',
data:
{
strategics: jsonData,
VersionID: $("#VersionUID").val(),
index: rowIndex
},
success: function () {
tmpGrid.dataSource.read();
}
});
}
} catch (e) { }
}
Just a guess, this is likely because you have a console.log in that script and in IE the console object doesn't exist if your debugger is closed... we've all be there :)
An easy fix is the just add small shim as early on in your site as you can.. it won't do a thing on any browsers except IE and will just stop the execution error that probably blocking your other JS code from running...
<script>
if(!console)console={log:function(){}};
</script>
a more robust solution here :
'console' is undefined error for Internet Explorer
---- EDIT
Okay one thing i can see from your code is that you're going to fail silently because you've used a try catch but do nothing with it. This is going to catch any exception you are having (blocking it from reaching your window thus making it seem like you have no errors). I would perhaps alert the error message at the very least while testing (so you don't need to open Debugger) and see if anything is thrown...
I'd be suspecting your ajax request myself.. that or an undefined in IE8.. so add some logging alerts (brute force i know) to test your assumptions at certain points e.g.
alert("Reach here and data="+data);
Alternatively, i can also see that your ajax request has no callbacks for unsuccessful which might be good idea to add to your call. It might be that the success isn't calling for some reason...
$.ajax({
url: "CreateStrategy",
type: 'POST',
data:
{
strategics: jsonData,
VersionID: $("#VersionUID").val(),
index: rowIndex
},
success: function () {
tmpGrid.dataSource.read();
}
})
.fail(function() {
alert( "error" );
//handle a failed load gracefully here
})
.always(function() {
alert( "complete" );
//useful for any clean up code here
});
Final food for thought.
Since you're checking the DOM for an item, and i have no idea when this code is called but just in case its called directly AFTER a page reload..and lets assume something in IE isn't ready at 'that' point, it might be the DOM isn't ready to be queried yet? Try executing this code when the DOM is ready.. lots of ways to achieve this $.ready , setTimeout(f(){},1) or vanilla... but you get the idea..
Note: Debugging Script with the Developer Tools: MSDN
To enable script debugging for all instances of Internet Explorer, on
the Internet Options menu, click the Advanced tab. Then, under the
Browsing category, uncheck the Disable script debugging (Internet
Explorer) option, and then click OK. For the changes to take effect,
close all instances of Internet Explorer then reopen them again.

Detect Close windows event by jQuery

Could you please give me the best way to detect only window close event for all browsers by jQuery?
I mean clicking X button on the browser or window.close(), not meaning F5, form submission,
window.location or link.
I was looking for many threads but have not found the right way yet.
You can use :
$(window).unload(function() {
//do something
});
Unload() is deprecated in jQuery version 1.8, so if you use jQuery > 1.8 you can use even beforeunload instead.
The beforeunload event fires whenever the user leaves your page for any reason.
$(window).on("beforeunload", function() {
return confirm("Do you really want to close?");
});
Source Browser window close event
There is no specific event for capturing browser close event.
You can only capture on unload of the current page.
By this method, it will be effected while refreshing / navigating the current page.
Even calculating of X Y postion of the mouse event doesn't give you good result.
The unload() method was deprecated in jQuery version 1.8.
so if you are using versions older than 1.8
then use -
$(window).unload(function(){
alert("Goodbye!");
});
and if you are using 1.8 and higher
then use -
window.onbeforeunload = function() {
return "Bye now!";
};
hope this will work :-)
There is no specific event for capturing browser close event. But we can detect by the browser positions XY.
<script type="text/javascript">
$(document).ready(function() {
$(document).mousemove(function(e) {
if(e.pageY <= 5)
{
//this condition would occur when the user brings their cursor on address bar
//do something here
}
});
});
</script>
Combine the mousemove and window.onbeforeunload event :-
I used for set TimeOut for Audit Table.
$(document).ready(function () {
var checkCloseX = 0;
$(document).mousemove(function (e) {
if (e.pageY <= 5) {
checkCloseX = 1;
}
else { checkCloseX = 0; }
});
window.onbeforeunload = function (event) {
if (event) {
if (checkCloseX == 1) {
//alert('1111');
$.ajax({
type: "GET",
url: "Account/SetAuditHeaderTimeOut",
dataType: "json",
success: function (result) {
if (result != null) {
}
}
});
}
}
};
});
You can solve this problem with vanilla-Js:
Unload Basics
If you want to prompt or warn your user that they're going to close your page, you need to add code that sets .returnValue on a beforeunload event:
window.addEventListener('beforeunload', (event) => {
event.returnValue = `Are you sure you want to leave?`;
});
There's two things to remember.
Most modern browsers (Chrome 51+, Safari 9.1+ etc) will ignore what you say and just present a generic message. This prevents webpage authors from writing egregious messages, e.g., "Closing this tab will make your computer EXPLODE! đź’Ł".
Showing a prompt isn't guaranteed. Just like playing audio on the web, browsers can ignore your request if a user hasn't interacted with your page. As a user, imagine opening and closing a tab that you never switch to—the background tab should not be able to prompt you that it's closing.
Optionally Show
You can add a simple condition to control whether to prompt your user by checking something within the event handler. This is fairly basic good practice, and could work well if you're just trying to warn a user that they've not finished filling out a single static form. For example:
let formChanged = false;
myForm.addEventListener('change', () => formChanged = true);
window.addEventListener('beforeunload', (event) => {
if (formChanged) {
event.returnValue = 'You have unfinished changes!';
}
});
But if your webpage or webapp is reasonably complex, these kinds of checks can get unwieldy. Sure, you can add more and more checks, but a good abstraction layer can help you and have other benefits—which I'll get to later. 👷‍♀️
Promises
So, let's build an abstraction layer around the Promise object, which represents the future result of work- like a response from a network fetch().
The traditional way folks are taught promises is to think of them as a single operation, perhaps requiring several steps- fetch from the server, update the DOM, save to a database. However, by sharing the Promise, other code can leverage it to watch when it's finished.
Pending Work
Here's an example of keeping track of pending work. By calling addToPendingWork with a Promise—for example, one returned from fetch()—we'll control whether to warn the user that they're going to unload your page.
const pendingOps = new Set();
window.addEventListener('beforeunload', (event) => {
if (pendingOps.size) {
event.returnValue = 'There is pending work. Sure you want to leave?';
}
});
function addToPendingWork(promise) {
pendingOps.add(promise);
const cleanup = () => pendingOps.delete(promise);
promise.then(cleanup).catch(cleanup);
}
Now, all you need to do is call addToPendingWork(p) on a promise, maybe one returned from fetch(). This works well for network operations and such- they naturally return a Promise because you're blocked on something outside the webpage's control.
more detail can view in this url:
https://dev.to/chromiumdev/sure-you-want-to-leavebrowser-beforeunload-event-4eg5
Hope that can solve your problem.

Browser Window close detection

This is something that's been driving me nuts.
I'm trying to detect whether the uses closes or navigates away from a page in order to do an ajax response upon the event. I have tried almost every possible method to invoke this but no luck. The only thing I can think of is that the activate window in question was fired using: window.open() method. Could that cause any issues? What I have so far:
window.onbeforeunload = function() {
//ajax stuff here
};
However, I've noticed that this does not work after the page is fully loaded. The event fires within the first few milliseconds (if I open the window and try to close it right away) during the page load and won't work after that.
Any ideas?
I once ran into this issue, and found it worked for me only by setting async : false on the ajax, like this:
jQuery(window).bind('beforeunload', function () {
jQuery.ajax({
url: 'your.url',
async: false,
data: yourdata
timeout: 2000 // or whatever timeout in milliseconds you want
success: function(data){
// Do whatever you want
}
});
});
As Ian mentioned on the comments, it's a good idea to set a timeout to prevent the window for taking too long to close in case the request takes a while. And keep in mind it won't work in all browsers...
This also supports old versions of IE and Firefox.
window.onbeforeunload = function (e) {
var message = "Your confirmation message goes here.",
e = e || window.event;
// For IE and Firefox
if (e) {
e.returnValue = message;
}
// For Safari
return message;
};

Javascript reload() not working

I searched everywhere here to see since so many people ask this question, but no matter what, I keep getting undefined..
function remove_item(itemid) {
var window = top.location;
var host = window.host;
$.ajax({
url: "http://"+host+"/backend/remove_lockbox.php?id="+itemid,
success: function() {
$(document).ajaxStop(function(){
window.top.location.reload();
});
}
});
}
That is my code. I tried window.location.reload, host.location.reload... I tried everything and I keep getting undefined... The parent of location is always undefined whether it's window, host, window.top, ANYTHING.
Can someone PLEASE help me?
So you are doing
var window = top.location;
and than you do
window.top.location.reload();
So you are actually saying
top.location.top.location.reload();
Why would you use a variable named window when that is already defined and has a different meaning? That is bad.
If you are using frames I would expect to see something like
parent.location.reload(true);
or just a plain old window
window.location.reload(true);
try it this way, its working fine in chrome, as I know this should work fine in all modern browsers.
function remove_item(itemid) {
var host = window.location.host;
$.ajax({
url: "http://"+host+"/backend/remove_lockbox.php?id="+itemid,
success: function() {
$(document).ajaxStop(function(){
window.location.reload();
});
}
});
}
Here is the working example of window.location, window.location.host and window.location.reload.
http://jsbin.com/apemen/3

Categories

Resources