I'm very new to Javascript and I have a button that need to be constantly checked against whether a server is active or not.
I'm using the Play framework based in Java. I already have a class ServerStatus that returns whether a service is healthy or not but I am not sure how to link this into my page which contains the button.
Basically, what I want is that if the server goes down then I want the button disabled so that the user cannot use it while the server is unavailable.
I looked a bit at Websockets and that looks really complex. I wasn't sure if there is a simpler way.
EDIT
Using Websockets: I had a read around and it seems I need to use the onmessage event. I found some sample code but I am not sure how to put this into my (document).ready function.
Below I have some code:
$(document).ready(function(){
var WS = window['MozWebSocket'] ? MozWebSocket : WebSocket;
var chatSocket = new WS("routes");//This does not seem to accept any #routes
var lastState = 'unknown';
chatSocket.onmessage = function(e){
var server_message = e.data;
//do something here about enabling and disabling
console.log(server_message);
}
});
function disable()
{
//disable all buttons
}
function enable()
{
//enable all buttons
}
I am lost as to how to add the websocket here.
I am borrowing heavy from this similar question and answer
The basic code is here:
var isNotWorking = false;
var myFunc = function(){
$.ajax({url: "YOUR_URL_HERE",
type: "HEAD",
timeout:1000,
statusCode: {
200: function (response) {
//alert('Working!');
isNotWorking =false;
},
400: function (response) {
//alert('Not working!');
isNotWorking = true;
},
0: function (response) {
//alert('Not working!');
isNotWorking = true;
}
}
});
$('#mybutton').prop('disabled', isNotWorking);
doSetTimeOut();
}
var doSetTimeOut = function(){
setTimeout(function(){
myFunc();
}, 1000);
}
doSetTimeOut();
See a working JS fiddle here
Related
I am trying to broadcast a message entered by an admin to be visible to online users as a pop up. i am using ajax to make a call to database with a time interval like the code below. This code runs for each and every online users and returns message if the message_Flag is 1 in the database
setInterval( function()
{
getChatText();
}, 5000);}
function getChatText() {
$.ajax({
type : "POST",
url : "/easyoffice/commonAjax.do",
data : "method=" + "getMessages",
success : function(responseText) {
if (responseText.trim() != ''){
$("#dialog-message").html(responseText);
$("#dialog-message").dialog({
modal: true,
draggable: false,
resizable: false,
position: ['center'],
show: 'blind',
hide: 'blind',
width: 400,
dialogClass: 'ui-dialog-osx',
buttons: {
"I've read and understand this": function() {
$(this).dialog("close");
}
}
});
}
},
error : function(e) {
alert('Error: ' + e);
}
});
}
This is working correctly , but being a webapp with a lot of users , this causes a performance drop. I've heard websockets doesn't support Broadcasting. Is there any alternative .?? Thanks in advance
I have to monitor server at real time. Means if there is any change happens in server value need to display it in android device . I have code to implement the same in web browser using html java script .
<script language="javascript" type="text/javascript">
function webservice_connect() {
// open a web socket
hostname = window.location.hostname;
ws = new WebSocket('ws://'+hostname+':8000/echo');
ws.onopen = function()
{
console.log("connected to server");
}
ws.onmessage = function (evt)
{
var received_msg = evt.data;
//alert("Message is received...");
console.log("Message is received..."+received_msg);
rdata = JSON.parse(received_msg);
show_status(rdata);
};
ws.onclose = function()
{
// websocket is closed.
console.log("disconnected server!");
};
}</script>
How can I implements the same in android
You could try using an android webview with exactly the same html/js code.
Background:
Using WebSockets with JavaScript + Play! framework (2.2).
Can send and receive data fine in Chrome.
Can only receive data (from server) in Firefox as send() doesn't trigger any callbacks.
In addition to the send issue, and in Firefox only again, the tab for the page is always stuck on "connecting" while the spinner keeps spinning (see figure 1).
Misbehaving Browser:
Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:24.0)(Firefox 24.0)
(Figure 1. Firefox tab after page has loaded and data is shown)
Any time I refresh the web page, I receive the error below, attributed to the constant page loading behaviour I'm sure.
The connection to ws://localhost:9000/ was interrupted while the page was loading.
The entire JavaScript code:
$(function() {
var chatSocket = new WebSocket("#routes.Application.getMetaData().webSocketURL(request)");
var sendMessage = function() {
chatSocket.send(JSON.stringify({
id: "unique",
name: "a name",
age: 22
}));
}
var receiveEvent = function(event) {
var data = JSON.parse(event.data)
document.write(data.age);
document.write(data.name);
document.write(data.message);
document.write("\n");
sendMessage();
chatSocket.close();
}
chatSocket.onmessage = receiveEvent
})
Now In the past, I've been trying with MozWebSocket instead of the standard WebSocket, but I get nothing rendered on screen using that module therefore unless there is an angle I've missed, WebSocket is the better one to use.
The relevant Play! block:
public static WebSocket<JsonNode> getMetaData() {
return new WebSocket<JsonNode>() {
// Called when the Websocket Handshake is done.
public void onReady(WebSocket.In<JsonNode> in, WebSocket.Out<JsonNode> out) {
// For each event received on the socket,
in.onMessage(new Callback<JsonNode>() {
#Override
public void invoke(JsonNode jsonNode) {
System.out.println("Message Incoming!");
System.out.println(jsonNode.get("id"));
System.out.println(jsonNode.get("name"));
System.out.println(jsonNode.get("age"));
}
});
// When the socket is closed.
in.onClose(new Callback0() {
public void invoke() {
System.out.println("Disconnected");
}
});
ObjectNode node = Json.newObject();
node.put("message", "hello");
node.put("name", "client");
node.put("age", 1);
out.write(node);
//same result commented/uncommented
out.close();
}
};
}
So in Chrome, the flow would be:
document.write(...)
"Message Incoming!"
... JSON attributes
"Disconnected"
But in Firefox, the flow is:
document.write(...)
"Disconnected"
Any help in diagnosing these problems would be greatly appreciated. I have no intention of supporting IE, but having both Mozilla and Chrome working would be great.
Other JavaScript Warnings:
Below is a warning I occasionally get in Firefox's console while pointing at the "ws" protocol as the culprit. What its relevance is to my problem, I do not know.
Use of getPreventDefault() is deprecated. Use defaultPrevented instead.
You call document.write() after the document is loaded, which then implies document.open() which in turn replaces the document and by that unloads the old one and aborts stuff like timeouts or websockets.
Use something other than document.write() and you should be fine.
My requirement is to give access like one login per user, For that I have updated the login Status to true in db when user login, and false when user logout.
But the problem is when user close the window without logout.
To handle window close I have implemented the following js code
var validNavigation = false;
function wireUpEvents() {
var dont_confirm_leave = 0;
var leave_message = 'You sure you want to leave?'
function goodbye(e) {
if (!validNavigation) {
if (dont_confirm_leave!==1) {
if(!e) e = window.event;
//e.cancelBubble is supported by IE - this will kill the bubbling process.
e.cancelBubble = true;
e.returnValue = leave_message;
//e.stopPropagation works in Firefox.
if (e.stopPropagation) {
e.stopPropagation();
e.preventDefault();
}
//return works for Chrome and Safari
return leave_message;
}
window.location = "logout.jsp";
}
}
window.onbeforeunload=goodbye;
// Attach the event keypress to exclude the F5 refresh
$(document).bind('keypress', function(e) {
if (e.keyCode == 116){
validNavigation = true;
}
});
// Attach the event click for all links in the page
$("a").bind("click", function() {
validNavigation = true;
});
// Attach the event submit for all forms in the page
$("form").bind("submit", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type=submit]").bind("click", function() {
validNavigation = true;
});
// Attach the event click for all inputs in the page
$("input[type='button']").bind("click", function() {
validNavigation = true;
});
}
// Wire up the events as soon as the DOM tree is ready
$(document).ready(function() {
wireUpEvents();
});
Here it works for window close, means if user close the window it goes to logout page, but problem is it was going to logout page when user reloads the page.
So I need bind the reload event also like the above js code for f5, submit and anchor tags.
Pleae help me in this regard.
Thanks in Advance...
Two things came into my mind:
First of all the fact that the user is logged in, doesnt mean that theres any activity going on, some people leave there pc turned on with the browser running.
Second is that even if the user closes a page it doesnt necesserly means that he/she wanted to logout and its especially true if the user use two tab to navigate on your site.
So instead of trying to check when they close the tab I suggest considering the idea of logging them out only when they login from somewhere else and/or setting up a timer that automatically log them out after a certain amount of inactivity.
I have searched stackoverflow for an full example or some blog that explains how to make facebook login Server-side Apps with javascript sdk
but didn't find anything.
I have searched developer.facebook.com site and the only thing i have got was a php example https://developers.facebook.com/docs/howtos/login/server-side-login/.
The problem is that i must use JavaScript.
Why should i want to do that?
The reason is that i want to upload files to the server(google-app-engine(Java Sdk)) and save them on the db with the facebook user id and retrieve them by his user id.
another question is, how can i debug my javascript code if he uploaded dynamically?what about code assist?
Well I can help you with this issue. If you need to use the JS SDK of FB, then you have to do everything on the client side or on browser, because Facebook doesn't have any support for Java on Server Side.
So I suggest you that you can authenticate user on client, define your scopes for accessing user profile, once authenticated by user you will get response as JSON Object which you can send using ajax to AppEngine Backend.
I am sharing my link where I used FB Login and accessing User's Profile Information along with his photos in albums and videos.
http://demositeunicfyp.appspot.com/fb-pictures.html
http://demositeunicfyp.appspot.com/facebook.html
You can Debug the JS Code in your browser to see what kind of response object you are getting back from Facebook APIs.
$(document).ready(function() {
// Initializing the Facebook SDK
FB.init({
appId : 'XXXXXXXXXXXXXXXX',
status : true,
cookie : true,
xfbml : true,
oauth : true
});
// Method to check if a user is looged in to FB or Not
FB.getLoginStatus(updateButton);
$("#logout").live("click", function(event) {
event.preventDefault();
// FB.getLoginStatus(updateButton);
FB.logout(function(response) {
$("#loginDiv").show();
$("#logoutDiv").hide();
});
});
$("#fbLoginButton").live("click", function(event) {
//event.preventDefault();
FB.getLoginStatus(updateButton);
});
function updateButton(response) {
var button = document.getElementById("fbLoginButton");
if (response.authResponse) {
// user is already logged in and connected
// button.innerHTML = 'Facebook Logout';
//$("#loginDiv").hide();
//$("#logoutDiv").show();
//window.location = '/confirm';
FB.api('/me', function(response) {
$("#userName").text(response.name);
$("#userEmail").text(response.email);
});
} else {
// user is not connected to your app or logged out
// button.innerHTML = 'Facebook Login';
button.onclick = function() {
FB.login(function(response) {
if (response.authResponse) {
// button.innerHTML = 'Facebook Logout';
$("#loginDiv").hide();
$("#logoutDiv").show();
FB.api('/me', function(response) {
$("#userName").text(response.name);
$("#userEmail").text(response.email);
});
} else {
//user cancelled login or did not grant authorization hence do nothing
}
}, {
scope : 'email,publish_actions'
});
}
}
}
});
Taken from JS.php in SDK download
<?php
require '../folderTo/facebook.php';
$facebook = new Facebook(array(
'appId' => '',
'secret' => '',
));
// See if there is a user from a cookie
$user = $facebook->getUser();
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('me?fields=photos'); } catch (FacebookApiException $e) {
echo '<pre>'.htmlspecialchars(print_r($e, true)).'</pre>';
$user = null;
}
}
?>
<!DOCTYPE html>
<html xmlns:fb="http://www.facebook.com/2008/fbml">
<body>
<?php if ($user) { ?>
Your user profile is
<pre>
<?php print htmlspecialchars(print_r($user_profile, true)) ?>
</pre>
<?php } else { ?>
<fb:login-button></fb:login-button>
<?php } ?>
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId: '<?php echo $facebook->getAppID() ?>',
cookie: true,
xfbml: true,
oauth: true
});
FB.Event.subscribe('auth.login', function(response) {
window.location.reload();
});
FB.Event.subscribe('auth.logout', function(response) {
window.location.reload();
});
};
(function() {
var e = document.createElement('script'); e.async = true;
e.src = document.location.protocol +
'//connect.facebook.net/en_US/all.js';
document.getElementById('fb-root').appendChild(e);
}());
</script>
</body>
</html>
Working example here: http://slicethegreen.com/examples/js.php