Best approach for using AJAX loaders? - ajax

I've implemented a few poor solutions for bringing up an AJAX loader before dynamically updating a content DIV, but none seem to be "universal", and I find each time I do it I'm reworking it. If I have a DIV with content that updates depending on what a user clicks on the page, and I want to display the loader over this content DIV, what is the best approach? I've seen some developers have the loader always on the page, and they just display it block or none, and I've seen others append it to the DIV. What about when you also have multiple areas that can update? I'm thinking something repeatable that I can call with a function, maybe passing a few parameters.

Some JavaScript libraries allow listening to opening and closing requests. Check out Prototype's request Responder http://www.prototypejs.org/api/ajax/responders.
You would do something like this:
Ajax.Responders.register({
onCreate: function() {
$('loader').show();
Ajax.activeRequestCount++;
},
onComplete: function() {
Ajax.activeRequestCount--;
if (Ajax.activeRequestCount < 1) $('loader').hide();
}
});
As for visual representation of loading, you may want to identify the different parts of your page which may require separate loading graphics and subclass the Request object, each time indicating the type of request.
E.g.
Is it a field being saved? new FieldUpdateRequest(field)
Is it the page being loaded? new Request();
Is a container being updated? new PartialRequest(div);
Then capture each subclasses type and show or hide a different loader graphic.
There is unfortunately no quick solution, hal. You could build a generic script for appending loader graphics to containers, that should save you some repetition. If you do, mind posting it here :)?

You could use a JQuery progress bar or something similar in a different library.

Related

Ember JS best way to show a full screen loading screen button press

I'm new with Ember and I would like to show a full screen overlay when a user presses a "get stuff from the server" button.
What is the best way to achieve this?
Does Ember already provide something built-in? Or is it that the only way is to have a piece of HTML in one of my templates, to show/hide it when the promise where I make the AJAX call returns?
You have a few options available to you.
The first concerns a route change. Conventionally speaking, if the user is hitting a button that transitions to another route, a separate route can be created to handle this in-between loading experience.
To describe this briefly, if you have a route named foo, creating a sibling route named foo-loading with an associated template, will show a "foo-loading" page state while things are being fetched, and then dismiss it once things are good.
Alternatively, as you've hinted, if the call to action for a user intends an updated result on the same route, a loading service could be useful. In your application template, you could have a loading div that is hidden by default. Prior to initiating an AJAX request, you could turn the loading state on and reveal the loading div. Then, once the AJAX call is settled, the finally block could include a call to conceal the loading div.
This latter approach would involve a conditionally loaded block in the primary application template, a loading service handling show and hide, and a loading template.
You could use ember-modal-dialog to create a loading screen component that gets rendered when you're waiting for your ajax request.
For example:
// view.js
showLoadingScreen: true
// view.html
{{#if showLoadingScreen}}
{{loading-screen}}
{{/if}}
// loading-screen.html
{{#ember-modal-dialog}}
<div class="loader-full-screen-class"></div>
{{/modal-dialog}}
The advantage of the component/ember-modal-dialog is that this pattern is usually implemented as a modal, and this library is the standard in ember. The component then allows you to put it anywhere you need it to be.

Single page application with Rails 4 and AngularJS

Ok, this idea might seem quite a bit crazy and it kindo' is (at least for me at my level).
I have a fairly standarad rails app (some content pages, a blog, a news block, some authentication). And I want to make it into a single page app.
What I want to accomplish is:
All the pages are fetched through AJAX like when using turbolinks, except that the AJAX returns only the view part (the yield part in the layout) withought the layout itself, which stays the same (less data in the responces, quicker render and load time).
The pages are mostly just static html with AngularJS markup so not much to process.
All the actual data is loaded separately through JSON and populated in the view.
Also the url and the page title get changed accordingly.
I've been thinking about this concept for quite a while and I just can't seem to come up with a solution. At this point I've got to some ideas on how this actualy might be done along with some problems I can't pass. Any ideas or solutions are greatly appreciated. Or might be I've just gone crazy and 3 small requests to load a page are worse then I big that needs all the rendering done on server side.
So, here's my idea and known problems.
When user first visits the app, the view template with angular markup is rendered regularly and the second request comes from the Angular Resource.
Then on ngClick on any link that adress is sent to ngInclude of the content wrapper.
How do I bind that onClick on any link and how can I exclude certain links from that bind (e.g. links to external authentication services)?
How do I tell the server not to render the layout if the request is comming from Angular? I though about adding a parameter to the request, but there might be a better idea.
When ngInclude gets the requested template, it fires the ngInit functions of the controllers (usually a single one) in that template and gets the data from the server as JSON (along with the proper page title).
Angular populates the template with the received data, sets the browser url to the url of the link and sets the page title to what it just got.
How do I change the page title and the page url? The title can be changed using jQuery, but is there a way through Angular itself?
Again, I keep thinking about some kind of animation to make this change more fancy.
Profit!
So. What do you guys think?
OK, in case enyone ever finds this idea worth thinking about.
The key can be solved as follows.
Server-side decision of whether to render the view or not.
Use a param in the ngInclude and set the layout: false in the controller if that param is present.
Have not found an easier way.
Client-side binding all links except those that have a particular class no-ajax
Here's a directive that does it.
App.directive('allClicks', function($parse) {
return {
restrict: 'A',
transclude: true,
replace: true,
link: function(scope, element, attrs) {
var $a = element.find('a').not($('a.no-ajax')),
fn = $parse(attrs['allLinks']);
$a.on('click', function(event) {
event.preventDefault();
scope.$apply(function() {
var $this = angular.element(event.target);
fn(scope, {
$event: event,
$href: $this.attr('href'),
$link: $this
});
});
});
}
};
})
And then use it on some wrapper div or body tag like <body ng-controller="WrapperCtrl" all-links="ajaxLink($href)"> and then in your content div do <div id="content" ng-include="current_page_template">
In your angular controller set the current_page template to the document.URL and implement that ajaxLink function.
$scope.ajaxLink = function(path) {
$scope.current_page_template = path+"?nolayout=true";
}
And then when you get your JSON with your data from the server don't forget to use history.pushState to set the url line and document.title = to setr the title.

Load data on ajax for Row expander in ExtJs

I am using Sencha ExtJs grid 4.2 . I am using a Expander plugins for my grid and try to load data under expanded region from Ajax. Right now I am using this code to show data on expanding.
plugins: [{
ptype: 'rowexpander',
rowBodyTpl: new Ext.XTemplate(
'<br><img height="31" width="32" src="../upload/patient/thumb/{patient_image}">',
' <p><b>{fname}, {lname}</b></p>',
'<br> {accordian_view}'
)
}],
Here you can see that data is pre populated, but my requirement is to load data on expanding. I am trying hard to find the event or process to do it. But still no luck. If anyone have any idea please share.
Thanks in Advance
You might check out the expandbody event on the RowExpander plugin: http://docs.sencha.com/extjs/4.2.1/#!/api/Ext.grid.plugin.RowExpander-event-expandbody
This event passes not only the row's bound record, but also the expanded element, so you could:
Request data via Ext.Ajax.request({...})
Handle response
Add content to expanded row
One thing to keep in mind, however, is the async nature of this approach. That is, the row is going to expand immediately, regardless of how long the subsequent request takes to come back. So it would probably be a good idea to do something like this instead when handling the expandbody event:
Add "loading" text/icon/whatever into expanded row area
Make Ajax request
Handle response
Replace loading text/icon/whatever with the data returned from the Ajax request
It's likely someone has already done so, but you could also (and I would highly suggest it) wrap this process into a custom plugin of your own that extends the RowPlugin. That way you could use it elsewhere in your app for any grid. If you end up creating a custom plugin, please share it with the community!
EDIT: A quick Google revealed a number of custom plugins that do precisely this. For example: https://github.com/nickbretz/Ext.ux.AsyncRowExpander/blob/master/AsyncRowExpander.js

Refreshing Partial View in MVC 3

I have a partial view that I have included on my _Layout.cshtml. It simply has a javascript function that changes an image based on the state of my system. I don't need to reload any data, I don't need to go to the code of the controller for anything, I simply need to reload that partial view.
I tried many of the examples that I found here but couldn't get any of them to work. I felt as if they were too complex for what I was doing anyway. Any guidance would be appreciated.
Thanks,
Steve
If the partial is loaded into the layout directly then there's no straightforward way to refresh it, because it's basically a part of the complete rendered page.
Your best bet is to render the partial using $.load or whatever equivalent you have available by hitting a controller method and rendering the result into a container (like a div). You would have to do this within a script that is loaded with the layout itself, by observing document.ready or something like that. Once you have that in place then it's trivial to keep reloading or refreshing the contents by hitting the controller method as many times as you need. For example in jQuery:
$(document).ready(function () {
RefreshPartial();
window.setInterval(RefreshPartial, 10000);
});
function RefreshPartial() {
$('#container').load('/some/controller/endpoint', {parameters});
}
This will call the controller method, and set the inner contents of the element identified with #container. You can call RefreshPartial as many times as you want.
Partial views only exist on the server. The only way to "refresh" the partial is to go back to the server to get it again.
Obviously, you must be doing something in the partial that needs refreshing. Whatever that is, should be callable from javascript to do the refresh.

onLoad or similar for Ajax?

Good day,
I was wondering if there is a way to make Ajax move on to the next code segment only when all the elements included in the server-side code page are fully loaded. When the retrieved data is text-only there’s no problem, but sometimes there are photos included.
This is part of the code I have been using:
xajx.onreadystatechange = function(){
if(xajx.readyState==4){
document.all.div1.innerHTML = xajx.responseText;
document.all.div1.style.display = “”;
}
}
The thing is that when the response is retrieved (readyState set to 4) and div1 is displayed, the Photo has not been completely loaded yet, so actually the user can see the process of the picture slowly appearing, as he would in any other “normal” case. What I want to do is making div1 available for display only once all the components are fully loaded while meanwhile the system does its stuff in the background. Before Ajax I used hidden iframes like everybody, so I could enclose an onload event handler within the iframe tag (or in an external script), so div1 would appear only after the iframe has fully loaded, photos included.
Any idea?
You can use the 'onload' event on images themselves. You'll need to work out how to attach that event when you are downloading the code dynamically as in your case.

Resources