Rails API - helpers for AJAX - javascript

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.

Related

django rest framework API edit function

though I am new to django rest framework, all in all, i get how the posting and viewing works each using jquery ajax to post and angular js for rendering the API json data.
but i don't understand yet how the 'edit' and 'delete' function should be implemented here.
it means i have to load preexisting title and contents to the designated field forms and resave the post into that specific post id.
how can i do that?
and how can i check the permission when executing edit or delete function using either jquery or angular?
please consider the fact that my website is SPA (single page app) that shouldn't require any sort of page refresh.
so these concepts are fairly new to me, and i don't understand how i can manually check the permission using only the API
here is the live site : http://192.241.153.25:8000
You can use class based views for this. Using class based views you can have different end points for different functionalities, differentiating on Request types.
class AView(APIView):
def get(self, request, format=None):
pass
def put(self, request, format=None):
pass
for authentication and permissions do refer to http://www.django-rest-framework.org/api-guide/authentication/#tokenauthentication

Rendering html.erb templates in javascript

I'm running rails 4.0.4. I have a form I'm using a partial in to add a subset of fields. The user has the option to remove those fields and replace them with other fields once they're on the page. I'd like to be able to add those fields back in in the event that they want to undo their decision.
Render isn't available in javascript files (which seems odd for js.erb files). I've gotten as far as using the following to read the text of the file into a variable.
var master_quantity = "<%= data='';File.open("#{Rails.root}/app/views/shared/_a2a_master_quantity.html.erb","r").each_line{|x| data+=x};data %>";
Unfortunately escape_javascript doesn't appear to be available in the asests folder either, so I'm unable to use this string as it breaks the javascript.
Anyone have any suggestions on cleaning the string or alternate methods to get the partial into my javascript?
You could try,
controller = ActionController::Base.new
controller.send(:render_to_string, '/shared/a2a_master_quantity')
Whatever you pass to render_to_string above are params for that method.
You may or may not need that leading '/' for '/shared'.
If I understand your question, and the partial never changes, you won't need to get it from the server. Just hide it in CSS (such as with JQuery's $('#selector').hide() )
On the other hand, if you need Ruby to customize your partial each time the user restores it, you can send an AJAX request from the browser to your server to request a new version of the partial.
Add a line to a suitable controller action that renders your partial:
render :partial => 'a2a_master_quantity' and return if request.xhr?
Make a suitable XML HTTP Request in your JavaScript to get this partial (such as JQuery's $.ajax().)
Then use JavaScript to add it to the DOM in the appropriate place.

Best practice for rails-javascript interaction?

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)

i18n in javascript using .properties file

I'm developing a web application with JSF, so I use a Java Properties File (i.e. resources_es_CO.properties) to localize strings for the application and this is working OK.
Mi question is: how can I call localized strings in this kind of files from my javascript validations so alerts show those localized strings to user?
Thanks in advance.
What I do is to send the messages out as part of the page, dropped into hidden <span> tags with "id" values made from the property names.
Alternatively, you could write an Ajax-called action and fetch the properties dynamically.
To do an ajax callback, you'd have to implement a server-side action that would understand something like the property key. The server would just apply the localization (ie look up the property in the locale associated with the session) and then return the string. Alternatively, you could implement a service that'd return a whole set of properties, maybe on a per-form basis, or grouped according to some convention of property names (like, "return all properties that start with 'validation.addressForm'")
The simplest case would look something like this with jQuery:
$.get('/fetchProperty', { property: 'firstNameMissing' }, function(propValue) {
$('#errMsg').text(propValue);
}, "text/plain");
Other frameworks provide similar ajax tools, or you could do the XMLHttpRequest yourself.
you could go to server with an ajax call and send alert texts from server to client and show it. or you could put messages to your page when your jsp's being rendered. both is ok. if you can change language without refreshing the page you probably want to make ajax call. if you can not , putting messages in javascript variables will be easier

AJAX with Ruby on Rails?

This is probably a really dumb question with a simple answer but...
I am working on a project where I need to use AJAX to send/receive information. I am using Ruby on Rails (which I am pretty new to), but rather than using the helper methods or the built in functionality in the 'defaults' Javascript file, I need to do this manually in my own Javascript.
I believe that ultimately I will want to send a request with a JSON object, then have the controller return another JSON object containing the requested information.
The problem is that I cannot seem to find the syntax for sending something to a specific controller method, with parameters, directly from Javascript - everything I Google ends up being tutorials for using the Rails AJAX helper methods.
Depending on the version of Rails you're using, you can do the following:
Install the jrails plugin. This will replace all the Prototype javascript in your application with jQuery. This means you now have access to all the jQuery libraries, but it won't break your existing rails helper stuff (remote_form_for, etc).
Now you can use the jQuery AJAX to make any AJAX requests you want to make. A simple example would be something like below:
//Let's get a specific post by id
$.ajax({
type: "GET",
url: "/posts/123",
success: function(data){
//put the data in the DOM
}
});
Then just add the appropriate respond_to in your controller:
PostsController < ApplicationController
def show
#post = Post.find(params[:id)
respond_to do |w|
w.json { render :json => #post.to_json }
end
end
end
if using jQuery is an option for you, jQuery.ajax will solve your problem.
[and for those who likes to say jQuery is not solution for everything, i know that. i'm just giving him an option].

Categories

Resources