I am trying to locate an decent example of ajax json interaction with Rails. I have a Rails app that uses standard forms and wish to improve it with some ajax, but I have not found a good example to inform me.
I have a large investment portfolio model object, which requires multiple views to input all the data. I have a mechanism that allows page-to-page transition, using divs with a style of display:none or display:block around wrapping each 'pane'. I can selectively hide/show each pane as I move off-screen to the next pane. The user can navigate around, setting values, some of which need to be fetched from the server (such as look up a stock quote). When all is done, a commit sends it all back to the server, since it is one single form. So far, so good.
Now, I need to interact with the user when he is picking individual stocks, performing auto-complete on the ticker symbol during typing and then updating a table of stocks picked. This part has me stumped, since I don't understand how I can get interactive behavior while the input form is displayed. I am hoping to review some clean examples of ajax interacting with rails.
Oh, by the way, the app is a Facebook application, so I can't use prototype or any rjs templates, but must use FBJS.
I can't seem to find an example that shows ajax updating page sections dynamically.
Related
I always find it difficult to decide if I should render my HTML server-side or build it client-side.
Let's say I want to render a dynamic HTML dropdown with following requirements:
Shows records from a database table at page load
Must stay up-to-date (users can add/remove records from the database table using the website)
I can't decide between
Option 1
Render template with empty dropdown server-side
Populate dropdown client-side using ajax requests (JSON)
Update dropdown client-side using ajax requests (JSON)
Concern: Rendering empty elements before populating feels ugly to me
Option 2
Render populated dropdown server-side
Update dropdown client-side using ajax requests (JSON)
Concern: Why would you render server-side if you are still updating it client-side?
What solution is more commonly used in web development? Feel free to share different approaches.
This is a little opinion bases. There are schools for the server-side, and other schools for the client-side. The main reason for the later is utilizing the client machine (which are free for you) to free the server resources (which you pay for). This also makes your app more scalable.
The example that you gave is not detailed enough, and it is only one aspect. I usually use these general rules:
If there are dynamic parts of your page (e.g. dropdown, grid, popup form, etc), I use Ajax to avoid reloading the entire page.
If the HTML is very simple and/or requires further processing on the client-side, then just send JSON data from the server and build the HTML on the client-side. For example, I usually do not send error message from the server. Instead, I only send status codes (e.g. Successful, AccessDenied, Error, etc...) and I inspect those codes on the client and display the associated message. This is specially useful when different messages are displayed in different colors and styles or contain other HTML tags like links.
If it is a complex popup form or grid of data, then I send the HTML from the server. It is usually much easier and more flexible to build complex HTML on the server. Also when there are sensitive information used to build the HTML, it is usually much easier to build it on the server, otherwise you'll have to send some flags from the server or, better, you need to split your HTML building process to sections depending on permissions.
As for that very specific example in your question, I would go with the first approach (all client-side), mainly for the DRY concept (Don't Repeat Yourself). You don't want to have two pieces of code doing the exact same thing, and have to remember to update both every time you need change something.
Note though, that you don't have to send empty drop-down if you don't like it. Instead of only updating options like your example is suggesting, you can actually rebuild the entire dropdown every time. I don't particularly like this approach, especially if there are event listeners and other references attached to the dropdown, but I just wanted to say other ways to do it. This method can be useful on some scenarios, especially if the dropdown is part of a bigger section of the page that this whole section requires updating (rebuilding) every time, in which case I usually opt for sending the HTML from the server.
Your concerns are valid, each case has its advantages and disadvantages as you mentioned.
I would, personally, go with the first approach (all client-side); mainly for code maintainability. With this approach, you only have to update the HTML client-side instead of both client-side and server-side.
However, there is an argument to be made for saving that one request by server-side rendering the values. Even though it might be insignificant, there is a small performance optimization.
That depends. are you worrying about SEO?
Are you using any kind of client-side framework? I will assume that you don't, since JavaScript frameworks have there own way to do this, if you want you can read more about angular/react/vuejs which is the hottest JavaScript frameworks those days that will solve this issue.
Client-side frameworks render HTML on client-side only, and use only Ajax API to receive data from the server.
But if you don't want to use any client-side framework and do it in the "classic" way, both ways are appreciated. I tend to like the first way, this is almost how client-side frameworks do it and makes the most sense, yes you render empty table but you only render the "container" of your data, if you're bothered by how it looks visually (Showing empty list before data is fetched) you can just show loading bar or hide the table till the data is fetched.
I'm developing a web application where I need to allow to the users to select one or more values I'm usig Jquery 1.11 I was think to use a picklist and not an autocomplete mainly for the following reason: it's not sure that users know what they want to add; they may want to select what to add by seeing a list The problem I'm facing is that in my database I can have thousands of values and a picklist showing all these elements is not comfortable to use I was wondering is there is some kind of Javascript library who can offer to me a paged picklist Otherwise.... what is the best way to show this huge size of data? By taking care that users often don't know what they can add
My situation is the following one: in my project i'm using a WCM (Liferay) and I'm doing some extension to the redactional side of contents. I must provide to the user to fill a field by selecting 1 or N (with N>1) other web contents taken from WCM DB
Often redactors don't use tags and/or categories when they write web contents and some web contents can be written from some user groups and others web content can be written by others user groups; virtually each user group don't know/communicate with other user groups and this means that each user don't know what other user adds so I can't use some autocomplete solution
At the beginning I'll have few Web Contente, but after some time, by seeing the old web site, i can reach huge values (around 4000/5000 web contents and also more)
I already used select2 and I like it, but I have only two option for select2:
full load all data from DB but this means to kill performances and
show users all the data in a combobox
offer a search to users but users may not know what to search and so
they can do a lot of research without finding what they are looking
for
Now I was seeing also this JQuery plugin: https://github.com/yanickrochon/jquery.uix.multiselect but this plugin doesn't offer pagination options so I should always load all data from DB
I'm wondering if I can use some kind of Javascript utility to solve my issue or if I should take another kind of solution
If I should use another kind of solution.. what would be the best one?
I premise that this form will be only used on the redactional side and so I don't need a multi-device solution
https://github.com/lucknerjb/PaginationSelect
Couldn't find a verified project, however this one seems legit.
If you download zip and run index.html you will see this widget at work.
However personally I would rather implement some sort of server side user cart and download items range from a database dynamically instead of serving entire list of items to the user at once.
I am working on a simple "task list" project right now. I have built the I have so far using jQuery and Javascript to insert/delete/manipulate the "tasks". Because all of the elements are created/removed/changed in the DOM, every time the page is refreshed, all changes to the list are lost. I dont want to use a caching system because the aim is to create a system that can be accessed from multiple devices. I would like to set up some sort of PHP database that would allow me to create user profiles and have each users "tasks" separated.
I am familiar with Wordpress so I'm thinking I could use that and its user profile system to accomplish what I need. The issue I have is that I cant find any information as to how I could send the changes that were made to the DOM to a separate database entry associated with each user.
My strategy from there (unless anyone could suggest a better method of storing the data) would be to essentially make a copy of a set section of the raw HTML and post that to the database entry when the user hits a "save" button. Each time they log in, the most recent HTML would be loaded into the DOM as a starting point. They could then make the changes they desire, hit "save" before leaving the site and the cycle would repeat.
I am new to development side of things, so I could be making this way harder than it needs to be. Any links to topics similar to this, suggestions, advice would be appreciated. Im not asking for an in-depth how-to guide (though that would be nice) but to just be pointed in the right direction.
In Google Contacts, by default the form displays the values with some (read only) but when you click on a value, it converts the field into an so you can edit it, and when you press enter, it updates the value, remove the and redisplay the new value in the .
So it's really easy to add/modify information in one click.
I'm looking for a lib that do that, ideally that handle the whole process javascript+ajax+ror. Or just the javascript+ajax, or just javascript at least.
I think, like many of the other products, that they use GWT. Google Web Toolkit, its actually written in Java then cross compiled into Javascript. It allows them to write sourcecode for both the front and backend in Java and then creates optimised javascript for cross browsers.
The advantage of this is it is all widget based, and its super easy to switch components in and out without having to manually interact with the DOM.
However, if you do not wish to go down this route you can do it very simply in javascript using ajax calls. On a blur event you make an ajax call to your server which saves the field. On success it switches back to a Label. When you click on the label/text it switches for a textedit and uses the same contents as the label. No real need to use a plugin for this kind of thing as its actually pretty basic, it just looks good :).
It is said that Backbone handles all the higher level abstractions, while jQuery or similar libraries work with the DOM, normalize events and so on..
Could someone please help me understand this statement with any simple practical example.
Also one important feature of MVC framework like Backbone, Knockout is that it keeps the model (data) and the view in sync. But this seems to be specific at a page-level and not across the entire application. So can we have the model/data and the view synced across multiple pages..(kind of global)
Your opening sentence was actually a very good statement of the differences between Backbone.js and jQuery, so let's unpack it a bit.
For one thing, the two libraries are not at all in competition--they are complimentary.
As an example, here are some things I would do with jQuery:
Animated slideshows
Form control enhancements, like an iOS-style number "spinner"
Toggling visibility of elements based on a class name
And some things that I might do in Backbone.js:
Create a photo album, where the user clicks on a thumbnail and can view a larger version of the photo, along with some data like the camera that was used, the location and the photographer's name
Build a master/details type of page that presents a grid of data and allows the user to click on individual elements and update them in a form.
jQuery excels at the micro level--selecting page elements, smoothing out the differences in how browsers handle events.
Backbone.js is more big-picture. It helps you manage data and application logic. In the photo album example above, Backbone provides several useful structures: you'd have something to contain all of the data related to photos (a model), a list of all the photos in the album (a collection), and somewhere to put logic that determines what happens when a user clicks on a thumbnail (the view). Those are the main pieces in a Backbone control or application.
Backbone.js benefits from jQuery, though, or something like it, to help render the results of your application's data and logic into the DOM. It's common, for example, to use jQuery to select the element on the page that will serve as the container for your Backbone app. It's also common to use jQuery's $(function () {}); to fire up the pieces of your Backbone control. You'd probably display form field validation error messages with jQuery as well.
You can certainly build big, complex user interfaces in jQuery. We have a few in the app I maintain at work. But they are difficult to work with because jQuery isn't designed to provide structure to an application. In particular, jQuery's API, which is based around selecting groups of items and then passing callback functions that manipulate those items, isn't a good pattern to use in a large, complex control or app. You end up with a lot of nested functions and it's very hard to see what's going on.
I'm currently reworking one of those controls in Backbone.js. As a final example, here's a quick summary of how my thought process differs when working on the same control in both different libraries.
In jQuery, I'm worried about:
Am I using the right selector to grab the group of li elements I want?
Do I need to repopulate that list of values when this Ajax call completes?
How can I put these array values back into the input elements on the page?
In Backbone, I'm more focused on:
What is the correct logic to validate this set of properties on my model item?
When the user clicks the Add button, should I add a new item to the collection immediately, or should I wait until they've filled in all the data and it's "valid"?
How should an item in my collection respond when the item immediately before or after it is deleted?
jQuery handles the nitty-gritty details, and Backbone is more high-level.
In closing, notice I've been using the words "control" and "app" when discussing Backbone.js examples. It's not true that Backbone.js is just for single page apps. It is true, though, that Backbone.js is good for building complex applications that manipulate data and handle a lot of logic. It would be silly to use it for small-scale UI elements--the extra structure it imposes isn't needed.
Update: On the issue of multiple pages, yes, Backbone does provide a powerful mechanism for persisting your data. Each model has a save method that will execute an AJAX call to store the changes on the server. So as long as you save your data as you go, you can have a multi-page app. It's a very flexible model, and it's how we'll probably end up using Backbone at work. While I would love to build a single-page app, we have 10 years of work in our existing multi-page application. We're looking to rebuild some of our more intense UI components in Backbone, then sync the changes to the server before the user moves to a different page.
Backbone / Knockout is typically used for single page applications. So while jQuery is a toolbox that can be used with any webpage, Backbone is meant for a specific type of application and helps you organize your code for it. At least in my experience one of the biggest challenges in building a single page app is keeping the code clean and modular, and backbone helps a great deal with this.
The characteristics of a typical backbone app are:
Essentially static html page, with nothing generated on the server
Server acts as a json REST api, which provides the content for the app
The dom elements to display the data are created with javascript in backbone views, using jQuery and various templating libraries to help
Communication with the server as well as between different parts of the app is done through the backbone models
Regarding your question about keeping the data synced across multiple pages, my instinctive answer is that you don't need multiple pages: the user may perceive that the page is changing, the address in the url bar changes thanks to pushState functionality, but technically the entire app is one page.
The biggest advantages of this kind of approach are a smooth user experience (no reloading pages), good caching support as everything except the json data is static content, for mobile targets the possibility to turn the web app into a mobile app with phoneGap (because everything except json is static).
I have never heard of people using backbone.js across multiple pages. It's almost always some kind of single page app.
The single page may have many different models, views, and states and can result in a full blown, powerful app.
If you already have server-side template/view rendering in java then backbone.js is NOT for you. To get the most out of backbone.js you must move or duplicate some of that code in the front end javascript.
If you don't want to do a single page app (this just means an app without page refreshes or changes, but the url can still change and can look like multi-pages to the user) then you can keep all of your MVC on the server and you have no need for backbone.
Edit:
What backbone does is move some of the MVC stuff normally handled on the server and move them to the client. For many people this means forgetting about the server and just writing your app as a single page javascript app. The server becomes just a source of JSON/REST data. If you're not prepared to do that, then backbone.js is not that useful.
Backbone is a MV* framework while jQuery is a DOM toolkit.
The main features of an MV* application are routing, data binding, templates/views, models, and data access.
Backbone could dependant on jQuery partially.
jQuery is a solid API for querying the DOM with extensive browser support and a vibrant community. It comes with event handling, deferred objects, and animations.
Simple event binding using jQuery
// When any <p> tag is clicked, we expect to see '<p> was clicked' in the console.
$( "p" ).on( "click", function() {
console.log( "<p> was clicked" );
});