How to save a variable to the server using jQuery - javascript

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...

Related

Pausing a timer

I have a page with two tabs that refreshes via timer every thirty seconds. I need to pause/cancel it when either tab-1 is selected or when data is being edited and restart it when tab-0 is selected or when the edit is saved.
The timer variable is in the .html file, the calls to start/stop are in the .js file.
HTML file:
<script>
var interval = setTimeout(function() {
window.location.reload(1);
}, 30000);
</script>
.js file:
The tab timer stop works:
jQuery(document).ready(function() {
jQuery('#tabs').on("click", function() {
var tabIndex = (jQuery("#tabs").tabs('option', 'active'));
if (tabIndex === 0) {
interval = setTimeout(function() {
window.location.reload(1);
}, 30000);
} else {
window.clearInterval(interval);
}
});
});
However, the edit timer stop doesn't work:
jQuery.ajax({
url: 'HandbookServlet',
type: 'POST', data: {formType: "getRecord",
id: id
},
dataType: 'json',
async: false,
success: function(responseText) {
var obj = JSON.stringify(responseText);
var obj2 = JSON.parse(obj);
jQuery('#lblEditDate').text(obj2.strDateSigned);
jQuery('#taEditComment').val(obj2.comment);
jQuery('#divAlert').show();
window.clearInterval(interval); //stop timer doesn't work here
}, error: function(request, status, error) {
alert("An error occurred. Error: " + status + ", " + error);
}
});
There's no errors generated. Does "window.clearInterval" only work via "jQuery(document).ready"?
The issue wasn't with scope or the timer itself (rather it was "operator headspace and timing").
The problem was that the edit button was on tab0 (which wasn't mentioned in my original question). When that button was clicked, the event propagated to the tab, firing the code in document.ready and restarting the timer after the timer had been stopped in the function.
To fix the problem, I sent the click event to the function and used event.stopPropagation() to prevent the tab from picking up the click:
function displayRecord(e, id) {
e.stopPropagation();
stopTimer();
jQuery.ajax({
url: 'HandbookServlet',
type: 'POST', data: {formType: "getRecord",
id: id
},
dataType: 'json',
async: false,
success: function(responseText) {
var obj = JSON.stringify(responseText);
var obj2 = JSON.parse(obj);
jQuery('#itemId').val(id);
jQuery('#lblEditDate').text(obj2.strDateSigned);
jQuery('#taEditComment').val(obj2.comment);
jQuery('#divAlert').show();
}, error: function(request, status, error) {
alert("An error occurred. Error: " + status + ", " + error);
}
});
}

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.

Control front-end javascript from node.js back-end

I am building a chat app and I want to ask users to input their username. JQuery front-end code slides a form into view (on ready), stores the data into variables and then loads the chat (when enter key or button is pressed). How do I stop that animation until I validate user input on server-side? I am using node.js for backend. Any ideas?
Thanks in advance!
Front-end jQuery:
var nameChoice, roomChoice; //to store user input
var initName = function() {
nameChoice = $("#init-name input").val(); //save chosen name in nameChoice
$("#current-name").text("Username: " + nameChoice); //put chosen name in chat header
$("#init-name").animate(
{"left" : "-35%"}, 300,
function() {
$(this).addClass("hidden");
$("#init-room").removeClass("hidden");
$("#init-room").animate({"left" : "35%"}, 300);
}); //remove name form and slide in room form in callback
} //end initName
var initRoom = function() {
roomChoice = $("#init-room select").val(); //save chosen room in roomChoice
$("#current-room").text("Room: " + roomChoice); //put chosen room in chat header
$("#init-room").animate(
{"left" : "-35%"}, 300,
function() {
$(this).addClass("hidden");
$("#chat-main").removeClass("hidden");
}); //remove room form and show page in callback
} //end initRoom
var btnHover = function() {
$(".btn-form").hover(
function() {
$(this).stop().animate(
{
backgroundColor : "#FFBD7A"
}, 300);
},
function() {
$(this).stop().animate(
{
backgroundColor : "white"
}, 300);
});
}
var init = function() {
$("#init-name").removeClass("hidden").animate({"left" : "35%"}, 300); //slide in name form
$(document).keydown(function(event) { //submit choice on enter key
if (event.which === 13) {
if (!$("#init-name").hasClass("hidden")) { //if user is choosing name
event.preventDefault();
initName(); //call initName function
}
if (!$("#init-room").hasClass("hidden")) { //if user is choosing room
event.preventDefault();
initRoom(); //call initRoom function
}
}
}); //end enter key submission
$("#init-name .btn-form").click(initName);
$("#init-room .btn-form").click(initRoom);
btnHover();
} //end init
$(document).ready(init);
I'm still learning node, so no back-end code yet...
rough code for this ...
$http.post("/login", {"username":username, "password": password}).then(function(response) {
console.log("success - do animation here");
}.catch(function(response) {
console.log("failure a non 2xx HTTP response - handle error here");
});
This code is crude since the http request should prob be in a service, also I have not linted this code, BUT you should get the general IDEA!
APOLOGIES THIS IS ANGULAR, JQUERY WAS ASKED FOR ... HERE GOES ...
$.ajax({
method: "POST",
url: "/login",
data: { username: username, password: password }
})
.then(
function( data, textStatus, jqXHR ) {
console.log("success - do animation here");
},
function( jqXHR, textStatus, errorThrown ) {
console.log("failure a non 2xx HTTP response - handle error here");
}
);
Never tried this in Jquery before but the docs suggest this approach.
Check the docs at ...
http://api.jquery.com/jquery.ajax/
Thanks
Edit: in case promise based jQuery code not available:
$.ajax({
method: "POST",
url: "/login",
data: { username: username, password: password }
})
// for older versions of jQuery, replace .done and .fail with .success and .error
.done(function( data, textStatus, jqXHR ) {
console.log("success - do animation here");
})
.fail(function( jqXHR, textStatus, errorThrown ) {
console.log("failure a non 2xx HTTP response - handle error here");
});

Google api authentication window closed callback

I'm trying to get the contacts from google using javascript api:
$(document).on('click', '#connect_to_google', function() {
$('body').addClass('loading');
var config = {
client_id: GOOGLE_CP_CIENT_ID,
scope: 'https://www.google.com/m8/feeds'
};
gapi.auth.init(function() {
gapi.auth.authorize(config, function() {
var token = gapi.auth.getToken();
if (null !== token && (typeof token.access_token !== 'undefined')) {
$.ajax({
url: "https://www.google.com/m8/feeds/contacts/default/full?access_token=" + token.access_token + "&alt=json&v=3.0",
dataType: "json",
cache: false,
success: function(data) {
//doStuff(data);
$('body').removeClass('loading');
},
error: function (xhr, error) {
$('body').removeClass('loading');
},
complete: function (xhr, error) {
$('body').removeClass('loading');
}
});
} else {
$('body').removeClass('loading');
}
});
});
});
The moment the client clicks the login button, the page displays a layer over it ($('body').addClass('loading');), to restrict any user interaction outside google auth page.
All works well, except for the situation when the user closes the google auth window manually, then nothing happens.
Is there any way to check if the user closed that window, to call the $('body').removeClass('loading');?
Or is there any way to open the gapi.auth.authorize window in a modal dialog container? That way I could very easy check it's status.
This seems to do the trick:
(function(wrapped) {
window.open = function() {
var win = wrapped.apply(this, arguments);
var i = setInterval(function() {
if (win.closed) {
clearInterval(i);
$('body').removeClass('loading');
}
}, 100);
};
})(window.open);
It's not the best solution, but it does the work

Kill Ajax Session Outside of Originating Function

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();
});

Categories

Resources