Best practice for rails-javascript interaction? - javascript

I have a page which shows a Google map. I'd like to use Javascript to fetch several points from my database and place them as markers on the map. So the flow is:
Javascript calls a Rails action with parameters.
Rails queries the database.
Rails returns the response.
Javascript updates the page (Rails can't do this since it must be aware of the JS map object).
What is the current best practice for implementing such a scenario? I know I can use a Prototype Ajax.Request to call the Rails action but how should I call the Javascript function which updates the page when the Rails action returns its results? Should I update some hidden HTML and have an event listener listen on it? Or is there a better way?

You have a couple options.
1) Your ajax request can be of type 'script' which will allow you to write an action_name.js file that your rails app renders. This has access to all of your page items (it's not likely to have access to your map object however unless that's public)
2) My preferences is to have your javascript query for json data (type 'json') which then allows you to use that data as you please in your JS. I don't use prototype but the general flow would be.
initialize your map
query for some json data using ajax (ie. locations with lat/long)
rails reponds_to do |f| f.json { render :json => some_hash} end
in your ajax callback (back in javascript), iterate over json data and add points to your map appropriately. (or do whatever you like)

Related

Does ajax call slows down the frontend?

i have the below scenario:
There is an arraylist of Java Pojo which stores data from db. The pojo has 3 fields and after fetching the data from db, the size of arralist is 250. I am storing that data in application scope. Its a spring mvc application.
I have created an end point in a controller class which filters the arralist using collection streams and returns the list of string as json.
I have implemented jquery autocomplete at frontend jsp and javascript, and i am fetching the source from this end point through ajax call.
My question is, whether ajax call approach is good or should i filter the data at the javascript code only.
After implementing ajax, the xhr call is taking on an average 300ms in local.
Note: IE11 support is also needed.

Rails API - helpers for AJAX

I have a normal rails app website, but on some pages I need to use AJAX.
I already have some working AJAX Javascript code using jQuery, but so far I haven't used any rails helper to do that, writing strings corresponding to paths manually.
But is there a more convenient way to do it in javascript ? Suppose I have a javascript function which takes an ID as argument, and must call an AJAX action. So far I've been doing it this way
var url = "/tags/tagID"
function getTag(tag_id){
$.get(url.replace("tagID", tag_id) +'.json')
.fail(function(data){
alert('Oops error !');
})
.success(function( data ) {blabla ] )
}
Is it possible to rename the .js to .js.erb and use path helpers ? So I could get rid of this url variable and write
routes.rb
resources :tags
tags.js.erb
$.get(tag_path("tagID").replace("tagID", tag_id)....
Or is there a more convenient way to do this ? I only need very little AJAX, so I don't want to use a frontend framework (Angular, etc.), just jQuery
EDIT My scenario
A user searches for a given tag thanks to an autocomplete searchbar. This searchbar will return the ID somehow.
The user can select several tags this way, and their IDs will be stored in an array. Now, upon clicking a button, I want to send a query to a non-RESTful (with the ID array as parameter) controller action via AJAX. For now I will focus on sending one item at a time (so just one ID string), for it is easier/more reactive.
This action is actually going to look in my models for projects and ingeneers that possess this tag, and return a JSON with formatted results.
Yes, you can use *.js.erb to use Rails helpers. Rails provides some handy helpers to work with Ajax. Normally with rails you can use them by using the the tag remote: true.
In your case something like
<%= link_to 'Tags', tags_path(<tag.id>), remote: true %> (roughly),
Read more about using Rails helpers with Ajax here, and this explains it nicely.
Update
Rails is using CSRF token to validate requests (except GET), so if you are going to use pure HTML/JavaScript, you want to add the token to your request. Have a look at this post on the same.
I agree there is no out-of-the-box way of doing that, but there are few workarounds.

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>

Acessing Gorm object in JS

i developed a web application using grails/gorm about traffic reports. Basically, its possible to find for traffic reports like (in road xx there was an accident yyy and the traffic is very slow.)
now i need to integrate the map in the application. My map is in javascript, how can i access gorm objects in js (if it is possible)?
standard groovy i use:
<%
def road1 = packagename.Road.list()
out << road1.name
%>
Can i have the same kind of access in JS ?
typically for this type of thing you make some sort of request to the server, which returns the data to the browser via JSON or XML. If your map is coming from some javascript library, you can use Ajax to query your server for the data. Which JS library are you using? Whatever it is, it probably has a mechanism to make an ajax request -- you would pass the params on the ajax request that the server needs to get the appropriate data, and when the request returns a callback that define will do something with the data.
As a note, its not a bad idea to set up your application code as follows.
You have your domain object, 'Road'
Generate a RoadService, with a method listAllRoads
Generate a RoadController, with an action listAllRoads
The controller calls the service, the service uses the Domain objects to retrieve the list. In your action, you can take the list and render in whatever form you need (json, xml, or as a gsp).
Grails is all about conventions; the above is how you conform to those conventions.

How can I send Javascript events back to Rails to process?

If I have user interactions in my Javascript layer, can I have Javascript actions trigger Rails controller actions and pass data from Javascript to those Rails methods?
Yes. You make asynchronous calls back to your Rails application using XMLHttpRequest, typically through Prototype or some other Javascript library. You pass data back to the server using query parameters, much like any other request, and your application returns HTML fragments or Javascript code that is used by the browser to update the relevant parts of the page.
The PrototypeHelper class is useful for generating the right stuff in the server. Ajax.Request is what you'll use on the client.
I believe you can make AJAX requests back to your controllers. Rails by default includes prototype so you can use its AJAX functionality ( http://www.prototypejs.org/api/ajax/request )

Categories

Resources