How to create an event driven AJAX counter in Rails 3? - javascript

I have a simple User ActiveRecord model class and I need to update a user counter visible in all pages (a partial) each time a new User is created. It should basically look like the download counter for Firefox here. I can imagine writing some JavaScript code that constantly polls the db would do the trick, but I guess that there is some better way to do it. I generally do mostly server-side programming and many UI techniques are quite new to me.
I'm using Rails 3.0.7 with jQuery enabled. I thank you in advance for suggestions/solutions to my predicament.

You could if you want use some kind of WebSockets solution. Which means that you can push the data whenever a new User is created to all the clients, and then just use JQuery to render the Counter area with the new data.
There's also 3rd party apps that makes this push technology really easy to set up. http://pusher.com/ is one of them.
If you want to investigate Node.js there's also Socket.io.
All of these "custom" solutions uses some kind of fallback because WebSockets isn't available in all web browsers. It usually is fallback to Flash Sockets or maybe Long polling.

Related

Best option for continuously refreshing an HTML table (SPA)

We're looking for a simple way to continuously update an HTML table (SPA) to display "orders" received. Currently, we are having to refresh the page every time we want to see the new orders. With my limited front-end knowledge, I can think of 3 ways to do it. I would appreciate advice on the best approach:
1- Making AJAX requests on a regular basis (every 10 seconds?) and then having a JS framework (Vue or React) update the table.
2- Using WebSocket (instead of HTTP) to enable server to push data when such new orders come in.
3- Using a notification service: back-end sends a notification to a topic that client browser is subscribed to. That triggers some code in front-end framework to request new orders from server. Is that feasible?
Again, I have very limited knowledge on how front-end frameworks (VueJS, React) can or can't do. I don't want this to become a full blown project. We're just looking for a simple solution to a (hopefully!) very common use case. Thank you.
It all depends from how many web client instances you expect to be running at any given time.
Polling for data changes even when there are no changes, and doing it from many web clients at the same time could result to a DoS attack to you own infrastructure.
WebSockets or even Server-sent-events should be a more reliable solution.
Implementing the client side is trivial, but doing the actual change detection on the back-end side involves some kind of versioning on your data. Hashing on the database row level should do the trick. There are more sophisticated solutions too.
Can you elaborate further on your use case?
EDITED ANSWER
As mentionned in the comments, Websocket is really the way to go performance-wise, if you plan on having many concurrent requests. Lelio Faieta linked an interesting post in the comments about long polling performance: In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?
OLD ANSWER
If you have to refresh the data every 10 seconds, ajax calls are fine as mentionned in the comments above. This will be easy to implement with jQuery or more advanced frameworks as you mentionned.
Please find below a real short code snippet calling an API every 10 seconds and updating the first row of a table, for example.
window.setInterval(function() {
$.getJSON("https://reqres.in/api/users?page=2", function( data ) {
let length = data.data.length;
let index = Math.floor(Math.random() * length);
$("#myTable td:eq(1)").html(data.data[index].first_name);
})
}, 10000)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="myTable">
<tr>
<td>Name</td>
<td>Value</td>
</tr>
</table>
As you can see this is pretty straight forward to implement, apart from your own data logic needs.
However, you might have incentives to use Websocket instead of Ajax queries. Those has been discussed in this post Why use AJAX when WebSockets is available?
As you mentioned, there are two ways mostly. Most of the applications I have seen if you are using react js (since i dont have any idea on vue), it's fast for rendering data (updating dom - it fits your case).
So for one of our application also we used polling of 15 seconds and it was performing well. In this case what you can do is basically if the tab is not active then you can turn off the polling by checking visibiltyState (chrome and firefox it works perfectly) and you can pause the polling when the tab is not active using this thanks to #oriol this works very well.
As discussed an other good way is socket. You need a backend like nodejs or golang where you will have rooms where you need to emit the data and it will be listened in the front end using some libraries called socket-io
And I have heard of using appollo graphql but never tried it, you can check that also.
I think this will give a better understanding of the problem.
So I think if you can afford in basis of data volume and time, then it's easy to implement the polling with setInterval else mostly everyone suggests sockets.
So I think for a better solution socket will be good, but easy implementation, easy to afford then setInterval from client side.

jQuery alternatives for multiplayer games?

First off, I am not asking for any code or anything like that.
all I need is some advise.
I'm creating a roulette game and everything in my roulette game is based on jQuery.
however, as we all know, jQuery is client side so I was thinking about using AJAX to send some details back to server and from the server to the users browser so I can make this roulette game work in "multiplayer" fashion... But the issue is that I don't think its possible to send the roulette's wheel animation to the server and back to users browser so I am a bit confused about this!
In my research I came across some information (old ones) about using node.js and jquery together! I don't know if this is possible or how easy it would be to use my jquery code in node.js as I have never used node.js before..
so the question that i have is:
based on the information i provided above and my requirements, what are my options?
can I use AJAX to achieve what i am trying to do and if so, a bit
information would be great.
if AJAX is out of question, is it possible to use my jquery code in
node.js to achieve what I am trying to do?
ANY ADVISE WOULD BE APPRECIATED.
P.S. I don't want to use HTML5 as 1st I don't know much about HTML5 and also, some devices, browsers do not support it.
Thanks
The best way is to use websockets to ensure real time communication. One of the best alternatives for implementing that could be using a server under node.js. Have a look to this video from Code School node.js tutorials: https://www.youtube.com/watch?v=mtDK4jf4RS0 where is ilustrated how to implement a real time chat. Your problem is based on the same.
There are three parts to a multiplayer game displayed in a browser:
client-side display,
server-side data management,
client-server communication.
If you're already set on your display technology (jQuery), then you're probably going to use $.ajax() for client-server communication. However, technologies used for server-side data management are completely up to you and they don't necessarily have any connection to the technologies used for display and communication (meaning the traditional communication initiated by client).
Basically, use any kind of server technology stack you like. Node.js might do just fine but there are many other viable alternatives. They just need to support communication with the client.
So, to be absolutely clear, your question doesn't really make sense. You might use jQuery in the client and Node.js on the server, but they will never really "work together". They will manage completely separate parts of your application and connect through protocols not specific to either of them.
As for the animation, the animation itself is solely a client-side problem. If you want to "synchronize the animation" across multiple clients, you can let the clients communicate with the server, but they only ever need to send/receive plain data. Then you adjust the client-side animation based on the received data.
As another poster points out, websockets are a better fit for this than regular client-initiated HTTP requests. Not because of "the animation", but because you want all the clients to receive the information about the start of betting at the same time.
I am also developing a MMO game using javascript only. Firstly, there are two different types of javascript here. Usual client side javascript (the one you already know) and the server side javascript (i.e. Node.js).
You will need to develop both client and server before connecting them with jQuery's Ajax. So you need to study Node.js before designing overall architecture of your game.
I read many Node.js tutorials and watched many youtube tutorial videos but I was still confused, before I really sat down and read a good textbook that explained from basics, one like below. Try to get hold of it from your local library.
Express web application development learn how to develop web applications with the Express framework from scratch by Hage Yaapa
Express is the popular framework that runs on Node.js now. So it's worth getting familiar with Express Framework. Once you understand how express app works (not so difficult), you will see how you can frame your game structure like I did :)
In order for many clients to share same animation, there must a server that synchronizes the game state. Ajax can only link between server-client communication in my understanding. There is no mechanism that connects between clients. The clients ask server what number was the result of roulette roll and show the corresponding animations.
Yes, you can use NodeJS and jQuery together.
NodeJS is server-side, meaning that you set up a server (a lot of people use the Express module, which is easy to use), which serves content to clients asking for it. Your server-side code can be in any language supporting sockets, not just NodeJS. But NodeJS is easy to use if you know JS already.
jQuery is client-side, meaning that it's executed by the user's browser, and may or may not have a server-side component (if it doesn't need it), or it might have one where it sends requests to the server-side code. When it requests a page from the server, it can be static content (like when you request index.html) or dynamic via an AJAX request. Client-side browser code must be HTML/CSS/JS (you can't make Firefox or Chrome interpret C, for example).

How to Implement Push Notifcation in PHP

I have been working with ajax for a while now, and I have used it to do a lot of nifty jobs.. But then my recent challenge has been on push notification.
I want to implement a site that would not need to make a call to the server every period of time, but rather would make a call to the server only when there is an update on a particular DB field, and I want to implement this in PHP, javascript and/or jquery or any other technology for the web. I do not have any idea as to how to go about it, or if it is even possible.
I would like directions on where and how to start, Thanks all.....
Since WebSocket support isn't quite there yet, you would want to fall back on long polling. There already seems to be a jQuery plugin for this:
https://code.google.com/p/jquery-graceful-websocket/
A nice slide on this subject can be found here http://www.slideshare.net/ffdead/the-html5-websocket-api
To implement WebSockets in PHP, have a look at https://code.google.com/p/phpwebsocket/

Javascript based spell-checkers for web applications

I have just received a requirement to implement spell checking on a web application that we are creating. I know all about FF, Chrome, IESpell, etc. but this one is the client's request.
Given that the only way to implement something like this (real time) is with JavaScript libraries, I want to know has anyone tried any of the open source ones? Were they any good? In general, what types of good/bad things can be said about this approach?
I guess going into this, I am against it as it is just more work for the end users's machine to do for little benefit. I guess what I mean by that is that it will be a script that is constantly doing something as opposed to an AJAX request or a quick div update which could lead to seemingly bad performance for our application even though it is a spell checker checking every input field on the page. It seems also that there is lots of room for a javascript error to stall the entire site.
Thoughts?
I agree that a spell-checker should be native if it's running at all times. If the client demands an explicit spell checker, though, it should be implemented as a button to be clicked when needed. It might also be worth firing that XHR request after the user has stopped typing for a certain amount of time, like SO does for syntax highlighting when writing a post.
I used After the Deadline for my school newspaper's back-end spell-checker, since it is powerful, checked for simple grammar errors as well, and integrated easily with TinyMCE. There's also a jQuery plugin to integrate with the service.
I've done some research on this problem for a web application that I am planning.
Googie Spell is very good, you can use their servers or run your own python backend.
There's a demo here.

Reflective Web Application (WebIDE)

Preamble
So, this question has already been answered, but as it was my first question for this project, I'm going to continue to reference it in other questions I ask for this project.
For anyone who came from another question, here is the basic idea: Create a web app that can make it much easier to create other web applications or websites. To do this, you would basically create a modular site with "widgets" and then combine them into the final display pages. Each widget would likely have its own set of functions combined in a Class if you use Prototype or .prototype.fn otherwise.
Currently
I am working on getting the basics down: editing CSS, creating user JavaScript functions and dynamically finding their names/inputs, and other critical technical aspects of the project. Soon I will create a rough timeline of the features I wish to create. Soon after I do this, I intent to create a Blog of sorts to keep everyone informed of the project's status.
Original Question
Hello all, I am currently trying to formalize an idea I have for a personal project (which may turn into a professional one later on). The concept is a reflective web application. In other words, a web application that can build other web applications and is actively used to build and improve itself. Think of it as sort of a webapp IDE for creating webapps.
So before I start explaining it further, my question to all of you is this: What do you think would be some of the hardest challenges along the way and where would be the best place to start?
Now let me try to explain some of the aspects of this concept briefly here. I want this application to be as close to a WYSIWYG as possible, in that you have a display area which shows all or part of the website as it would appear. You should be free to browse it to get to the areas you want to work on and use a JavaScript debugger/console to ask "what would happen if...?" questions.
I intend for the webapps to be built up via components. In other words, the result would be a very modular webapp so that you can tweak things on a small or large scale with a fair amount of ease (generally it should be better than hand coding everything in <insert editor of choice>).
Once the website/webapp is done, this webapp should be able to produce all the code necessary to install and run the created website/webapp (so CSS, JavaScript, PHP, and PHP installer for the database).
Here are the few major challenges I've come up with so far:
Changing CSS on the fly
Implementing reflection in JavaScript
Accurate and brief DOM tree viewer
Allowing users to choose JavaScript libraries (i.e. Prototype, jQuery, Dojo, extJS, etc.)
Any other comments and suggestions are also welcome.
Edit 1: I really like the idea of AppJet and I will check it out in detail when I get the time this weekend. However, my only concern is that this is supposed to create code that can go onto others webservers, so while AppJet might be a great way for me to develop this app more rapidly, I still think I will have to generate PHP code for my users to put on their servers.
Also, when I feel this is ready for beta testers, I will certainly release it for free for everyone on this site. But I was thinking that out of beta I should follow a scheme similar to that of git: Free for open source apps, costs money for private/proprietary apps.
Conceptually, you would be building widgets, a widget factory, and a factory making factory.
So, you would have to find all the different types of interactions that could be possible in making a widget, between widgets, within a factory, and between multiple widget making factories to get an idea.
Something to keep on top of how far would be too far to abstract?
**I think you would need to be able to abstract a few layers completely for the application space itself. Then you'd have to build some management tool for it all. **
- Presentation, Workflow and the Data tier.
Presentation: You are either receiving feedback, or putting in input. Usually as a result of clicking, or entering something. A simple example is making dynamic web forms in a database. What would you have to store in a database about where it comes/goes from? This would probably make up the presentation layer. This would probably be the best exercise to start with to get a feel for what you may need to go with.
Workflow: it would be wise to build a simple workflow engine. I built one modeled on Windows Workflow that I had up and running in 2 days. It could set the initial event that should be run, etc. From a designer perspective, I would imagine a visio type program to link these events. The events in the workflow would then drive the presentation tier.
Data: You would have to store the data about the application as much as the data in the application. So, form, event, data structures could possibly be done by storing xml docs depending on whether you need to work with any of the data in the forms or not. The data of the application could also be stored in empty xml templates that you fill in, or in actual tables. At that point you'd have to create a table creation routine that would maintain a table for an app to the spec. Google has something like this with their google DB online.
Hope that helps. Share what you end up coming up with.
Why use PHP?
Appjet does something really similar using 100% Javascript on the client and server side with rhino.
This makes it easier for programmers to use your service, and easier for you to deploy. In fact even their data storage technique uses Javascript (simple native objects), which is a really powerful idea.

Categories

Resources