I have a web application which serves as the Admin Panel. It has a live chat option which connects with writers(employees) on the other end. The web application uses the following PHP code to check for online writers.
$q = 0;
$lasttime = isset($_POST['timestamp']) ? $_POST['timestamp'] : 0;
while ($q<5){
sleep(3);
$wresult = $db->query("SELECT writer_alias FROM tblwriter WHERE writer_isactive=1 AND (UNIX_TIMESTAMP(NOW())-last_activity)<10");
if ($wresult->num_rows){ break; }
++$q;
}
if ($wresult->num_rows){
while ($row = $wresult->fetch_object()){ $writers[] = $row; }
$wresult->free();
}
echo json_encode(
array(
"writers" => $writers,
"now" => time()
)
);
On the application the following javascript code handles the PHP response and calls ajax again to complete the loop.
function UpdateCHAT(){
$.ajax({
type: "POST",
url: "liveserver.php",
data: {update:"1",timestamp:lastime},
success:
function(data1){
if (data1 == null){
$(".onlinechat i").removeClass("icon-white");
}else{
lastime = user_signin = Number(data1.now);
if (!data1.writers.length){
$(".onlinechat i").removeClass("icon-white");
}else{
$(".onlinechat i").removeClass("icon-white");
$.each(data1.writers,function(j) {
$("#writer_"+data1.writers[j].writer_alias).find("i").addClass("icon-white");
});
}
}
},
dataType: "json",
timeout: 60000,
complete:
function(){
UpdateCHAT();
}
}
);
}
Everything is working just fine except the fact that I cannot think of a way to know for offline writers since the PHP code is designed to check for the online writers, but this means if a writer is online once, he will remain online (on the application) until the PHP code dies and return empty writers.
Hope I am able to explain my point. This question is more to do with idea rather than piece of code. Any input is appreciated.
Thanks.
Make the PHP code always return after some time (like 2 minutes) with an empty result set (ie. no new chat lines).
JS will then do a new request immediately. If it doesn't, well, then the user is offline. Keep a last_request timestamp, if it's older than 2+e minutes the user is offline.
You could try to detect when the connection closes in PHP. Set ignore_user_abort(true) so you are in control of when your script dies. Then use connection_aborted() to check if the client closed. If he did you know he left.
A potential problem occurs if the user has two windows open: a close on one doesn't mean he left, but this may turn out to be acceptable; the user will blip for just a while.
Another solution is to use a separate ping request that just tells you "yep, I'm still here". If you haven't gotten one of those in a while the user is probably offline.
Related
(When I say "App" I am only talking about Android, I'm not gonna even try to deal with Apple)
So I have a website that I'd like to develop an Android app for. All I need it to do is show the website(it'll change some styling if being accessed from the app), which I can do just fine.
I use Intel XDK, which works great. But the notification options it offers seems to be just mass-notification stuff, not individualized.
All I want to do is be able to tell users when they get a notification from my website(like a message from another user).
I've looked all over the place for hours and hours and can't find anything useful. There are a ton of extremely complicated Java codes and tutorials, but I don't even know Java. I'm solely a web developer and all I want is an app that makes it easier for users to check the website.
I'm hoping there is some Java file out there that I can send data to somehow that will allow me to create and delete push notifications on Android systems. Maybe a HTML5 library or JS function, I dunno.
I simply can't seem to implement it myself, and I'm definitely not going to learn an entire dying language just for one basic thing that should be simple to do. Anything you guys can provide would be greatly appreciated. Optimally I would like to get a Java file I can download and put into my app that gives a notification, then I can edit it to say what I need it to or whatever(I also would really like a way to make the notification go away[in case the user sees it on another device before seeing it on the phone] ). I would also need to know how to call onto this Java file, make it check for notifications on the server or whatever.
I know this is all very nooby stuff, but I run an independent website and simply don't have the time to learn all this stuff when my needs are so basic. Thanks in advance.
You can use appMobi for push messaging, see documentation at http://docs.appmobi.com/index.php/push-messages/pushjsapi/. You can setup your appMobi account in the Services tab of the Intel XDK.
//Check if user is registered
var onDeviceReady=function() {
//See if the push user exists already
//You can send any unique user id and password.
AppMobi.notification.checkPushUser(AppMobi.device.uuid, AppMobi.device.uuid);
};
document.addEventListener("appMobi.device.ready",onDeviceReady,false);
//if user is not registered, register them
var isUserAdded = false;
var notificationsRegistered=function(event) {
if(event.success === false) {
if (!isUserAdded) {
isUserAdded= true;
AppMobi.notification.addPushUser(AppMobi.device.uuid,
AppMobi.device.uuid,
'no#email.com');
return;
}
AppMobi.notification.alert("Notifications Failed: " + event.message,
"My Message","OK");
return;
}
var msg = event.message || 'success';
AppMobi.notification.alert("Notifications Enabled: " + msg,
"My Message","OK");
};
document.addEventListener("appMobi.notification.push.enable",
notificationsRegistered,false);
//when push message event is found get notification
var receivedPush = function(){
var myNotifications=AppMobi.notification.getNotificationList();
//It may contain more than one message, so iterate over them
var len=myNotifications.length;
if(len > 0) {
for(i=0; i < len; i++) {
msgObj=AppMobi.notification.getNotificationData(myNotifications[i]);
try{
if(typeof msgObj == "object" && msgObj.id == myNotifications[i]){
AppMobi.notification.alert(msgObj.msg + "\n" + msgObj.data
+ "\n" + msgObj.userkey,"pushMobi Message","OK");
//Always delete messages after they are shown
AppMobi.notification.deletePushNotifications(msgObj.id);
return;
}
AppMobi.notification.alert("Invalid Message Object: " + i,
"My Message","OK");
}catch(e){
AppMobi.notification.alert("Caught Exception For: " + msgObj.id,
"My Message","OK");
AppMobi.notification.deletePushNotifications(msgObj.id);
}
}
}
};
document.addEventListener("appMobi.notification.push.receive", receivedPush, false);
//send a push notification from your website
AppMobi.notification.sendPushNotification(myAppMobiUserID,"new website blog posted!",{});
document.addEventListener("appMobi.notification.push.send",updateNotificationEvent,false);
var updateNotificationEvent=function(event)
{
if(event.success==false)
{
alert("error: " + event.message)
}
else
{
alert("success");
}
}
You can also use Parse.com APIs but I don't believe the subscribe to channel JavaScript API is fully flushed out last I checked, see https://www.parse.com/docs/push_guide#top/JavaScript.
Parse.initialize("YOUR KEY", "HERE");
// Save the current Installation to Parse.
ParseInstallation.getCurrentInstallation().saveInBackground();
You can then send push notifications through the Web Console, or on your website using:
//The following code will push the alert to the "Winterhawks" and "Oil Kings" channels.
Parse.Push.send({
channels: [ "Winterhawks", "Oil Kings" ],
data: {
alert: "The Winterhawks won against the Oil Kings!"
}
}, {
success: function() {
// Push was successful
},
error: function(error) {
// Handle error
}
});
Subscribe to channels is not yet implemented for JavaScript as far as I know so you'll have to use REST or native APIs.
I am developing a management application in Spring Hibernate wherein I need to implement a timer system.
USE CASE
User clicks on an activity or an event on the UI(jsp). The timer starts, it displays the countdown on the UI. Only after the stipulated timer count is over the user can perform that event again.
I need to persist the time in the db because if the user closes the browser the timer count should continue in the server. Just like how we encounter in web based social media games.
I searched for a solution on the web but didn't come across anything. I tried Spring Scheduling but that didn't seem to solve the purpose plus it has a lot of limitations.
Can anyone suggest me any solution? Thanks
To answer this question, I'll assume the following:
On the back-end you have the ability to run asynchronous background jobs
A JavaScript timer on the front-end is sufficient to give a countdown (regardless of being slightly off with the background job
The basic idea is that you send off a date stamp to the server, start a countdown on the front-end, and any time there is an interaction to try the activity again, you ask the server (the same background task) if the time interval has completed.
The solution below is the beginnings, and is by no means a complete version of what it would take to manage such an interaction.
On the front-end you could imagine doing something like:
function restoreAndStartTimer(response, initialLoad){
var secondsToCountDown = 10;
//Here we can use the server response to tell us if there's already
//a timer running
if(response.timerRunning){
secondsToCountDown = response.secondsRemaining;
}
//Now kickoff the front-end timer
function countdown(){
//Add code here to display stuff to the screen, etc
if(secondsToCountDown !== 0){
secondsToCountDown--;
setTimeout(countdown, 1000);
}
};
if(initialLoad){
if(response.timerRunning) countdown();
} else {
countdown();
}
};
//Click handler, assuming you use jQuery
$('#myActivityButton').on('click', function(){
$.ajax({
url: 'https://...',
type: 'POST',
//Grabs the time of the click and sends it off to the server
data: { currentTime: new Date() },
success: function(response){
restoreAndStartTimer(response, false);
}
});
});
$(function(){
//On document ready
//This should be wrapped as a function to avoid repetition, but for the sake of
//expediency using this editor...
$.ajax({
url: 'https://...',
type: 'POST',
data: { currentTime: new Date() },
//If a user had reloaded the page while a timer was running, it will get picked
//up here, otherwise it does nothing.
success: function(response){
restoreAndStartTimer(response, true);
}
});
});
As for the back-end, you would have some method that runs as a background thread. That thread would get the time from the initial time-stamp sent by the front-end and return any of the following responses depending on state:
response.timerRunning = true and response.secondsRemaining = #ofSeconds given that the time interval has not completed
response.timerRunning = false when the time interval is finally complete
I am sorry, I know the question is pretty stupid, but I am pretty new at Java, I've been working a lot with .NET.
With .NET I was using the following function to gather data and receive response from another page:
$.ajaxSetup({
global: false,
timeout: 60000,
type: "POST"
});
$.getJSON("Async/GetRegionalData",
{
requestedFunction: "getData",
id: 1
},
function (data) {
if (data != null) {
if (!data.ErrorCode == "0") {
}
else {
//function goes here
}
}
}
});
My question is this: How can I achieve the same thing with Java file as a server side?
Any links to relative topics would be of help.
How to get the parameters in the url that is requested? Anything connected with this topic is helpful. I did some research, but I didn't find much regarding this topic. Thank you in advance.
I need to upload multiple files from jsp. I am using $ajaxFileUPload.js to take the file to server side. I am doing my file size validation in server side for each file. I need a message on validating the file, where i face a problem. I am not able to show that message. Could someone help me in this please?
I have not used the plugin but what I have done previously in similar situation is send different markers back to the client side like for an upload the exceeds the file limit size, you can start the response back with something like 'ERROR:' and then look for this marker in the function getting the response back and then branch to a different logic. You obviously have to parse the response and look for the marker.
Looking quickly at the plugin in Github, it looks like the usage is
$('input[type="file"]').ajaxfileupload({
'action': '/upload.php',
'params': {
'extra': 'info'
},
'onComplete': function(response) {
console.log('custom handler for file:');
alert(JSON.stringify(response));
},
'onStart': function() {
if(weWantedTo) return false; // cancels upload
},
'onCancel': function() {
console.log('no file selected');
}
});
So what I think you can do is in the onComplete function something like
if (response.search("ERROR:") != -1){
//error condition
//add your msg for the front end here
} else {
//non error condition, continue with your regular flow
}
Does this make sense and relate to what you are trying to do?
As I talk about befor I'm using to jQuery to refresh / update a webcam image.
This works just fine if you wanna update the image every 5th or 10sec.
But when your gonna do a stream with 10-15fps it gets into problems with most browsers
it seems. The problem seem to be that it sends a request befor the first one was done.
Is there a way to wait for the first request to be done befor sending a new update request for the webcam image? Because to me it seems to stack up requests if there is alittle delay on the server with the image.
Sorry if I did explain it alittle bad but... I'm norwegian and blode. Not the best combination. :)
Webcam Image is a single url
ex. http://www.ohoynothere.com/image.jpg
Old code I use.
$(document).ready(function() {
setInterval('updateCamera()',3000);
});
function updateCamera() {
$('.online2').each(function() {
var url = $(this).attr('src').split('&')[0];
$(this).attr('src', url + '&rand=' + new Date().getTime());
})
}
Definitely!
It sounds like your best bet would be to use the jQuery.ajax() method ( http://api.jquery.com/jQuery.ajax/ ) or .get() method to chain your requests. Basically, you want a JavaScript function that does a request for the image using the .ajax() call. In the response handler, simply call the function again:
function getMyImage() {
jQuery.get(image_url, function(response) {
jQuery('#img-name').attr('src', response);
getMyImage();
});
}
Whenever getMyImage successfully returns the image's src value from the webcam, it will immediately go out and try to retrieve a new image, but not before the previous one is loaded.
If I haven't understood what you're trying to do, please let me know. It would be helpful to know more about how the webcam image is retrieved (i.e. is it the same image src returned every time, etc.).