Best techniques to ajaxify Rails app? - ruby-on-rails

I'm currently ajaxifying my Rails app as follows.
JS
application.js
$("a").live("click", function() {
$.getScript(this.href);
//do something
return false;
});
Views
index.js.erb
$("#core").html("<%= escape_javascript(render 'index') %>");
index.html.erb
<%= render 'index' %>
_index.html.erb
#my partial
So when a user clicks a link, it will be intercepted and the corresponding js file will be executed, which renders a partial in a div. This means that, for each action, I will need 3 views, say index.js.erb, _index.html.erb, and index.html.erb.
This is painstaking to set up, and the index.html.erb file is somewhat useless, it just renders the partial (perhaps there's a way to render a full view from another view directly, hence eliminating the need for a partial?).
Is this the best way to do things? How do you usually imbricate Ajax with Rails?
Thanks.

Javascript MVC seems like it works well with MVC style backends. It standardizes ajax calls, controllers and views in a similar way that you are showing above:
http://javascriptmvc.com/

Related

render (partial) and scope between elements

I have a checkout popup I would like to share between different pages (event, video meeting ...), so I thunk creating a shaded element /views/shared/_checkout.html.erb, and insert <%= render "shared/checkout" %> in my pages.
Uncaught ReferenceError: popup_payment is not defined
All the html and javascript is this shared page.
I just can't understand why from my pages (event, video ...) I can not call the javascript from this shared component.
the html and the javascript is present when I check the source. I was excepting that render / render partial was acting some code injection, am I wrong ?
How could I preserve the DRY - Don't repeat Yourself - in ERB ?
And have the elements / javascript communicate betweek page and included javascript ?
Here is some pseudo code example :
pageA.html.erb
<%= link_to image_tag('pinandchip.png', size: '18x18'), '#', onclick: 'popup_payment();', class: "btn flat" %>
...
view/shared/_popup.html.erb
<script>
function popup_payment() {
}
</script>
You could try adding the class payment-popup-button to your button and create a new file in app/assets/javascripts/shared called popup.js.
In that file you can do something like:
$(document).ready(function(){
$('payment-popup-button').click(function(e){
e.preventDefault();
$('#popup_payment_div').show();
});
});
This assumes that you're using jQuery, and that you've already rendered the popup code somewhere on the page, but it's hidden.
If you need to render a fresh form every time or populate the form with dynamic data you'll probably have to create controller actions that respond_to and render js.erb to get you the right markup.
It's hard to say exactly without seeing more code.
Are you ensure that your javascript function is loaded in all pages?
On this question answer how to have global javascript functions on rails projects.
i found a solution with this gem :
https://github.com/komposable/komponent
it fulfill my needs : create external components

How to avoid embedding javascript in views/show

I have a Rails app that uses javascript (Backbone) to show user specific data on each users profile page /views/users/show.html.erb. I do this by passing <%= #user.id %> as a data parameter to Backbone's fetch function, however, the only way I know how to get the <%= #user.id %> into Backbone's fetch function is by embedding the javascript in each views/users/show.html.erb page, which therefore allows Backbone to load different user specific info for each views/users/show.html.erb page. Although this works, it seems like the wrong way to do it, as I have read that I should not embed javascript like this. Furthermore, I am going to have to do it a lot, because I wish to display a lot of different kinds of data, more than you see below. So the show.html.erb page will be filled with javascript to make the app work the way I wish.
Question: how might I get #user.id into Backbone's fetch function for each user's show page without embedding javascript in the way that I've done. In the comments, someone suggest I use app/assets/javascripts/user.js, but I don't know how to get <%= #user.id %> into that file. #user.id is readily available in show.html.erb
<script type='text/javascript'>
$(document).ready(function() {
app.collections.awardCollection.fetch({ data: $.param({ user_id: <%= #user.id %> }) }).complete(function(){
app.views.awardCollection = new app.Views.awardCollection({ collection : app.collections.awardCollection});
app.views.awardCollection.render()
});
});
</script>
In order to understand how the views works, is that you can add as many extensions to a view as you want, and they will be parsed by the right library.
If you create a view like
my_view.haml.erb
It will be first parsed with ruby (erb), and then with haml, and will end in a html page.
You can create many views for js, usually you want to archive that when you do ajax, so you can end having a js view like:
my_view.js.erb
First ruby will be parsed (all the <% %> tags), that will end as plain text, and then the server will serve the .js file. But that's usually a common task for ajax.
If you have to render a html page where you want to put some js and you need some ruby code on it, what I usually do is to put the data in the html content with a hidden div.
You can put in any view (even on your layout if you want it to be globally available), something like:
<div id="user_id" style="display: none;"><%= #user.id %></div>
And then on a js (or coffeescript or whatever) you can just check the content of that div:
<script type="text/javascript">
var user_id = $("#user_id").html();
</div>
that's really useful when you want to debug or create tests for your js files, since its plain js and won't throw syntax errors.
I see the comment of Luís Ramalho and Gon is a good option, but I recommend use the following approaches:
If the from the variable is not going to change, print it with <%= %> under .js.erb files located in app/assets/javascripts (note that it will be cached until you restart your app)
If you need server variables the best way is to use Ajax
You can define functions on .js files on app/assets/javascripts and call those functions from the views
If you really don't want any Javascript code in the view, you can create the functions on a .js on app/assets/javascripts (corresponding to the view, for order), and use events and/or store the variables in hidden fields (or even use the data attribute from HTML5)

how can i render a template as well as a JS file BOTH in a controller action

i have a scenario where in edit action ,i need to render the edit.html.erb as well as trigger the edit.js.erb file as well.right now i have
def edit
#page_id = params[:id]
respond_to do |format|
format.html
format.js
end
end
but only the view is renderring ,but my edit.js.erb is still not triggered.
With both ansers you can get it working, but you do not follow conventions. The edit.js is meant for Ajax-calls.
What you seem to be doing, is using partials to build up your page. Then you really should follow naming conventions (starting the filename with _) to be clear for other programmers.
Second, you always need to make sure your site can work without javascript, so your Edit page never should require any Javascript to work. The javascript is complementary to improve user experience (like using ajax to make edits without a page-refresh).
Summing up:
- move the 'required' javascript code to your edit.html.erb.
- only use the edit.js.coffee to handle the updates to the existing webpage if Ajax is activated, use as much of the js from the edit.html.erb.
- Put the rest of the shared code into partials, like _niceedit.js.coffee and render it using 'render :partial=>'...
Follow conventions, it will help you later on and when using test services etc.
respond with js and write code below:
edit.js.erb
$('body').html('<%=j render "edit" %>');
Your impression of what it does is wrong.
If you want javascript to run, then your edit.html.erb file needs to contain:
<%= javascript_include_tag "jsfilename" %>
and store your javascript in public/javascripts/jsfilename or similar location (public/assets/javascripts/
The respond to format.html, format.js is for requesting the view in that format.
Eg. If I browse to edit.html, it shows the html.erb view, if I browse to edit.js, it shows the js.erb view. The functionality is so that you can request the same content in different file formats, rather than to add javascript functionality to your webpage.

Displaying flash message in portion of page that is otherwise not updated

I'm looking to display my flash messages in a portion of the page that is otherwise not always in a partial that gets updated.
In other words, I may submit a form that updates a partial via ajax. But I want to display the flash message in a portion of the page that is outside of that partial.
I could have some javascript in every single necessary js.erb file to update the flash partial, but that seems crazy. Is there a more simple way of going about this?
I don't have to necessarily use flash messages either if something custom would work better.
Thanks!
You can do it the low-tech way by using a :remote call on your form that, when executed, will inject some HTML back into your page from a partial of your choosing.
It's pretty easy to do in a .rjs view:
page['flash'].html(render(:partial => 'flash'))
You can also do it in a .js.erb view using jQuery:
$('#flash').html("<%= escape_javascript(render(:partial => 'flash')) %>");
I tend to think the .js.erb method is a lot more ugly, but we all have our preferences.

RoR- How to use div onclick to render results in a separate area of the page?

I am learning Ruby on Rails, and I am very confused on how the controller-model-view relationship works for my application.
What I have now is a table full of comments (posts) users have made. What I want to do is let users click on a comment to see more information in a separate panel (ie, other database fields that weren't initially shown, for example the user_id of the person who posted the comment).
In my _post.html.erb, I have something like:
<div class="post" id="<%= post.post_id %>" onclick = ?? >
<p>post.text</p></div>
What should go in onclick? I need a way for the onclick to call a helper/controller method which can load more information, and then put that in another div on a page (I've tried variations of using the controller and helper to call javascript which inserts html into the site, but that seems messier than it should be). From what I understand, I should create some kind of partial _postdetails.html.erb file that handles the actual displaying of the html, but I have no idea how to specific where that partial would go in the page.
Any help would be appreciated, thanks!
You can achieve what you want either by using Rails helpers or by writing the AJAX calls yourself.
Personally I manually write all my AJAX calls using jQuery.
You can also use Prototype which ships with Rails.
That being said you can do.
In your JS file :
$("div.some-class").click(function()
{
$.ajax(
{
url:"url/to/controller/action",
type:<GET>/<POST>,
data://If you wish to sent any payload
});
});
In your controller :
def some_action
#some computation
render :update do |page|
page["id_of_div_to_be_refreshed"].replace_html :partial => "some_partial"
end
end

Resources