Best practice for passing data to JavaScript in Django - javascript

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.

Related

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 to use AJAX with node.js

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.

Best way to pass a query result to another page

Quick question:
I have a page that makes an AJAX call to my SQL server and receives an XML response. I parse the XML and display the relevant data in a table.
I have a button on the page that is used to display the table data in a simple line graph on a new page. Currently, I just re-query the database and to re-get the data and create a new array object of that data for my graph.
The GET can take up to 2.5 seconds, with the final graph time to render being about 8-9 seconds. I am investigating any alternatives to re-GET'ting the data.
So far I have:
localStorage (HTML5)
php pass me the data instead of querying the DB
jquery plugin (DOMCache)
Any thoughts on this or best practices??
thanks for any input!
You might do best to just make sure the response is cached in your users' browsers. There are a variety of ways to make this happen (variant upon the framework your server is running, browsers that your clients are using, etc etc), but the long story short is that relying upon caching will alleviate you from having to jump through performance hoops by making modifications to your codebase.
IE8+ is actually a kingpin in this area (much as I hate to admit it). Its aggressive caching of ajax responses is usually a serious pain in the arse, but in this case would prove valuable to your scenario.
Edit -
You mentioned SQL Server, so I'm making the assumption that you're running through an ASP.NET middle tier. If that's the case, here's an interesting article on caching ajax requests on the server and the client with the .NET framework.

Help! me with "AJAX"

I am working around AJAX for few months now and i see Ajax request as following,
Pass parameters to background page (PHP/ASP/HTML/TXT/XML ... what else can be here?)
Do some processing on server
Get back the results and show to client (HTML/XML/JSON ... what else can be here?)
If there is something else to add on Request lifecycle please I will be glad to know?
Now I have some questions around AJAX and i will try to frame them one by one.
How many concurrent AJAX request can be made?
Yes there is timeout period in AJAX but considering the web2.0 scenarios and possibilities with the Network what is the timeout period? Best practice?
Consider scenario that if user invoke AJAX Request and it’s in process on the server and meanwhile user left the page. Will the processing on the server will be left in haft way? Or all the execution on server will be done and response is sent back to browser? What will happen?
Is it a strict requirement that we should have a server page (PHP/JSP/ASP) to take the AJAX request? As with this approach considering wide use of AJAX now a day, on server we need page per request (or few pages to server more than one request) which is something become difficult to maintain.
Can we have something else instead of server side page (PHP/ASP etc.) like web service or something which can be directly requested from AJAX (JavaScript) like URL? If yes how? This can reduce need of additional server side pages.
AJAX request also supports the Authentication. In what scenario this is used? Is it mandatory?
Comet is something which I heard lot about. My understanding is that it’s just some pattern in which AJAX is used to get updated data by using polling mechanism. Is it right? Please provide your views/insight.
Security risk using AJAX? How can it can be mitigated (Encryption/Decryption or something else)?
Thanks all,
Depends on the browser. It follows the same rules as concurrent HTTP requests everywhere else in the browser.
Ditto.
Pretty much the same as the user hitting the Stop button on a regular page.
An HTTP request must request a URI. How you handle that on the backend is up to you. The term "page" doesn't really fit — that is an HTML document with associated resources (stylesheets, images, etc). Most systems don't have a 1:1 mapping between server side programs and resources. In an MVC pattern, for example, it isn't uncommon to have a shared model and a controller that just switches between views for determining if to return an HTML document or the same data expressed in JSON.
A web service is just a server side program that responds in a particular way, lots of people write them using PHP, JSP or ASP so the question doesn't really make sense.
No, it isn't mandatory. You use authentication when you need authentication. There is no special "ajax authentication", that is usually just using the same cookies that are used everywhere else in the site.
No, the point of Comet is to avoid polling. See http://en.wikipedia.org/wiki/Comet_%28programming%29
Requests containing data are sent to the server. Responses containing data are returned from the server. The security implications are no different to any other HTTP request you handle.
You must use the URI to use it

Categories

Resources