display number of message dynamically using javascript or asp.net - javascript

I will do my best to explain my problem to avoid people pointing me into different directions.
I got an assignment from business people. I don't know the terminology. It is very similar to email notification, message notification on facebook, notification on social media games.
For example, people are sending 20 email messages 5 minutes ago. the screen will display 20 (see attachment). Now, 3 more messages have arrived, the web page should update the number to 23.
Facebook has similar concepts when our friends like/comment message. The notification changes. Same thing is true on social media game. Any status changes on our game, it will reflect it.
I kind of have idea on how to do it cosmetically (on CSS). How to do it using javascript/asp.net. Do I need to postback in order to refresh the message. I never pay attention to that on facebook/yahoo email/social media games. All I know is something is happening, the webpage is updating the status.
Sorry the question is too broad. If someone can help me to point to the right direction, I appreciate any help

HTML5 introduced a very interesting concept call Server-Sent Events in which server can dynamically connect to the client and send data.
Eg:
var source = new EventSource("demo_sse.asp");
source.onmessage = function(event) {
document.getElementById("result").innerHTML = event.data + "<br>";
};
And on server side you can write,
<%
Response.ContentType = "text/event-stream"
Response.Expires = -1
<!--Writing "data:" is important-->
Response.Write("data: The server time is: " & now())
Response.Flush()
%>
However, some old browsers may not support this.
One other way to accomplish this task is to use Ajax call as,
function checkNewMessages(totalMessages){
return $.ajax({
url: 'demo.asp',
type: 'GET',
cache: false,
data: {
totalMessages: totalMessage;
}
});
}
checkNewMessages(totalMessages).success(function (data) {
// display the data wherever you want
});
//Checking for new messages every 5 seconds
setInterval(checkNewMessages(totalMessages,5000));
Whatever you write within your Write() in server side will be displayed here. Now to constantly check for the new messages you can call the above ajax function with the help of setInterval()

There are many ways to do this, depending on how real time you need it to be.
The most common way is to use JavaScript with an XmlHttpRequest to call an ASP.NET page which returns the number of messages, I recommend you use a JSON object for this. The benefit of this approach allows you to request data from the server without the user experiencing a full page refresh. You can use JavaScript to set it to call every x seconds depending on your requirements.
Collectively that is known as AJAX, using a JavaScript library such as JQuery can make this much easier.

Related

How to set up an online chat without javascript?

I stumbled upon a rather strange site the other day : https://harmless.herokuapp.com/main
It is an online mini chat that does not use javascript on the client side, and yet it allows you to display your messages and those of others, in real time.
While trying to document myself I came across the term "Long Polling" but all the sources I could look at used javascript to implement it.
I guess the forever loading page is something to do with it.
From what I understand, if a valid XMLHttpRequest is not returned, then the client-side browser never closes the connection with the server and keeps trying to receive data.
I tried the code below but it didn't work : How do I implement basic "Long Polling"?
<?php
if(rand(1,3) == 1){
/* Fake an error */
header("HTTP/1.0 404 Not Found");
die();
}
/* Send a string after a random number of seconds (2-10) */
sleep(rand(2,10));
echo("Hi! Have a random number: " . rand(1,10));
?>
In short, I wanted to understand how a site could update the data received and send it back to the user in real time without using client-side javascript.
EDIT :
Here is the answer : github.com/kkuchta/css-only-chat
Thank you to Flux for his find!

Show live data from can bus on webpage with visualization

I want to use a linux device like a BananaPi with a socketcan-compatible can-controller to connect to a automotive can-bus and show its data in realtime on a webpage, which should be hosted on the Pi.
The data should be listed as hex-values and visualized via graphs (the different signals, for example the current speed).
After some research I discovered node-can and I could get managed to show the can-messages as a list on a webpage. But I noticed, that the messages come with a quite huge delay (~2 secs) when there is a huge busload (I sent can messages in a 1 ms period). The same delay occurs, if I use the following minimalistic example:
var can = require('socketcan');
var channel = can.createRawChannel("can1", true);
channel.addListener("onMessage", function(msg) { console.log(msg); } );
channel.start();
I am absolutely new in this topic but I think, that nodejs isn't the best choice to realize this project?
Are there any other (better) methods to realize such a system?
I could imagine something like a C-backend, for example based on candump (with this program no delay occurs at the same busload), and a frontend realized with javascript, html and css. But I have no idea how to get those different single programs together. Could you give me a keyword so I have a starting point for further research (websocket?!)?
I also thought about writing the can frames in a sql database and grab them from the database for the webpage-gui but I have no idea, if/how this works and if this is fast enough....
Thanks in advance!

Storing a variable to web server

I have a page on my site where you can play a game. When you die in the game, a function called "playerIsDead();" is called, then the game closes (The game screens are prompt();s and confirm();s shown one after another, so by "the game closes", I mean the page stops showing popup messages.). The playerIsDead(); Function:
var playerIsDead = function() {
confirm(deathMsg);
confirm(deathMsg2);
confirm(deathMsg3);
};
I want to make the function increase a variable, totalDeathCount, by one each time, like this:
var playerIsDead = function() {
confirm(deathMsg);
confirm(deathMsg2);
confirm(deathMsg3);
totalDeathCount++;
};
So, my question is, how can I store totalDeathCount to the server, so I can display it on the page? I don't want it to show how many deaths have happened locally, I want it to show how many worldwide deaths have occurred.
Any help would be much appreciated!
You could use a MySQL database and store the value using PHP. Or you could simply use javascript's localStorage to store them locally on the device.
var newDeathCount = localStorage.getItem('totalDeathCount') + 1;
localStorage.setItem('totalDeathCount',newDeathCount);
Then you basically stored how many times they have died. Not in a web server but this is an alternate solution.
1) Decide how and create something to persist the information. E.g. write it to a file, store it in a database, etc.
2) Write a simple php script to store the data. (or implement it as part of your existing php backend if available)
3) Make an ajax post request to send the data to the script.
For implementation details use google and your imagination. ;)

How to share data between clients using JavaScript?

I have a variable for JSON, but I want to make it where everyone that is on that PHP Page will be able to see the same variable contents.
This code should explain more of my situation.
(I am trying to make it where the page won't reload)
var chats = [];
var j = jQuery.noConflict();
j(document).ready(function()
{
setInterval(function(i){
var txt = "";
var x;
for (x in chats) {
txt += chats[x] + " <br />";
}
document.getElementById("json").innerHTML = JSON.stringify(chats);
}, 1000)
});
j(document).ready(function() {
j('#post_button').click(function() {
$text = $('[name=message]').val();
$sender = $('#texta').val();
chatstuff = {
"sender" : $sender,
"message" : $text,
};
chats.push(chatstuff);
$('[name=message]').val("");
});
});
So when it does document.getElementById("json").innerHTML = JSON.stringify(chats);, I want everyone to be able to see the same chats content when they are on the same page.
JavaScript runs in the user's browser. Any data in a variable is only visible to that client.
In order to synchronize data between clients, you would need to use something like websockets. Each client (user) would send data to your server and the server would relay all client activity to each client.
A very popular JavaScript websockets library is socket.io. You'll find a plethora of "How to create simple chat in JavaScript with websockets" tutorials if you just start searching for them.
Here's a socket.io chat demo that's right on there site.
"Why use websockets instead of Ajax?"
Well, just think about it for a little bit... Ajax is great for clients sending data to the server asynchronously, but what about the server talking to the client?
If user A writes "hello", we can send that to the server using Ajax, but how will users B and C be notified that a new message arrived?
Historically, before websockets, this was done with Ajax "long polling". What that means is each client will make an ajax request to the server every x seconds that asks "Hey, any new messages for me to read?"
If you're implementing a realtime chat app, that means x is going to be something like a max of 5 seconds otherwise users will be too frustrated with the lag.
Pinging our server every 5 seconds to ask the same question over and over is annoying. And it's quite archaic by today's standards. Maybe there's a better way...
"OK, so how does websockets make this better?"
Well websockets allows a connection between the client and server to stay open. This means that the server can send data to the client as soon as data arrives, without the client having to ask for it.
This means that we can ditch the polling and get data sync'd up even faster! Sweet!
"OK, that's great, but I can't rely on bleeding edge technologies..."
Well that's not really a problem either. The reason I recommended a websocket lib (e.g., socket.io) is because the socket.io will make a wide variety of attempts to achieve a socket-like connection in the event that your browser doesn't support actual websockets.
Included in a list of fallback methods is none other than... drumroll, please... Ajax long polling.
"Is there any alternative to socket.io?"
Yep. Now that you know you're looking for it should be easy to find tons of options out there. ws is another great lib that i'd definitely check out if socket.io seems too heavy-handed for you.
no, you have to use a server for this. send new data from this page to the server and the server will update the page for other viewers. consider reading some tutorials like this http://tutorialzine.com/2010/10/ajax-web-chat-css-jquery/

Best practice for a practical real-time app with .NET MVC4

Hello people and bots,
I'm developing the front-end web application for a system and have hit a little problem.
The whole application has to be on one page, meaning no refreshes or page changes during the flow of the major areas of the application.
It also has to work in all web browsers including IE7 and be deploy-able as a HTML5 application for tablets and mobile phones.
It's based around a user logging in, which is regulated by webforms authentication, then I need to poll or long-poll the server for updates. This would be simple if I could do a request for each part of the system, however if the system gets too big session blocking becomes a problem and it could also end up ddosing itself. So what I need to do is think of a way to send one request and build one response from that request.
My first idea was to build a response model with JSON or XML and let JavaScript regulate what needs to be updated. For example, a new comment has been made on a topic, all the clients see this update near instantly. My idea was to send something like this:
[
'd':
{
'addComment' : [{'topicId':'topic1', 'description':'haha'}, {'topicId':'topic1', 'description':'lol'}],
'addTopics' : ['topic2','topic708'],
}
]
JavaScript would then parse this and add "haha", and "lol" to the element with the id "topic1". In theory it seems quite simple to achieve, but as the system is getting bigger it seems to constantly be turning into a big mess.
My second idea was to simply have a set of client-side functions for adding and removing stuff in the DOM, And then use a JSONP technique to call this function.
var addComment = function(commentModel)
{
var topic = document.getElementById(commentModel.topicId),
comments = topic.getElementByClassName('comments')[0],
comment = document.createElement('div');
comment.innerHTML = commentModel.description;
comments.appendChild(comment);
updateUnreadComments();
}
Response:
(function(addComment){
addComment({ topicId : 'topic1', description : 'haha' })
addComment({ topicId : 'topic1', description : 'lol' })
})(addComment)
Personally I find both methods a rather annoying workaround for nothing more than simple broadcasting.
I was wondering if anyone else has ever had the same problems and if they have ever come up with a more creative solution.
I would also like to know what kind of security issues I could expect with JSONP.
All help is appreciated!
You may take a look at SignalR. Scott Hanselman also blogged about it.

Categories

Resources