i have this js that requests the user to be logged out whenever they close the tab/window and cancels that request when the user does an window.onload shortly after a few second to distinguish between refresh and exiting the tab/window. it works perfectly when on Chrome but when it comes to mozilla the window.onunload event gets triggered but does not trigger the ajax call. below are my codes
window.onunload = function(){
setCookie('tabs', parseInt(getCookie('tabs')) - 1, 99999)
if(parseInt(getCookie('tabs')) < 1)
{
if (window.localStorage) {
window.localStorage['myUnloadEventFlag']=new Date().getTime();
}
requestSessionTimeout();
}
};
window.onload = function(){
setCookie('tabs', parseInt(getCookie('tabs')) + 1, 99999)
if(parseInt(getCookie('tabs')) < 2 ){
if (window.localStorage) {
var t0 = Number(window.localStorage['myUnloadEventFlag']);
if (isNaN(t0)){
t0=0;
}
var t1=new Date().getTime();
var duration=t1-t0;
if (duration<10*1000) {
cancelSessionTimeoutRequest(); // asynchronous AJAX call
}
}
}
};
and here are the cancelSessionTimeoutRequest and requestSessionTimeout definitions
function requestSessionTimeout(){
var header = ''
var token = ''
$.ajax({
url:antiCsrfHost +"/addSessionToDeleteQueue",
type:"POST",
aysnc:false,
contentType: 'application/json; charset=utf-8',
success:function(d){
}
})
}
function cancelSessionTimeoutRequest(){
$.ajax({
type: 'GET',
url: antiCsrfHost + '/csrf' ,
xhrFields: true,
contentType: 'application/json; charset=utf-8',
aysnc:true,
success: function (data) {
$.ajax({
url:antiCsrfHost +"/removeSessionToDeleteQueue",
type:"POST",
data : null,
dataType : 'json',
aysnc:true,
contentType: 'application/json; charset=utf-8',
beforeSend : function(xhr){
xhr.setRequestHeader(data.headerName, data.token);
},
success:function(d){
}
})
}
})
}
Hey your code working on Google Chrome but not working on Mozilla....
Solution 1:
Means there may be a cache problem first you clear cache then relaoad your webpage
Or
Solution 2:
event.preventDefault();
Write this code inside windowonload function
Related
I am working on a real estate web app in ASP.NET MVC. My problem is in my Reservations section.
I am using AJAX to post in a Controller which returns a JSONResult. Here is my code:
Controller
[HttpPost]
public JsonResult SubmitReservation(ReservationViewModel rvm)
{
return Json(rvm, JsonRequestBehavior.AllowGet);
}
Main AJAX
var rvm = new ReservationViewModel();
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
$.ajax({
url: "/Reservations/SubmitReservation",
data: JSON.stringify(rvm),
type: "POST",
dataType: "json",
contentType: "application/json",
success: function () {
console.log(clientData);
console.log(siteData);
console.log(unitData);
//Assignment of data to different output fields
//Client Data
$('#clientName').html(clientData.FullName);
$('#clientAddress').html(clientData.Residence);
$('#clientContact').html(clientData.ContactNumber);
//Site Data
$('#devSite').html(siteData.SiteName);
$('#devLoc').html(siteData.Location);
////House Unit Data
$('#unitBlock').html(unitData.Block);
$('#unitLot').html(unitData.Lot);
$('#modelName').html(unitData.ModelName);
$('#modelType').html(unitData.TypeName);
$('#lotArea').html(unitData.LotArea);
$('#floorArea').html(unitData.FloorArea);
$('#unitBedrooms').html(unitData.NumberOfBedrooms);
$('#unitBathrooms').html(unitData.NumberOfBathrooms);
$('#unitPrice').html(unitData.Price);
$('#reservationDetails').show();
alert("Success!");
},
error: function (err) {
alert("Error: " + err);
}
});
Functions for fetching data
function getBuyerInfo(id, cb) {
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getSiteInfo(id, cb) {
$.ajax({
url: "/Sites/GetSiteByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function getUnitInfo(id, cb) {
$.ajax({
url: "/HouseUnits/GetUnitByID/" + id,
type: "GET",
contentType: "application/json",
dataType: "json",
success: cb
});
}
function ReservationViewModel() {
var buyerId = $('#SelectedBuyerID').val();
var siteId = $('#SelectedSiteID').val();
var unitId = $('#SelectedUnitID').val();
var rsvDate = $('#ReservationDate').val();
var me = this;
me.ReservationDate = rsvDate;
me.SelectedBuyerID = buyerId;
me.SelectedSiteID = siteId;
me.SelectedUnitID = unitId;
}
function clientCallback(result) {
clientInfo = result;
clientData = clientInfo[0];
}
function siteCallback(result) {
siteInfo = result;
siteData = siteInfo[0];
}
function unitCallback(result) {
unitInfo = result;
unitData = unitInfo[0];
}
The whole code WORKS well for the second time. However, it does not work for the FIRST time. When I refresh the page and I hit Create, it returns undefined. But when I hit that button again without refreshing the page, it works well. Can somebody explain to me this one? Why does AJAX returns undefined at first but not at succeeding calls? Thanks in advance.
You are calling several ajax requests in your code, inside these functions:
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
and finally $.ajax({...}) after them, where you use results from pervious ajax calls.
Your problem is that the first ajax calls do not necessarily return results before your start the last ajax because they are all async. You have to make sure you get three responds before calling the last ajax. Use promises or jQuery when, like this:
var rvm = new ReservationViewModel();
$.when(
$.ajax({
url: "/BuyersInformation/GetBuyerByID/" + rvm.SelectedBuyerID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/Sites/GetSiteByID/" + rvm.SelectedSiteID,
type: "GET",
contentType: "application/json",
dataType: "json"
}),
$.ajax({
url: "/HouseUnits/GetUnitByID/" + rvm.SelectedUnitID,
type: "GET",
contentType: "application/json",
dataType: "json"
})
).done(function ( clientResponse, siteResponse, unitResponse ) {
clientInfo = clientResponse;
clientData = clientInfo[0];
siteInfo = siteResponse;
siteData = siteInfo[0];
unitInfo = unitResponse;
unitData = unitInfo[0];
$.ajax({ ... }) // your last ajax call
});
AJAX calls are asynchronous. You last ajax call will not wait until your above 3 ajax calls finishes its work. so you can make use of $.when and .done here as below..
$.when(
getBuyerInfo(rvm.SelectedBuyerID, clientCallback);
getSiteInfo(rvm.SelectedSiteID, siteCallback);
getUnitInfo(rvm.SelectedUnitID, unitCallback);
).done(
$.ajax({
//Ajax part
})
);
I'm using the jquery countdown timer plugin (http://keith-wood.name/countdown.html) to display the time. I'm calling a function to add more time on callback event 'onTick'. When the time countdowns to 00:00:00, the function will make an ajax call to add extra time. It's working fine but every time the timer equals 00, ajax is making multiple calls (>15). How can I make it to send just one call? I tried doing async: false but still it's making multiple calls. Thank you.
$(this).countdown({ until: time, format: 'HMS', onTick: addExtraTime });
function addExtraTime() {
if ($.countdown.periodsToSeconds(periods) === 00) {
var postValue = { ID: id }
if (!ajaxLoading) {
ajaxLoading = true;
$.ajax({
url: "#Url.Action("AddExtraTime", "Home")",
type: 'post',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(postValue),
success: function() {
// show success
},
error: function(data) {
// show error
}
});
ajaxLoading = false;
}
}
}
You have a variable, ajaxLoading, that you use to determine if an Ajax request is in flight but you set it to false immediately after calling $.ajax() instead of when you get a response. Set it to false inside your success and error handlers instead.
You're setting ajaxLoading = false; even when the ajax request is still being done, set it to false after the request is completed
if (!ajaxLoading) {
ajaxLoading = true;
$.ajax({
url: "#Url.Action("AddExtraTime", "Home")",
type: 'post',
dataType: 'json',
contentType: "application/json",
data: JSON.stringify(postValue),
success: function() {
// show success
},
error: function(data) {
// show error
}
complete: function(){
ajaxLoading = false;
}
});
//ajaxLoading = false;
}
I am using Angular Js with JQuery in a noodles way. See my code below.
Code
app.controller('ClassController', function ($scope) {
$scope.ShowHideNoRecords = false;
var credentials = new Object();
credentials.SourceName = "###";
credentials.SourcePassword = "###";
credentials.UserName = "###";
credentials.UserPassword = "##";
credentials.SiteId = [-99];
var locationIds = [1];
var startDate = Date.today();
var endDate = startDate;
var dto = { credentials: credentials, startDate: startDate, endDate: endDate, locationId: locationIds };
$.ajax({
type: "POST",
url: 'MbApiConnector.asmx/GetAllClasses',
data: JSON.stringify(dto),
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
success: function (response) {
alert(response.d);
},
complete: function (msg) {
$scope.$apply(function () {
$scope.Classes = JSON.parse(JSON.parse(msg.responseText).d);
if ($scope.Classes.length > 0) {
$scope.checkin = function (id) {
dto = { credentials: credentials, classId: id };
$.ajax({
type: "POST",
url: 'MbApiConnector.asmx/Checkin',
data: JSON.stringify(dto),
contentType: "application/json; charset=utf-8",
dataType: "jsonp",
complete: function (msg) {
alert(msg.responseText);
}
});
}
}
else {
$scope.ShowHideNoRecords = true;
}
});
}
});
});
Everything is working fine with this code. I knew its a bad idea mixing the two but my app was already developed in Jquery Ajax and we are upgrading with Angular JS but with lesser changes. So I came up with this solution.
Anyways, my issues is that jquery ajax success function is not get called. I am able to receive data from the webservice , but inside the complete method, as you can see in the code above.
Can you explain me why its behaving so?
May be Jquery fails to parse it as the result may not be in JSON format, try to find the error using error callback function. You could try with dataType : 'json'.
error: function (err) { alert(err) }
I'm getting reports that a website I developed is not functioning as it should in IE 9 and IE 10. The problem occurs when attempting to submit a form:
$("form[name='signIn']").submit(function(e) {
var formData = new FormData($(this)[0]);
e.preventDefault();
$( "#return_status_sign_in" ).empty();
$.ajax({
url: "<?= SITE_URL ?>account/login",
type: "POST",
data: formData,
async: false,
success: function (msg) {
$('#return_status_sign_in').append(msg);
},
cache: false,
contentType: false,
processData: false
});
});
The above submits the form via AJAX in all other browsers and works perfectly. However, in IE 9 and 10, the page refreshes and the POST data appears as get variables in the URL. How come is this happening? Could it be that e.preventDefault(); is not triggering? If so, what's the alternative to that?
As I stated in my comment, IE 9 uses the 'xdomainrequest' object to make cross domain requests and 'xmlhttprequest' for other requests. Below is a sample of code that I use to work around this issue. 'xdomainrequests' only send 'plain/text.' They cannot send JSON:
if ('XDomainRequest' in window && window.XDomainRequest !== null) {
var xdr = new XDomainRequest(),
data = JSON.stringify(jsonData);
xdr.open('POST', 'http://www.yourendpoint.com');
xdr.onload = function() {
// When data is recieved
};
// All of this below have to be present
xdr.onprogress = function() {};
xdr.ontimeout = function() {};
xdr.onerror = function() {};
// Send the request. If you do a post, this is how you send data
xdr.send(data);
} else {
$.ajax({
url: 'http://www.yourendpoint.com',
type: 'POST',
dataType: 'json',
data: {
// your data to send
},
cache: true
})
.done(function(data) {
// When done
})
.fail(function(data) {
// When fail
});
}
i run the ajax request with async set to false inside the loop, and it stopped when the counter at 2. here is the script
var x = 0;
for(i=0; i<10; i++){
$.ajax({
async: false,
global: isGlobal,
type: 'POST',
url: url,
dataType: 'json',
data: JSON.stringify(body),
headers: {'Content-type':'application/json', 'Accept':'application/json'},
success: function(result){
x = result.something.value;
},
error: function(){
callback(false);
}
});
console.log(x); // debug x value
}
any idea why this is not working correctly?
PS: the url is cross domain
i solve this problem my self. here is the working script, in case you, visitor, have the same problem as mine.
var theList = [/*LIST GOES HERE*/];
var yourGlobalVar = '';
i = 0;
(function gcr(){
var body = {
ID: theList[i].ID
};
$.ajax({
async: false,
global: isGlobal,
type: 'POST',
url: url,
dataType: 'json',
data: JSON.stringify(body),
headers: {'Content-type':'application/json', 'Accept':'application/json'},
success: function(result){
yourGlobalVar += result.anything.value;
if(i < theList.length - 1){
// wait for the response then call itself
i++;
gcr();
}
}
});
})();