How to use AJAX with node.js - javascript

I am relatively new to server side programming, however I am building a framework in order to learn and as end outcome deliver it to the public after it is finished.
I want some parts of the web platform to be able to update only parts of the page on requests, however I do not know anything about AJAX yet.
It would be great if someone could suggest a sort of learning curve to what I am aiming for. Kinda SoundCloud like website, with the ability to update only those parts of the DOM which are requested.

Note: I'm kind of new at this as well, so a grain of salt is advised. I detail a technique that is working for me, but I make no guarantees that it is The Best Way!
AJAX is on the client side and is achieved through either standard javascript (a pain which I wouldn't recommend in most cases) or through a library like jQuery. There are a plethora of tutorials on using jQuery for ajax calls, but the gist is that you are requesting some resource on your server that, when it arrives, calls a callback which does something with the data (this behavior is asynchronous, just as node.js tends to be).
If you have no experience using AJAX for the client, I suggest you start off with a framework like Express, before rolling your own (this also gets into reinventing the wheel). An AJAX call is no different than a standard HTTP request: it can be POST, GET, etc.
You then get into the concept of routing: given a request for some information (AJAX or not!), what should I do and what should I return? A framework does the behind-the-scenes stuff for you, so that all you need to do is specify the resource to be requested, the method in which it is requested, and then the callback which does the server-side processing which returns some data. This data can be a web page, it can be a JSON object, and so on. The key point is that you want to structure it in a way that makes sense for the AJAX call.
Here is a simple example: say I have a web page that will display a bunch of information relevant to the server, such as uptime, load, memory usage, and so forth. First, I write the basic HTML page (say, index.html) that structures this data, and I begin to write a script that makes an AJAX call for this information. I decide that the request (say, /json/stats) will receive a JSON response. On the server-side, I whip up a simple Express script which starts the server and has two routes: the first route will take any request for my / page and serve the index.html. The second route will take any request for /json/stats and make a few calls to figure out the state of the server, construct an object holding this data, and return it as a response. Now, back in the script for my HTML page, I can act on the structure of this object through jQuery in order to build the page.
If you'd like to see some code for this, you can view it here. I suggest looking into the REST architecture (of which this code adheres to) as to gain more conceptual understanding of this topic.

Related

I have trouble entering URLs in the address bar when creating routes with vanila javascript

I am trying to create routes with vanilla javascript but every time I type a URL in the address bar I get an error saying, 'Cannot GET /about'. I am requesting a link to a tutorial or an answer to this kind of problem since it is my first time doing it with vanilla javascript and I have no clue.
Taking "Vanilla JavaScript" to mean "JavaScript, running in the browser, without the use of third-party libraries":
What you want is not (reasonably) possible.
When you type a URL into the address bar, the browser makes an HTTP request to that URL, and the HTTP server for the origin of the URL (i.e. the scheme + hostname + port) is responsible for delivering something (typically a webpage) back to the client.
You can't substitute client-side JavaScript for that initial request to the HTTP server.
There is an edge case. I think a progressive web app can use a service worker to intercept the request and generate a response internally. This is no good for handling the initial request though since the PWA wouldn't be installed at the time.
Generally, when you are writing a single page application you will need two parts for your URL handling.
The first part is the History API. This allows you to write JavaScript which tells the browser:
In response to the click the user just performed, I am going to update the DOM. If you were to visit this URL then you would get the same result as the changes I am making to the DOM, so go ahead and update the address bar to represent that.
It also lets you hook into the browser's back navigation so you can undo those changes if the user click's back.
The second part is where you make sure that the server really does deliver the same content for that other URL.
There are three strategies for achieving this:
Have the server return a more-or-less empty HTML document that checks the URL as it loads and then populates itself entirely with JavaScript. This is a poor approach which might as well just use hash bangs.
Generate all the HTML documents in advance. This is a strategy employed by Gatsby and Next.js. This is very efficient, but doesn't work for frequently updated content.
Generate the HTML documents on demand with server side code. Next.js can do this too.
You can do this when you write vanilla JavaScript (kinda), but it takes a lot of work since you need to write all the code to run on Node.js (where you might not count it as vanilla any more) to generate the HTML documents. I strongly recommend using a framework.

Best practice for passing data to JavaScript in Django

When writing a view in Django, there are several ways to pass a list of data to javascript. Some of the methods I found are:
Passing the data in the response text by serializing into JSON and assigning into a JavaScript variable,
Passing the data via an AJAX request after the page is loaded. There are also two ways for this:
Sending a POST request to the same URL,
Sending a request to another URL
Which method is the most reliable one?
I think this really comes down to personal preference. I prefer option 1 because it means the client side has less work to do, which (potentially) can make the page load faster. I also use Memcache pretty extensively on the server side so my database has less to do.
Of course, whether this matters has a lot to do with what your app is trying to accomplish. Mine pulls a good amount of data from the database every time a view is called, so it's beneficial for me to do it this way.
Something else to think about is that doing everything server-side avoids having to deal with CORS/CORB issues. If you own the API it's no big deal because you can adjust your CORS headers, but its something to think about. I've had some difficulties with CORS depending on the APIs I'm trying to interact with and I've made it my policy to never pull from an API on the client side if I can avoid it. Just makes life easier.

Pattern for multiple requests to REST server

So let's say I have a typical REST server that serves some data in a very specific manner, like: GET accounts, GET prices, GET inventory, GET settings, GET user_history, etc...
A single view, let's say, needs to fetch N different specific resources like this. What's the best technique/library/pattern for combining N HTTP requests into one without too much hassle?
Maintaining the "REST" idea would require writing new server code for every view because no two views would need the same set of resources. Doing this would become unnecessarily cumbersome in my opinion. I guess the only way that makes sense is to roll your own DSL that presents your data requirements to the server.
What's the easiest alternative to writing new response code for every possible combination of a given view's resource requirements?
You say this is a rest service, all you need to do is getting information, Why not issue a jsonp request?
issue a jsonp request for every get that you need, instead of writing a new response code for each and every get. It will save you alot of code and will enhance performance.
In conclusion, I would send a jsonp request to the server (given it's an external server of course) in order to get all the data that I need, while issuing ajax calls to the server.
issuing jsonp request to the same domain using .NET

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.

How does one do realtime updates of a web page?

Google's GMail service does it because it integrates Google Talk -- and Etherpad (now typewith.me) made famous the system which is used by, for example, Google Wave. All such systems update the page the user is working on effectively instantly when other users make changes to the page. It's easy to tell the server that a change has happened when it has happened, but it's more difficult to get clients to update themselves.
How does this kind of realtime editing work? Does it simply have the client ping the server tens of times per second for updates?
You can use Comet.
Asynchronous JavaScript and XML or AJAX
With Ajax, web applications can retrieve data from the server asynchronously in the background without interfering with the display and behavior of the existing page. The use of Ajax techniques has led to an increase in interactive or dynamic interfaces on web pages. Data is usually retrieved using the XMLHttpRequest object. Despite the name, the use of XML is not actually required, nor do the requests need to be asynchronous.
Just in case someone falls on that question.
Comet was an old way of doing real-time updates, now it has been made obsolete by technologies like websockets
I suggest using AJAX & jQuery for Asynchronous JS
http://api.jquery.com/category/ajax/
There are many options but basically i'd recommend you look into XMPP. i don't think i'm good enough to boil it down correctly, so i'll let a wiki talk for me
In fact, google voice and video uses it for these systems.
About AJAX, i think it's a communication channel, not a platform or a protocol for multiple person exchange. You could also answer "Use xml over http!" and still be at the same point :)
AFAIK, they use some form of AJAX. However, I would recommend you use the AJAX libraries via jQuery. AJAX is simplified a lot if you use jQuery to do it.
Javascript / Ajax allows you to send code to be executed on the client-side (that means, by the browser).
Now if you e.g. define a loop which checks for new messages on server every 5 seconds, you can update the web-page "in-real-time" (plus the time for the server to process the req and send response), or similar. A practical example would be the RoR Prototype periodically_call_remote Ajax helper.
Hope this helps!
As everyone says.. AJAX.
The client keeps on asking the server, after say 30 secs if there is anything new for it to do. Also, you can set the timeout value on an ajax request. keep the time out a bit high.. and the server replies whenever there is something new.
There is no way that the server can other wise ask the client to load some data.
If you are thinking of implementing something on the same lines, look up strophe.js which is an XMPP js-library
It can be done via POlling and Push design.
Polling is a client side information pulling technique after a given timeperiod.
Push technique involves the server to push the new updates to the client using websockets or new websocket like technology for example pusher.
Article

Categories

Resources