Kill Ajax Session Outside of Originating Function - javascript

I have an AJAX function I'd like to kill, but it is outside of the function. Take a look:
function waitForMsg(){
var heartbeat = $.ajax({
type: "GET",
url: "includes/push_events.php",
tryCount : 0,
retryLimit : 3,
async: true,
cache: false,
// timeout: 500,
success: function(data){
console.log(data);
if(data){
if(data.current_date_time){
updateTime(data.current_date_time);
}
if(data.color){
console.log("Receiving data");
displayAlert(data.color, data.notification_message, data.sound, data.title);
}
if(data.user_disabled){
console.log("Receiving data");
fastLogoff();
checkDisabled();
}
}
setTimeout(
waitForMsg,
5000
);
},
error: function(data){
if (data.status == 500) {
console.log("Connection Lost to Server (500)");
$.ajax(this);
} else {
console.log("Unknown Error. (Reload)");
$.ajax(this);
}
},
dataType: "json"
});
};
// Detect browser open.
$(document).ready(function(){
// window.onunload = function(){alert('closing')};
// mainmode();
$('#alertbox').click(function(){
$('#alertbox').slideUp("slow");
});
$(document).ready(function(){
$('#alertbox').click(function(){
$('#alertbox').slideUp("slow");
});
// Check focal point
var window_focus = true;
$(window).focus(function() {
window_focus = true;
console.log('Focus');
});
$(window).blur(function() {
window_focus = false;
console.log('Blur');
});
setInterval(function(){
if(window_focus == true){
console.log('in focus');
waitForMsg();
}else{
console.log('out of focus');
heartbeat.abort();
}
}, 5000);
});
});
If you notice, the ajax is outside of the document.ready. I am trying to kill the ajax calls if the user goes to a different window, then restart the calls once the return to the window. The start works, but if the user goes away from the window, it gives me the "heartbeat is not defined". Obviously this is because its outside of that function. Any work arounds?

I'd refactor a bit the code to avoid the usage of setInterval and clean up a bit the code.
You can abstract the logic in an object, let's say Request. You can add two methods to resume and stop which will handle the status of the underlying AJAX request.
var Request = function(options){
var request = this, xhr = null, aborted = false;
/* Resumes the operation.
* Starts a new request if there's none running.
*/
request.resume = function() {
aborted = false;
request.retry();
};
/* Retry loop.
*/
request.retry = function(){
if(!xhr) {
xhr = $.ajax(options).done(function(){
request.destroy();
!aborted && setTimeout(function(){
request.retry();
}, options.timeout);
});
}
};
/* Aborts the current operation.
*/
request.abort = function(){
aborted = true;
if(xhr) xhr.abort();
request.destroy();
};
/* Destroy.
*/
request.destroy = function(){
xhr = null;
};
return request;
};
Now, you can drop the setInterval.
$(function () {
var request = new Request({
type: "GET",
url: "includes/push_events.php",
timeout: 5000,
success: function(data){
/* Success handler */
},
error: function(data){
/* Error handler */
},
dataType: "json"
});
$(window).focus(function () {
request.resume();
}).blur(function () {
request.abort();
});
request.resume();
});
The Request constructor receives the $.ajax options which should contain an additional timeout parameter that specifies the delay between requests.

You need to stop further request after window.blur. restart request after window.focus.
Modified code
var setTimeoutConst;
function waitForMsg(){
if(!window_focus){
return; //this will stop further ajax request
}
var heartbeat = $.ajax({
type: "GET",
url: "includes/push_events.php",
tryCount : 0,
retryLimit : 3,
async: true,
cache: false,
// timeout: 500,
success: function(data){
console.log(data);
if(data){
if(data.current_date_time){
updateTime(data.current_date_time);
}
if(data.color){
console.log("Receiving data");
displayAlert(data.color, data.notification_message, data.sound, data.title);
}
if(data.user_disabled){
console.log("Receiving data");
fastLogoff();
checkDisabled();
}
}
setTimeoutConst= setTimeout(waitForMsg,5000);
},
error: function(data){
if (data.status == 500) {
console.log("Connection Lost to Server (500)");
// $.ajax(this);
} else {
console.log("Unknown Error. (Reload)");
//$.ajax(this);
}
setTimeoutConst= setTimeout(waitForMsg,5000); // continue sending request event if last request fail
},
dataType: "json"
});
};
var window_focus = true;
$(document).ready(function(){
$('#alertbox').click(function(){
$('#alertbox').slideUp("slow");
});
$('#alertbox').click(function(){
$('#alertbox').slideUp("slow");
});
// Check focal point
$(window).focus(function() {
if(window_focus ){return}
window_focus = true;
waitForMsg();
console.log('Focus');
});
$(window).blur(function() {
if(!window_focus ){return}
clearTimeout(setTimeoutConst);
window_focus = false;
console.log('Blur');
});
waitForMsg();
});

Related

Ajax is not aborting when stop button is clicked

I have this code, and when the stop button is clicked, I need to stop the ajax, but for some reason ajax is not aborting.
var started = false;
$(document).ready(function () {
$('#start').click(function () {
var count = $("#names").val();
var line = count.split("\n");
started = true;
line.forEach(function(value, index) {
setTimeout(
var ajaxCall = $.ajax({
url: url,
type: 'GET',
data: someData,
success: function(result) {
//some works here
}
});
$('#stop').click(function () {
ajaxCall.abort(); //abort Ajax
$('#check').attr('disabled', false);
$('#stop').attr('disabled', 'disabled');
})
}, 2000 * index);
});
});
});

How to redirect in ajax after successfully post of data

I am submitting form data using Ajax and they are successfully saved in the database and I am able to alert the response data. I now want to use the returned data as response to call another function using Ajax and pass them as parameters so that to the called function they can be used to fetch data and and display them on the web page.
The problem is that when the data have been alerted, the function I call using Ajax is not responding even when I use some functions like window.location.href, window.location.replace, window.location.reload they are not executed
Here is the sample code
submitHandler: function(form) {
/*errorHandler.hide(); */
var el = $(div);
el.block({
overlayCSS: {
backgroundColor: '#fff'
},
message: '<i class="fa fa-refresh fa-spin"></i>',
css: {
border: 'none',
color: '#333',
background: 'none'
}
});
/*Set off for database validation */
$('#name1').removeClass('has-error');
$('#name1 .help-block').empty();
$('#date1').removeClass('has-error');
$('#date1 .help-block').empty();
/*end database validation */
/*ajax options */
var options = {
/*target: '#output2', target element(s) to be updated with server response */
success: function(data, textStatus, XMLHttpRequest) {
el.unblock();
if (!data.success) {
/*append error message on the form for each control and database validation*/
console.log(data);
if (data.errors.name1) {
$('#name1').addClass('has-error');
$('#name1 .help-block').html(data.errors.name1);
}
} else {
var business_id = data.business_id;
var bnm_app_id = data.bnm_app_id;
var name = data.name;
var doc = data.doc;
alert(business_id);
alert(bnm_app_id);
alert(name);
alert(doc);
if (window.XMLHttpRequest) {
myObject = new XMLHttpRequest();
} else if (window.ActiveXObject) {
myObject = new ActiveXObject('Micrsoft.XMLHTTP');
myObject.overrideMimeType('text/xml');
}
myObject.onreadystatechange = function() {
data = myObject.responseText;
if (myObject.readyState == 4) {
//document.getElementById('step-2').innerHTML = data;
window.location.reload(true);
}
}; //specify name of function that will handle server response........
myObject.open('GET', '<?php echo base_url()."bn_application/register";?>?bnm_app_id=' + bnm_app_id + '&doc=' + doc + '&business_id=' + business_id + '&name=' + name, true);
myObject.send();
}
},
error: function(xhr, textStatus, errorThrown) {
el.unblock();
if (xhr.responseText === undefined) {
$.gritter.add({
/* (string | mandatory) the heading of the notification */
title: 'Connection timed out',
class_name: 'gritter-black'
});
} else {
var myWindow = window.open("Error", "MsgWindow", "width=900, height=400");
myWindow.document.write(xhr.responseText);
}
/*clear controls that do not need to keep its previous info */
},
url: home + 'bn_application/save_clearance_name',
/* override for form's 'action' attribute*/
data: {
name1_percent: name1_percent
},
type: 'post',
/* 'get' or 'post', override for form's 'method' attribute*/
dataType: 'json',
/* 'xml', 'script', or 'json' (expected server response type)*/
beforeSend: function() {
},
uploadProgress: function(event, position, total, percentComplete) {
},
complete: function() {
}
};
/*submit form via ajax */
$('#bn_clearance').ajaxSubmit(options);
}
If i understand you right , you need something like this ?
$.ajax({
type: "GET",
url: baseUrl + 'api/cars',
success: function (firstResponse) {
$.ajax({
type: "GET",
url: baseUrl + 'api/cars/' + firstResponse[0].Id,
success: function (secondResponse) {
window.location.href = secondResponse[0].Make;
}
});
}
});
You can use window.open function
$("button").click(function(){
$.ajax({url: "demo_test.txt", success: function(result){
$("#div1").html(result);
window.open("http://www.w3schools.com", "_self");
}});
});
You should put your redirecting url in success function of ajax. (if you are using jQuery). Because javascript runs codes asynchronously and probably your code tries to run before you get response from request.

How to save a variable to the server using jQuery

I am implementing a video conference room and I have a variable (room_status) which holds the status of the room (0 = close & 1 = open). Now this variable is only accessible my the client who clicks open-room.
I need to save the room_status variable to the server so that it can be accessed on other client's side. Here is a piece of my code:
var room_status = 0; //room closed
$('#open-room').click(function () {
// http://www.rtcmulticonnection.org/docs/open/
$.ajax({
type: 'GET',
url: "../invite",
data: {
videoconference_id: $('#meetingID').val(),
invitee_id: 1111,
status: "Accepted"
},
success: function() {
alert("success!");
},
error: function() {
alert("fail");
}
});
//room_status = 1; //room opened
rmc.open();
rmc.streams.mute({video : true});
document.getElementById("on-off-video").style.color= 'red';
});
$('#join-room').click(function () {
if(room_status) {
// http://www.rtcmulticonnection.org/docs/connect/
rmc.connect();
rmc.streams.mute({video: true});
document.getElementById("on-off-video").style.color= 'red';
} else {
console.log("Waiting for meeting organizer");
}
});
Ajax is your friend.
Here is an example from a prject of mine with jquery ui :
function prepare_ajax_button(l){
$("#button").button().click(function(event,ui){
$.ajax({type: "GET",data: {"arg1":l},url: "update_variable.php",success: function(data){
alert("Success ?!");
},error: function(data){alert("Problem ?!");}});
});
}
The page "update_variable.php" can for instance write the variable in a text file, mysql...

event.preventDefault(); only works some of the time with submit form

I am using the Mailchimp API to submit a form. The goal is to prevent the default callback provided by Mailchimp. The majority of the time event.preventDefault() is behaving as it should. Then randomly it will not work:
$(function () {
var $form = $('#mc-embedded-subscribe-form');
$('#mc-embedded-subscribe').on('click', function(event) {
if(event) event.preventDefault();
register($form);
});
});
function register($form) {
$.ajax({
type: $form.attr('method'),
url: $form.attr('action'),
data: $form.serialize(),
cache : false,
dataType : 'json',
contentType: "application/json; charset=utf-8",
error : function(err) { alert("Could not connect to the registration server. Please try again later."); },
success : function(data) {
if (data.result != "success") {
// Something went wrong, do something to notify the user. maybe alert(data.msg);
var message = data.msg
var messageSh = data.msg.substring(4);
if (data.msg == '0 - Please enter a value' || data.msg == '0 - An email address must contain a single #') {
$('#notification_container').html('<span class="alert">'+messageSh+'</span>');
} else {
$('#notification_container').html('<span class="alert">'+message+'</span>');
}
} else {
// It worked, carry on...
var message = data.msg;
$('.popup-promo-container').addClass('thanks');
$('.checkboxes, #mc_embed_signup_scroll').addClass('hidden');
$('.complete-promo').html(message).removeClass('hidden');
setTimeout(function() {
document.querySelector('.popup-promo').style.display = "none";
},20000);
}
}
});
}
Try
take off ready function.
remove if on event
Code:
var $form = $('#mc-embedded-subscribe-form');
$('#mc-embedded-subscribe').on('click', function(event) {
event.preventDefault();
register($form);
});

jQuery Ajax Firing success before beforesend on cordova iOS app

The following excerpt changes the html of the login button until the response is received from the server.
When testing on my iPhone in an app build with Cordova. The alert is fired before the html of the login button has been updated. In a desktop browser it works as expected.
I've tried setting the cache and async to false but it makes no difference.
I can't think what else to try other than different ajax libraries?
Is there a better library to use for AJAX with cordova?
$.ajax({
data: $data,
cache: false,
async: false,
beforeSend: function() {
$('#btn-login').html('Logging In...');
},
success: function(r, status) {
if (r.status == 'success') {
getUser();
initNavSwipeGestures();
$('#page-index').removeClass('active');
} else {
alert(r.message);
}
},
error: function(data, status) {
alert(status);
}
});
Success is called when it is successful - http://api.jquery.com/jquery.ajax/:
success
Type: Function( PlainObject data, String textStatus, jqXHR jqXHR )
A function to be called if the request succeeds. The function gets passed three arguments: The data returned from the server, formatted according to the dataType parameter; a string describing the status; and the jqXHR (in jQuery 1.4.x, XMLHttpRequest) object. As of jQuery 1.5, the success setting can accept an array of functions. Each function will be called in turn. This is an Ajax Event.
Use "success" if you want to check what data is returned... otherwise you should use "complete".
Something like this should work:
$.ajax({
data: $data,
cache: false,
async: false,
beforeSend: function() {
$('#btn-login').html('Logging In...');
},
success: callback()
},
complete : function() {
getUser();
initNavSwipeGestures();
$('#page-index').removeClass('active');
},
error: function(data, status) {
alert(status);
}
});
var callback = function(response) {
///stuff to do after success here
};
Here's what I ended up with:
$('#form-login').on('submit', function(e) {
e.preventDefault();
if ($.trim($('#email').val()) === '' || $.trim($('#password').val()) === '') {
return;
}
var loginBtn = Ladda.create( document.querySelector('#btn-login') );
$data = $('#form-login').serializeArray();
$.ajax({
data: $data,
beforeSend: function() {
$('#btn-login').addClass('isloading');
loginBtn.start();
},
success: function(r, status) {
setTimeout(loginResponse(r, loginBtn), 500);
},
error: function(data, status) {
if (PLATFORM == 'desktop') {
alert(status);
} else {
loginBtn.stop();
$('#btn-login').removeClass('isloading');
navigator.notification.alert(status, false, false);
}
}
});
});
function loginResponse(r, loginBtn) {
if ($('#btn-login').hasClass('isloading')) {
if (r.status == 'success') {
getUser();
$('#page-index').removeClass('active');
} else {
if (PLATFORM == 'desktop') {
alert(r.message);
} else {
navigator.notification.alert(r.message, false, false);
}
}
loginBtn.stop();
$('#btn-login').removeClass('isloading');
} else {
setTimeout(loginResponse(r, loginBtn), 500);
}
}

Categories

Resources