JavaScript: Timer to refresh content of elements with same class - javascript

There is a web app I am designing. I'm using AngularJS on the front-end with a Java back-end. The web app is being deployed in a war file to a local JBoss server. I currently have a Java class that performs a series of calculations and sends that data as JSON to the client every 10 seconds. This works, but I want to update the elements that contain this data with AJAX(?).
In Angular I have a few $resource services that consume the Java RESTful API. This is all JSON data, which is the being propagated into the view by a single controller. I then have some HTML elements generated by ng-repeat that all have the same classes. I wanted to use one of these classes to trigger a refresh on all of the elements every 10 seconds. Here is a snippet with the ng-repeat I am talking about:
<div ng-repeat="mq in mqDepth">
<progressbar class="mq" max="max" value="dynamic" ng-init="dynamic=mq.currentDepth" type="info>
<span>
{{dynamic}} / {{max}}
</span>
</progressbar>
</div>
In the above snippet, the data that's being updated is mq.currentDepth.
And this is the code I am using to refresh:
function refreshQueue() {
$('.mq').load('', function() {
$(this).unwrap();
});
}
refreshQueue();
setInterval(function() {
refreshQueue();
}, 10000);
I get a warning that basically states the way I am implementing AJAX will break my user interface, which it does after a series of updates.
Synchronous XMLHttpRequest on the main thread is deprecated because of its detrimental effects to the end user's experience. For more help, check http://xhr.spec.whatwg.org/.
I have a few questions
Can you update the contents of an element with a class in AJAX, or does that only work with IDs?
Should I be using AJAX to refresh the page?
If not, then how would I implement that with Angular?

Doing synchronous network calls from javascirpt will block the main thread, which may block your UI and hence is not adviced. To answer your questions.
When you are using angular, you shouldn't access the elements using class or ids (using selectors), the way we use to do with jQuery. Instead you should use data-binding.
You do not need AJAX to refresh the page.
You can use your existing $resources for retrieving data. Once you have the data in controller, save that in a scope variable. Then you can use the same variables in your HTML using angular-expression to update the data.
$scope.mqDepth = MqDepth.get({ id: id });

Related

data persistence across elements

suppose I want to have a data provider element for my user, like
<user-data-provider user-data="{{data}}"></user-data-provider>
which sends an ajax request and gets the logged in user.
Suppose I want to access my user data in different pages, and I add this tag to wherever I need, but the problem is, every time the browser sees this tag, makes an ajax again and I have to wait until data is fetched!
I know I can make a variable in my main page and pass it along child pages, but that seems like overkill to me !
how can I persist user data across different pages and part of my app?
thank you in advance
There are different ways to do this.
You can use use a monostate pattern
You can have one instance of your user-data-provider element in your root element or index.html and use iron-signals to transmit the data to all other elements that want to consume it
You can use iron-meta to have global state
Use an external state management framework (i.e. redux). There is a polymer wrapper for it: polymer-redux
I would recommend using an external state mangement framework such as redux.
Some of the solutions are shown here:
Polymer 1.0 Global Variables
I used pouchdb for my data store, and used polymer's predefined elements to work with it
now every time that I need data, I just use that component

How can I chunk results (lazy load?) without rewriting my whole application (Laravel + jQuery, SPA style)

I've developed a web application with the concept of Single Page Application but none of the modern techs and frameworks.
So I have a jQuery page that dynamically requests data to localhost - a Laravel instance that compiles the entries in the DB (within a given time interval).
So the client wants to see all the entries for last week, the app works fine. But if he wants to see the results for the whole last month... well, they're so many that the default execution time of the php ins't enough to process all the data (30 seconds). I can easily override this, of course, but then the jQuery client will loop through these arrays of objects and do stuff with them (sort, find, sum...). So I'm not even sure jQuery can handle this many data.
So my question can be broken in two:
Can laravel ->paginate() be used so the ajax request of jQuery can also chunk the data? How does this work (hopefully in a manner that doesn't force me to rewrite all the code).
How could I store large amounts of information on the client? It's only temporary but the users will hang around for a considerable amount of time on my webpage, and I don't want them to wait 5 minutes every time they press a button
Thanks.
If you want to provide an interface to a large amount of data stored in a backed, you should paginate the data. This is a standard approach, so I'm sure your client will be ok with that.
Using pagination is pretty simple - see the docs for Laravel 5.0 here: http://laravel.com/docs/5.0/pagination
In order to paginate results in the backend, you need to call paginate($perPage) on your query instead of get() in your controller, like that:
$users = User::whereIsActive(true)->paginate(15);
This will return paginated result with 15 records per page. Page number will be taken from page parameter of the request. In order to get 3rd page of users, you'll need your frontend jQuery app to send a request to URL like:
/users?page=3
I don't recommend caching data in the frontend application. The data can be changed by some other user and you won't even know about it. And with pagination, your requests should be lightweight enough to stop worrying about a request sent to fetch every page of results.
Not sure if you're subscribed to laracasts but Jeffery Way is amazing in explaining features of Laravel and I highly recommend his videos.
In short you can paginate the results, then on the view when you call the foreach on your items you can array_chunk() the results to display them how you need to. But the paginated results are going to be fetched using a query in the URL, and i'm not sure that is what you want if you're already using a lot of jQuery to keep everything on the same page.
https://laracasts.com/lessons/crazy-simple-pagination
But assuming you're already paginating the results with whatever jQuery you've already written for the json data...
You could also use a query scope to get the data you need to for the amount of time to scope to create a simple api to use with ajax. I think that's probably what you're looking for.
So here's what I would do assuming you're already doing some pagination manually with your javascript.
Create a few query scopes to filter the data for different lengths of time
Create simple routes to fetch results from URI using the query scopes
Get the json data from the route preforming an ajax requests to the URIs created
More information on Query Scopes: http://laravel.com/docs/5.1/eloquent#query-scopes

Javascript: How to show hide divs based on security role

I have been using JQuery and AngularJS. One requirement I had was to show/hide divs and other widgets based on the login user role. I implemented the solution as below:-
On page load, get role of logged in user and store as a global variable in javascript
Show complete page
Hide divs using simple if statements based on security role
Is this the best way? Isn't there some framework or library for this? Doesn't AngularJS have anything to help?
Btw I understand that server side security is a must in spite of controlling what widgets login user can see in browser.
You could look at something like Angular Schema Forms. This takes a JSON object and will render it out using templates as HTML.
Another approach would be to use a template for each widget and then check the role before retrieving the template. If the template isn't retrieved then your custom tags will remain empty and have no content.
if isAuthorized
get template
else
do nothing or remove the element (your call)
The benefit of the first is that your markup is generated from server side data and thus has the extra benefit of being more secure. The second will work as well however.
Do note that you can change ANYTHING in javascript including global variable and javascript code in client side, so your server CANNOT TRUST THE CLIENT.
It's fine if you want to show/hide div based on the global variable, but your server should NEVER use that global variable to determine user permission. And for the div's that are hidden, you should NOT populate them with data from DB, so even when client change the CSS, they can't see data that is not permitted. Not to mention they can always inspect the network to see what is inside the JSON returned.
Usually you don't need to store as global variable, though. If your user does proper authentication, you should verify his identity for every transaction (every ajax request) and return only relevant content. In Angular view you can do ng-if when data exists only.

Page Load alternative in a Pure HTML AJAX Website

I am working on a pure HTML website, all pages are HTML with no relation to any server side code.
Basically every request to the server is made using AJAX, I send data from forms, I process this data in Handlers, then I return a JSON string that will be processed back on the client side.
Let's say the page is loaded with parameters in the URL, something like question.html?id=1. Earlier, I used to read this query string on Page Load method, then read data from the database and so on...
Now, since its pure HTML pages, I'm trying to think of an approach that will allow me to do the same, I have an idea but its 99% a bad idea.
The idea is to read URL parameters using JS (after the page has loaded), and then make an AJAX request, and then fetch the data and show them on the page. I know that instead of having 1 request to the server (Web Forms), we are now having 2 Requests, the first request to get the page, and the second request is the AJAX request. And of course this has lots of delays, since the page will be loaded at the beginning without the actual data that I need inside it.
Is my goal impossible or there's a mature approach out there?
Is my goal impossible or there's a mature approach out there?
Lately there are a good handful of JavaScript frameworks designed around this very concept ("single page app") of having a page load up without any data pre-loaded in it, and accessing all of the data over AJAX. Some examples of such frameworks are AngularJS, Backbone.js, Ember.js, and Knockout. So no, this is not at all impossible. I recommend learning about these frameworks and others to find one that seems right for the site you are making.
The idea is to read URL parameters using JS (after the page has loaded), and then make an AJAX request, and then fetch the data and show them on the page.
This sounds like a fine idea.
Here is an example of how you can use JavaScript to extract the query parameters from the current page's URL.
I know that instead of having 1 request to the server (Web Forms), we are now having 2 Requests, the first request to get the page, and the second request is the AJAX request. And of course this has lots of delays, since the page will be loaded at the beginning without the actual data that I need inside it.
Here is why you should not worry about this:
A user's browser will generally cache the HTML file and associated JavaScript files, so the second time they visit your site, the browser will send requests to check whether the files have been modified. If not, the server will send back a short message simply saying that they have not been modified and the files will not need to be transmitted again.
The AJAX response will only contain the data that the page needs and none of the markup. So retrieving a page generated on the server would involve more data transfer than an approach that combines a cacheable .html file and an AJAX request.
So the total load time should be less even if you make two requests instead of one. If you are concerned that the user will see a page with no content while the AJAX data is loading, you can (a) have the page be completely blank while the data is loading (as long as it's not too slow, this should not be a problem), or (b) Throw up a splash screen to tell the user that the page is loading. Again, users should generally not have a problem with a small amount of load time at the beginning if the page is speedy after that.
I think you are overthinking it. I'd bet that the combined two calls that you are worried about are going to run in roughly the same amount of time as the single webforms page_load would if you coded otherwise - only difference now being that the initial page load is going to be really fast (because you are only loading a lightweight, html/css/images page with no slowdown for running any server code.
Common solution would be to then have a 'spinner' or some sort (an animated GIF) that gives the user an visual indication that the page isn't done loading while your ajax calls wait to complete.
Watch a typical page load done from almost any major website in any language, you are going to see many, many requests that make up a single page being loaded, wether it be pulling css/images from a CDN, js from a CDN, loading google analytics, advertisements from ad networks etc. Trying to get 100% of your page to load in a single call is not really a goal you should be worried about.
I don't think the 2-requests is a "bad idea" at all. In fact there is no other solution if you want to use only static HTML + AJAX (that is the moderm approach to web development since this allow to reuse AJAX request for other non-HTML clients like Android or iOS native apps). Also performance is very relative. If your client can cache the first static HTML it will be much faster compared to server-generated approach even if two requests are needed. Just use a network profiler to convince yourself.
What you can do if you don't want the user to notice any lag in the GUI is to use a generic script that shows a popup hiding/blocking all the full window (maybe with a "please wait") until the second request with the AJAX is received and a "data-received" (or similar) event is triggered in the AJAX callback.
EDIT:
I think that probably what you need is to convert your website into a webapp using a manifest to list "cacheable" static content. Then query your server only for dynamic (AJAX) data:
http://diveintohtml5.info/offline.html
(IE 10+ also support Webapp manifests)
Moderm browsers will read the manifest to know whether they need to reload static content or not. Using a webapp manifest will also allow to integrate your web site within the OS. For example, on Android it will be listed in the recent-task list (otherwise only your browser, not your app is shown) and the user can add a shorcut to the desktop.
So, you have static HTMLs and user server side code only in handlers? Why you can't have one ASP .Net page (generated on server side) to load initial data and all other data will be processed using AJAX requests?
if its possible to use any backed logic to determine what to load on server side, that will be easy to get the data.
say for example if you to load json a int he page cc.php by calling the page cc.php?json=a, you can determine from the PHP code to put a json into the page it self and use as object in your HTML page
if you are using query string to read and determine, what to load you have to make two calls.
The primary thing you appear to want is what is known as a router.
Since you seem to want to keep things fairly bare metal, the traditional answer would be Backbone.js. If you want even faster and leaner then the optimised Backbone fork ExoSkeleton might be just the ticket but it doesn't have the following that Backbone proper has. Certainly better than cooking your own thing.
There are some fine frameworks around, like Ember and Angular which have large user bases. I've been using Ember recently for a fairly complex application as it has a very sophisticated router, but based on my experiences I'm more aligned with the architecture available today in React/Flux (not just React but the architectural pattern of Flux).
React/Flux with one of the add-on router components will take you very far (Facebook/Instrgram) and in my view offers a superior architecture for web applications than traditional MVC; it is currently the fastest framework for updating the DOM and also allows isomorphic applications (run on both client and server). This represents the so called "holy grail" of web apps as it sends the initial rendered page from the server and avoids any delays due to framework loading, subsequent interactions then use ajax.
Above all, checkout some of the frameworks and find what works best for you. You may find some value comparing framework implementations over at TodoMVC but in my view the Todo app is far too simple and contrived to really show how the different frameworks shine.
My own evolution has been jQuery -> Backbone -> Backbone + Marionette -> Ember -> React/Flux so don't expect to get a good handle on what matters most to you until you have used a few frameworks in anger.
The main issue is from a UX / UI point of view.
Once you get your data from the server (in Ajax) after the page has been loaded - you'll get a "flickering" behavior, once the data is injected into the page.
You can solve this by presenting the page only after the data has arrived, OR use a pre-loader of some kind - to let the user know that the page is still getting its data, but then you'll have a performance issue as you already mentioned.
The ideal solution in this case is to get the "basic" data that the page needs (on the first request to the server), and manipulate it via the client - thus ease-in the "flickering" behavior.
It's the consideration between performance and "flickering" / pre-loading indication.
The most popular library for this SPA (Single Page Application) page - is angularJS
If I understand your inquiry correctly. You might want to look more about:
1) window.location.hash
Instead of using the "?", you can make use of the "#" to manipulate your page based on query string.
Reference: How to change the querystring on the same page without postback
2) hashchange event
This event fires whenever there's a changed in the fragment/hash("#") of the url. Also, you might want to track the hash to compare between the previous hash value and the current hash value.
e.g.
$(window).on('hashchange', function () {
//your manipulation for query string goes here...
prevHash = location.hash;
});
var prevHash = location.hash; //For tracking the previous hash.
Reference: On - window.location.hash - Change?
3) For client-side entry-point or similar to server-side PageLoad, you may make use of this,
e.g.
/* Appends a method - to be called after the page(from server) has been loaded. */
function addLoadEvent(func) {
var oldonload = window.onload;
if (typeof window.onload != 'function') {
window.onload = func;
} else {
window.onload = function () {
if (oldonload) {
oldonload();
}
func();
}
}
}
function YourPage_PageLoad()
{
//your code goes here...
}
//Client entry-point
addLoadEvent(YourPage_PageLoad);
Since you're doing pure ajax, the benefit of this technique is you would be able to easily handle the previous/next button click events from the browser and present the proper data/page to the user.
I would prefer AngularJS. This will be a good technology and you can do pagination with one HTML. So i think this will be good framework for you as your using static content.
In AngularJS MVC concept is there please read the AngularJS Tutorial. So this framework will be worth for your new project. Happy coding

Using JavaScript objects and AJAX vs ASP MVC3 Model

Since I am fairly new to MVC, I am a little confused as to what is the proper/preferred way of using MVC's Models together with JavaScript objects and AJAX.
As an example, I have an application that displays a calendar with user's events, which are stored in the database. On top of that, these events can be manipulated by moving them around the calendar and then the new times are saved in the database.
When the user first makes a call to my Calendar action, I load the events from the database and then pass them to the view via the CalendarModel. This allows me to prepare these events visually but now I also need these events to be available as JavaScript objects because I will use AJAX calls to my UpdateEventTimes action to persist user's changes.
So my options today are to either "extract" the events' data from the CalendarModel and "hardcode" them as a string in JavaScript code or perform an AJAX call from JavaScript to retrieve these events again. Needless to say, I like neither approach so I am wondering if there is some MVC trickery that I am missing that's more elegant?
Unfortunately there isn't any. The only option to archive your scenario is to build js from Model like this:
<script>
var events = #(Model.Events.Aggregate(<aggregation function here to build js object>)) ;
</script>

Categories

Resources