Integer variable common for all sessions in node.js - javascript

How to have an integer variable common for all client sessions in node.js and access them in client html? (that is, I need a integer variable which can be displayed in the html page and can be updated in html page. The new updated value should be displayed for other clients.) I knew this is a silly question. But I am sorry. I am totally new to node.js and I do not have much time. I need a solution at the earliest. Thank you.

There are multiple options for getting the common variable into a web page:
You can embed an actual <script> tag with the variable in every page that is served from the server. This technique would be easiest if using a template engine so that a common sub-template can be included in every page.
You can have each page send an ajax call to the server when it first loads to fetch the value of the variable.
You can have each page create a webSocket connection to the server when it first loads and then when the server receives the connection, it can send back the value of the variable.
When the client wants to update the variable, it has a couple options for informing the server:
If using the webSocket connection above, it can just send a message to the server that the variable has been uddated and send the new value. The server can then broadcast to the other webSocket-connected clients what the new value is.
If using the either of the other two options above, then whenever the client wants to change the value, it can issue an ajax call to the server to update the value. Other than the webSocket option above, the only way for the other clients to know when the value of the variable changes is for each client to regularly poll the server asking to fetch the current value of the variable (say every 30 seconds or so). This is not particularly efficient.
Because part of your problem is for all connected clients to know when the variable has change, you need the ability for the server to "push" an updated value to all clients. This is what webSockets were invented for and would likely be the recommended option.

Related

How does two client javascript files interact with each other, when the server is running separately?

I have created a django application. There are two different html pages, which run different scripts in each other. I want to share data between the two script files, so while I update the variables in one script, I can send the updated data to the other script file, and make the corresponding changes to the variable present in the other script file.
As I researched, one way I found to do that is to use websockets, where a regular connection is built with the django server and the client. But, it is limited to single client. So, through websockets, I can not share data between two different client pages. What other methods, can I use to share data between the two script files in the client?
Edit 1: The changes in one script file has to be reciprocated instantly or after really less time delay in the second script file.
Edit 2: The clients for the server can be running on different devices(one on phone and other on computer). Thus, having a solution to save data in localstorage doesnt work
Edit 3: I tried making api calls. The instant change in variable happens in one script file, an api call is made that makes change in the database. While, the other script is constantly making api calls at regular intervals to get the value of the variable that is saved. But, this creates a time delay, and therefore, was looking for a websocket like solution, where instead of communication between server and client, we have communication between two different clients operating in the same server
Use built in window.localStorage to store things on the clients browser for the life of the session. See https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage for reference.

How to refresh the view using websocket getting the data from database

I need to refresh a part of my view without refreshing the whole page.
At my index.html page I have three panels, wich one shows the number of Tickets by it's status, I need to refresh this number every time a new ticket is created or updated. I used Java with Spring Boot and Thymelaf to build my application.
This is my view:
This is the way I'm doing it now:
model.addAttribute("resolvedTickets", atendimentoService.findAllTicketsByStatus(STATUS_RESOLVED).size());
I have tried to use web sockets but i can't figure out how to get this and refresh the panels.
In a standard web interaction, the client (i.e. your web browser) sends a request to your server. Your server receives the request, and sends back the information to show in your browser and then terminates the connection.
WebSockets are a way to create a persistent, two-way connection between the client and the server, but it requires cooperation from both. A lot of shared servers don't allow WebSockets, so you first have to make sure your server is capable of providing WebSockets. (I see from your screenshot that you're running on Heroku, which should have no problem running WebSockets.)
On the server side, you need to set up handling for incoming WebSocket requests. I don't know what language you've coded your server in, so I can't provide any guidance, but there are plenty of libraries that do the server-side part of WebSockets in most languages.
On the client side, you need to set up your WebSocket client. MDN has a great guide on WebSockets that explains what you'll need to do. Basically, all you'll have to do is listen for incoming messages and increment your counter.
var count = 0;
var exampleSocket = new WebSocket("ws://example.com/socket");
exampleSocket.onmessage = function(event) {
count++;
document.getElementById('myTicketCounter').innerHTML = count;
}
For some things, WebSockets are overkill. If you find that this is too much work for too little reward, you can also just set up an AJAX call to fire every few minutes that pings another page on your server and returns the number of tickets and updates accordingly. It won't be instantaneous, but if you don't need down-to-the-second resolution, it'll probably suffice. You can adjust the interval to be as long or as short as you want (to an extent; bombarding your server with constant requests will slow you down a bit).

Establing connection to MYSQL Database [PHP]

I had this random question in my mind while I was surfing on the net...
Is it possible to establish connection to MYSQL database WITHOUT refreshing? Like if there is a button in a page which when clicked it secretly establishes connection to Database without even letting user notice any change in the webpage, Everything looks the same but secretly a webpage connects to the database..
I know.. This process is possible in Javascript, but I wanted to find out a way in PHP
When the page has been loaded. PHP can't be used anymore because it's a server side language. Javascript on the other hand works client side. Which means you can execute functions and such on the client's machine without page reload.
AJAX can enable you to 'open' a PHP and execute PHP code (not JS) without page reload. If you will, it's like you're opening a PHP page but it's not visible to the user, it runs the PHP file 'behind'.
As others have said, remember that PHP is a "server-side" language, and that the SQL database also lives on the "server side." The JavaScript application, running on the client, has no direct access to it.
What the JavaScript application must do, then, is to issue asynchronous requests ("AJAX ...") to the server, asking for whatever it wants. The end-user will not be directly aware that this is going on, and the content of the screen-display won't necessarily change (unless you change it).
As part of servicing the (properly authorized ...) request, the PHP side might connect to the database and issue queries against it to get the information that it needs, in order to prepare and send-back a reply to the (JavaScript) client.
Now, the JavaScript side won't necessarily know, nor will it care, just how the results that it receives were actually obtained by the PHP code. It only "issues a request, and, sometime thereafter, gets a corresponding answer."

Is it possible to make server push without using javascript?

Is there some mechanism to provide server push technology using plain HTML, without using javascript (or any other script languages on the client side).
Under "server push" I mean process where the server to update some part of the page content when needed.
I don't know of any way that true server push can be used without any javascript in the page.
Without javascript, the only thing I'm aware of is a meta refresh tag that would tell the browser to refresh this page after some particular time interval. This tag applies to a whole page only. If you wanted only part of a page to be updated, you could use an iframe and have only the iframe be updated. Of course, this is not server push, but a client-driven auto-update and it will be run on a predetermined interval, not just when there is actually new data. For something smarter than this, you will need javascript.
The most efficient server-push would be to use javascript from the page to connect to your server over a websocket and then have the server just send data to the page via the websocket whenever it wants (true server-push). The client's javascript can then respond to the receipt of that websocket data by updating a particular piece of the page.

How to update web application with data every n minutes

I want to create a web application that displays data from a public api. I will use d3 (a javascript data-visualization library). I want to retrieve data from the api every ten minutes, and update my page (say it is traffic, or something). I have not built many web applications, how do I get the updates?
Should the js on the client side use a timer to request updates from the server side of my application (perhaps the application is written in Rails or node.js). The server then makes the api call and sends a response asynchronously? Is this called a socket? I have read that HTML5 provides sockets.
Or, perhaps an AJAX request?
Or, does the server side of my application create a timer, make the api call, and then "push" updates to the view. This seems wrong to me, there could be other views in this application, and the server shouldn't have to keep track of which view is active.
Is there a standard pattern for this type of web application? Any examples or tutorials greatly appreciated.
An AJAX request (XMLHttpRequest) is probably the way to go.
I have a very simple example of an XMLHttpRequest (with Java as the backend) here: https://stackoverflow.com/a/18028943/1468130
You could recreate a backend to receive HTTP GET requests in any other server-side language. Just echo back whatever data you retrieved, and xmlhttp.onload() will catch it.
Depending on how complex your data is, you may want to find a JSON library for your server-side language of choice, and serialize your data to JSON before echoing it back to your JS. Then you can use JavaScript's JSON.parse() method to convert your server data to an object that can easily be used by the client script.
If you are using jQuery, it handles AJAX very smoothly, and using $.ajax() would probably be easier than plain-old XMLHttpRequest.
http://api.jquery.com/jQuery.ajax/
(There are examples throughout this page, mostly-concentrated at the bottom.)
It really annoys me how complicated so many of the AJAX tutorials are. At least with jQuery, it's pretty easy.
Basically, you just need to ask a script for something (initiate the request, send url parameters), and wait for the script to give you something back (trigger your onload() or jqxhr.done() functions, supplying those functions with a data parameter).
For your other questions:
Use JavaScript's setTimeout() or setInterval() to initiate an AJAX request every 600000 milliseconds. In the request's onload callback, handle your data and update the page appropriately.
The response will be asynchronous.
This isn't a socket.
"Pushing" probably isn't the way to go in this case.
If I understand correctly and this API is external, then your problem can be divided into two separate sub-problems:
1) Updating data at the server. Server should download data once per N minutes. So, it should not be connected to customers' AJAX calls. If two customers will come to the website at the same time, your server will make two API call, what is not correct.
Actually, you should create a CRON job at the server that will call API and store its' result at the server. In this case your server will always make one call at a time and have quite a fresh information cached.
2) Updating data at clients. If data at customers' browsers should be updated without refreshing the page, then you should use some sort of Ajax. It can make a request to your server once per X minutes to get a fresh data or use so-called long-polling.
I think the most effective way to implement real time Web application is to use Web socket to push changes from the server rather than polling from the client side. This way users can see changes instantaneously once server notify that there is new data available. You can read more on the similar post.
I have tried using nodejs package called socket.io to make a real time virtual classroom. It works quite well for me.

Categories

Resources