how to use ajax with json in ruby on rails?

Why should I use Angular.js?

  • I am a Ruby On Rails Developer and I use RoR for handling backend and jQuery for handling front-end request (AJAX). Why should I use Angular.js? How can I benefit from it? Potentially, there are many new javascript frameworks - Ember, Backbone - which one suits the best to Ruby On Rails?

  • Answer:

    My company uses Rails as backend for developing JSON Api. On the frontend we use AngularJS. I'm the core frontend developer and from my experience of both Backbone.js and AngularJS, I will suggest you to go with AngularJS. Some of the reasons are : Initially I started learning Backbone.js and soon realized that there are no controllers and to build a page we need to think from bottom-up rather than top-down approach of designing a page. Think of it like you want to develop a page and instead of laying out all the thing, you build small items like a list item and then collection of list item then a wrapper around it and combining each of them will yield a fully decorated page. Now think in terms of top-down approach where you know you have a full page where you can place small components, so you build outer wrapper first then collection template and then template for individual list items. You will be thinking, man that's the same thing! But I tell you, when you start developing you will feel that our mind is set for developing a product in top down manner and bottom-up approach is little different for our mind, it's little tough to think like bottom-up components. As a Rails developer, I'm much more comfortable with controllers and default way of routing. AngularJS works on same ideology with little different terms for models. However in Backbone.js, there is no controller and for this I have to also learn Marionette.js ( a plugin over Backbone.js ). Soon I realized, I have to structure my code more efficiently so I tried including Require.js in my company project. All of this hard work and very little results except that i'm avoiding page refresh for requests but work load became so much that I have to try out AngularJS. I looked at yeoman project ( http://yeoman.io/ ), installed it and developed a sample app in less than 6 hours. When I started using it in for my company project, it became very easy to do tasks that are repetitive in nature and with directives you can automate many components like forms, simple plugins for slider, dialog, dropdown, datepicker, autocomplete and much more ... You can do this in Backbone.js also, but it will require you to organize your code at a very good abstraction level and a lot of patience is required to write many lines of code. Workflow that I use for my project: Install yeoman and generator-angular from yeoman website ( http://yeoman.io ). I use Sublime text for developing. ( http://sublimetext.com ) For deploying, run grunt command and mount dist/ folder to nginx or apache server ( a system dev will know how to do that ) Use rails to develop JSON Api for your project. There are many guidelines for good api format, look google or facebook. Use RABL gem or JSON builder gem to make JSON templates. They will help you a lot and a must in my opinion. If you don't want to write code and project is simple, use rails-api gem. This gem will replace your scaffolding with JSON templating and no erb files will be generated. I prefer to use restangular instead of angular-resource. It depends on which is developer prefers. Start with angular-resource if restangular seems not obvious. There are other things also, but none of them will matter right now. Just dive right in, don't expect to write good code for first time. Build an app. Again build an app. Continue doing until it get fixed into your workflow. Do look for questions regarding tutorials on AngularJS.

Piyush Chauhan at Quora Visit the source

Was this solution helpful to you?

Other answers

If you're doing sites with heavy user interaction via forms, Angular is very good. The validation side is very impressive. Things like admin areas are where it shines, IMO. We're just looking at integrating it into a Rails workflow, and the way it's structured will seem familiar. It's the other way round from query; instead of locating elements and acting upon them, the HTML becomes essentially a description of how your view model functions. It's neat; there's some rough edges, but for something as data-driven as a Rails app, it's likely to be a good fit. There are a few caveats: it expects a SPA, so if you're doing (mock) multipage and paginating (for example), the controller will likely be destroyed and rebuilt if you don't do careful tweaking, which can be seriously costly. It's geared toward desktop apps, and you might be looking at performance hits on handhelds if you're not careful (Angular works for mobile, but maybe look at React if that's what you're targeting, it's lightweight and seriously quick). Make sure you do your research on integration with Rails as well, there's a few gotchas. Also, re $http in Angular, bone up on promises: you can do very neat things with them, and they're baked into the core.

Daniel Couper

if your interested in developing apps very quickly and testing them as well then angular.js is the way forward, its quite popular. i am really keen on using it in my personal website.

Akash Paul

I strongly prefer you to go for http://batmanjs.org/, It's Damn easy if you are good with RoR.

Peeyush Singh

Just two from AngularJS features that I find most impressive: - Building with the shortest possible code. This HTML code is fully functional App: <input ng-model="name">Name is {{name}} It instantly updates the "name" variable as the user types. I have yet to see another framework putting so much functionality in so terse code. - Based on standard JavaScript and HTML with minimal modifications. Any AngularJS component (e.g. Controller, Service) is a plain JavaScript function. It can be easily ported anywhere, with or without AngularJS, so there isn't really any "vendor lock-in". Similarly, any HTML template with AngularJS directives can be re-used anywhere (with directive being silently ignored but not breaking). In contrast, most other frameworks use proprietory JavaScript objects and non-native HTML syntax.

Dmitri Zaitsev

I have used AngularJS in a number of projects (with nodeJS and RoR in the backend), and have also tried Backbone, Ember, Derby and Meteor. Each of these has their pros and cons. For me, there are 3 places where Angular scores over other frameworks: 1. Modularity and code organisation: Angular excels here, with a clear separation of modules, templates, controllers, services, directives and filters. When combined with a module like Angular-UI-Router, you can very cleanly divide up your app into different states that each are small and self-contained. This modularity is what allows you to build large-scale apps with many developers individually owning a piece, and what also allows for easily testing applications. 2. Functionality first thinking: Using AngularJS well means you think about the functionality you want to build, and then you build it! In every other framework, you need to think a lot about the structure and mess with the DOM - "let me get this div, make this AJAX call, check if the user is logged in and then change this span in the div to say Sign-up" in other frameworks v/s "I need to handle the unauthenticated state of the user, by allowing them to sign-up or sign-in.". This is enabled mostly by the power of directives. This change in thinking allows you to have good conversations around design of the app up-front, before coding starts. 3. Tooling & Support: Tooling in Angular - whether for testing (Karma, Protractor, Jasmine), Build (grunt, gulp), Workflow (yeoman, bower) and other tasks is just fantastic. Added to that is the support in the form of modules (http://ngmodules.org), easy prototyping Backend-as-a-Service (FireBase, for example) and community support in the form of free and high quality tutorials and videos makes Angular a really good choice. To close this off, a few tangential thoughts on your question: Angular works great with a JSON API delivered from the server: If you care about performance and can influence the decision, think about why you have RoR on the backend instead of a MEAN (Mongo-Express-Angular-Node) stack, which delivers better performance, is great for API's and allows for a common language across client, server and database. Meteor is another fantastic framework that I use. However, I find that Angular / Node works better for mobile applications (where I can package Angular inside PhoneGap), whereas Meteor excels when I commit to it on client and server, and don't care much about mobile applications. While I've tried Ember, I found it to be more opinionated that Angular, and I just couldn't wrap my head around the "Ember way of doing things". Some people love it though, so you may want to check it out!

Arun Rajappa

http://geeksprogrammings.blogspot.com/2015/01/why-we-should-use-angularjs.htmlAngularJS Features Modules Directives Templates Scope Expressions DataBinding MVC (Model, View & Controller) Validations Filters Services Routing Dependency Injection Testing Modules AngularJS modules divides your web application into small, reusable and functional components which can be integrated with other web applications. Each module is identified by a unique name and can be dependent on other modules.DirectivesAngularJS directives are used to extend the HTML vocabulary i.e they decorate html elements with new behaviors and help to manipulate html elements attributes in interesting way.TemplatesAngularJS templates are just plain old HTML that contains Angular-specific elements and attributes. AngularJS used these templates to show information from the model and controller.ExpressionsAngular expressions are JavaScript-like code snippets that are usually placed in bindings such as {{ expression }}. AngularJS expressions doesn't support control flow statements(conditionals, loops, or exceptions). These supports filters to format data before displaying it.Data BindingAngularJS data-binding is the most useful feature which save you from writing a considerable amount of boilerplate code. Now, developers are not responsible for manually manipulating the DOM elements and attributes to reflect model changes. AngularJS provides two-way data-binding to handle the synchronization of data between model and view.ScopeScope is an object that refers to the application model. It acts as a context for evaluating expressions. Typically, it acts as a glue between controller and view. Scopes are hierarchical in nature and follow the DOM structure of your angularjs app.FilterFilters are used to format data before displaying it to the user. They can be used in view templates, controllers, services and directives. There are some built-in filters provided by angularjs like as Currency, Date, Number, OrderBy, Lowercase, Uppercase etc. You can also create your own filters.

Himanshu Bhalla

The complete Client Side Solution The data binding and the dependency injection reduces much of the code and make it more precise. All these things happen within the browser at par with any server side language. Everything you need to build a CRUD app in a cohesive set: data-binding, basic templating directives,form validation, routing, deep-linking, reusable components, dependency injection. Testability story: unit-testing, end-to-end testing, mocks, test harnesses. Registering Callbacks : Java script callbacks clutters your code whereas, Angular JS  vastly reduces the code size. It makes it easier to see what your application does. Manipulation of HTML DOM : In AJAX based application DOM manipulation is complex and error prone. Angular never have to manipulate the DOM programmatically, it can be done if it is needed. Arrange data to and from the UI : Angular assembles the data from the server to the HTML objects and allows the user to modify, validating, display validation errors and return the object back to server. In this process lot of boilerplate code is reduced in the code. Writing tons of initialization code just to get started : To initiate an AJAX app user has to write a lot of code. In Angular using services and dependency injection it can be started easily. Angular implements the most efficient MVC frame work, Angular inherently splits your  application to MVC Pattern. M - Model - The models are the objects that are from the rest API or any javascript objects. The API may provide json or XML  and can be parsed by javascript. V - View - The views are nothing but the HTML elements or the directives which are the  elements of DOM.The view can be dynamically changed based on the model. C - Controller - Generally the business logic will be the part of the controller. M-V-W - Model View Whatever, the View is changed as soon as the Model is changed without the DOM access. In angular it is called as MV-VM frameworks. Controller bridges between the Model and the View. AngularJS has a inbuilt view resolver which will render the HTML templates from the client side instead having a server API to render the templates to the browser. In this case the server need to handle only the data objects from the client. The power house of the angular js is its 2 way data binding, as soon as the view changes the model is automatically updated, from the client side we dont need to write any code for doing that as in jQuery or other frameworks MVC in AngularJS A simple calculator program using AngulsrJS, after seeing this code you can definitely feel how hassle free is AngularJS compared to other frameworks

஠ஷ்வின் குமார் [Aswin Kumar]

If at any point in your life you happen to be in charge of creating a complex client-side UI that has huge forms, strict constraints on data, a requirement for the user to be able to play with it until all the constraints are met before the data hits the DB  - for example a calendar-based booking system for assets - then you will quickly see how "boilerplate" jQuery-based code for input/validation/output eats away your time, while really complex and dangerous edge cases are still not handled.Angular, in turn, hides away at least the part of handling the import and providing the output (including the validation) - you state that right in your markup, and then the library does its magic of two-way data-binding for you. Since the markup is yours - you are not forced to some particular component library or approach, you can do anything. And since not a single line of JS is required to collect and validate input, you can hence focus the JS-literate part of your brain on managing a higher level of logic - the business logic behind handling the constraints.So, Angular should not be perceived as a replacement to jQuery (in fact, at some point Angular contained a little cut-down copy of jQuery, just in case). But rather Angular is a great approach to build a whole client-side application - in case you need to do that.

Eugene Rimmer

Why I Love Angular JS?It has been more than 6 years that I have been a web developer, from software apps to webs apps, I have done it all. And all this while, it was JavaScript that had taken over my world of development. But since the introduction of Angular JS, my perspective has changed. It is somewhere much better than JavaScript for web apps like CRUD, RESTful and yes of course Single Page Applications. Here is why i am so much in love with this technology framework.1. Two Way Data Binding There is a need to understand the most elaborate features of Angular JS and two way binding is one of the most awesome features of Angular JS. Also, there is a need to realize this advantage that Angular JS offers. Aweb developer can easily choose models to bind them into HTML elements. Also, when you change your models, then you can make changes later where the changes will be updated automatically. I am so fond of this technology framework because it reduces the amount of boilerplate code which is written to keep the model and view in sync.http://websiteontwikkelingspecialist.weebly.com/website-ontwikkeling/why-i-love-angular-js

Rasin Bekkevold

Just Added Q & A:

Find solution

For every problem there is a solution! Proved by Solucija.

  • Got an issue and looking for advice?

  • Ask Solucija to search every corner of the Web for help.

  • Get workable solutions and helpful tips in a moment.

Just ask Solucija about an issue you face and immediately get a list of ready solutions, answers and tips from other Internet users. We always provide the most suitable and complete answer to your question at the top, along with a few good alternatives below.