Rails ajax forms + flash messages - ruby-on-rails

Are there any good tutorials or gems that handle Rails Flash messages via Ajax?
In my .js.erb files, I've used something like the following:
<% if #event.errors.any? %>
<% #event.errors.keys.each do |key| %>
$( "#event_<%= j key.to_s %>" ).addClass("errorField");
<% end %>
$("#flashMSG").css("display", "block");
if(!$(".flashError").length){
$("<div class='flashError'>").html("Sorry, please fill in required fields.").appendTo(".noticeContainer");
}
<% else %>
$(document).bind("ajax:success", function(e, data, status, xhr) {
$("#flashMSG").slideUp(400).delay(400).slideDown();
if(!$(".flashSuccess").length){
$("<div class='flashSuccess'>").html("Event Updated.").appendTo(".noticeContainer");
}
});
<% end %>
Just wondering if there's a better way to do this or automate it similar to how Rails just handles it with a standard form submission.

How do you handle Rail's flash with Ajax requests?
and the gist:
https://gist.github.com/linjunpop/3410235

Related

How to Hide Foundation flash message?

I'm really confused as to how to hide a flash message in my rails app. I've read the documentation but I'm not sure how to do this correctly. I was hoping someone could point me in the right direction.
For my app, I have a flash message/alert for submitting videos/comments/sign_in,sign_up etc. etc. Below is the flash code in my application.html.erb file:
<% flash.each do |name, msg| %>
<% if msg.is_a?(String) %>
<div data-alert class="alert-box <%= name.to_s == 'notice' ? 'success' : 'alert'
n%>">
<%= content_tag :div, msg %>
</div>
<% end %>
<% end %>
The part that I get confused is the jquery part. On Foundation, the docs say that to customize it you need these three files:
<script src="js/vendor/jquery.js"></script>
<script src="js/foundation/foundation.js"></script>
<script src="js/foundation/foundation.alert.js"></script>
I thought these files were already in foundation. Do I need to create them under my app/assets/javascripts/ directory? Also, why would I need to add these at the bottom of my application file? I thought this tag
<%= javascript_include_tag "application" %> does it for me? It should because of the * require tree right?
I'm just confused about what goes where and what needs to go in what? For example, to hide the flash messages, where would I put this?
$(document).ready(function(){
$('.alert-box alert').fadeOut(1000);
$('.alert-box success').fadeOut(1000);
});
Does this go in the foundation.alert.js file,the foundation.js file, or the vendor/jquery.js file or somewhere completely different. Some help would be nice.So confused.......
I needed similar functionality once in which I had to fade out the flash message only on one specific page.
I created a separate JS file and required it in application.js.
I think to apply it to all the flash messages you need to put it in foundation.alert.js
Try this
setTimeout(function() { $(".alert-box a.close").trigger("click.fndtn.alert"); }, 1000);

Changing data stored in a div using ajax and ruby on rails

Does anyone know a good guide or example for me to follow on how to change data on the screen using ajax?
I have a div that stores the last #event_status and every 5 minutes I want to go get the last event status created and display it in the div using ajax.
<div id="last_status">
Last Status:
<% if #event_status.present? %>
<span id="last_status_content">[<%= #event_status.user.initials %> # <%= #event_status.created_at.strftime("%I:%M%p") %>]<br />
Audio: <%= #event_status.audio ? 'Good' : 'None' %> |
Video: <%= #event_status.video ? 'Good' : 'None' %> |
<% if #event_status.notes.present? %>
Notes: <%= #event_status.notes %>
<% else %>
Notes: No Notes
<% end %>
</span>
<% else %>
<span id="last_status_content">None</span>
<% end %>
</div>
You can use javascript to periodically call an action and place the contents into a div. First extract the content of your last_status div to a partial, then return said partial from a controller action.
Javascript in your page:
$(document).ready(
function() {
setInterval(function() {
$('.last_status').load('/controller_name/action_name');
}, 36000);
}
);
Your controller action needs to then initialize all variables used by the partial, then render the partial.
def my_action
#event_status = get_latest_event
render :partial => 'my_partial'
end

Render template having Jquery datatables in .js.erb file

I am currently working on a project where I am implementing several reports. The report filters are remotely submitted to my action and the return results are displayed in Datatable with searching,sorting and pagination.
I have a drg.js.erb file which is having code like this :
var html = "<%= escape_javascript(render(partial: 'drg_datatable',formats: [:html],locals: {result: #result})) %>";
$("#datatable-result").append(html);
The partial _drg_datatable.html.erb is having datatable implemented like this. Below is my _drg_datatable.html.erb file :
<% if result %>
<table id="results" class="table table-striped table-bordered display">
<% case params[:view] %>
<% when "ahfs" %>
<%= datatable_ahfs_result(result) %>
<% when "drg_code" %>
<%= datatable_drg_result(result) %>
<% when "inpharmics_id" %>
<%= datatable_inpharmics_id_result(result) %>
<% when "provider" %>
<%= datatable_provider_result(result) %>
<% else %>
<% end %>
</table>
<% end %>
The problem I am facing is that when I render the partial _drg_datatable.html.erb using .js.erb file it creates the table but escapes the javascript to add sorting,pagination and other cool features we get in Jquery Datatables. Can someone point me how should I go about doing this ? I have tried to render the partial is .js.erb without writing escape_javascript but then the partial does not get rendered at all.
You must explicitly call the datatable js function in your drg.js.erb in order to "datatablize" your table. Ex:
var html = "<%= escape_javascript(render(partial: 'drg_datatable',formats: [:html],locals: {result: #result})) %>";
$("#datatable-result").append(html);
$('#results').dataTable();
I suppose you have something like:
$(document).ready(function(){
$('a selector of yours').dataTable();
});
somewhere in your application's javascripts. This runs once, after document load and applies to elements existent to your dom. Since now you are adding a new table you have to "re assign" the datatable behavior...
#grotori: Your solution gave me a hint of fixing it. I renamed my datatable id with a name which was not used in the application anywhere. I removed the initial implementation of the datatable in the partial and modified the code to render the partial first and than apply datatable to it. Here is what I did :
var html = "<%= escape_javascript(render(partial: 'drg_datatable',formats: [:html],locals: {result: #result})) %>";
$("#datatable-result").html(html);
jQuery(function() {
$("#drg-results").dataTable({
"sDom": "<'row-fluid'<'span4'l><'span7 pull-right'f>r>t<'row-fluid'<'span4'i><'span7 pull-right'p>>",
"sPaginationType": "bootstrap",
"sScrollX": "100%",
"bDestroy": true,
"bProcessing": true,
"bScrollCollapse": true
});
});
Hope this helps other trying to achieve the same thing.

How can I make JQuery as include file?

Now, I have this JQuery in my application.html.erb
But I see this in every html of my web site. So I want to put this in refresh_post.js, which is created in /assets/javascripts
But as you know, application.html.erb calls all JavaScript file in the directory. Because I use many and putting this
<%= javascript_include_tag "application" %>
How can I call this JQuery only when user is logged in. and Where should I make refresh_post.js at so that it won't be loaded unless user is logged in?
The purpose of doing this is for SEO. I don't want to put JavaScript in HTML.
views/application.html.erb
<% if current_user %>
<%= javascript_tag do %>
jQuery(document).ready(function () {
refreshPartialPost();
setInterval(refreshPartialPost, 1000)
});
function refreshPartialPost() {
$.ajax({
url: "/posts/refresh_partial",
type: "GET",
dataType: "script",
});
}
<% end %>
<% end %>
How about this for your application layout:
<%= javascript_include_tag 'application' %>
<% if current_user %>
<%= javascript_include_tag 'refresh_post' %>
<% end %>
Have a look at this, Even though this is for CSS same can be applied for js
HTH

Rails 3 UJS driver events

According to Simone Carletti blog post, Rails 3 ajax helpers have changed a lot. We are supposed to write more javascript with rails 3 than we used to with rails 2.
I tried to figure out how to show up an ajax loading gif -while an ajax query is running- in the "rails 3 way". I came up with this kind of code, which uses javascript events sent by the Rails 3 UJS driver. This example uses prototype:
<div id="wait" style="display:none">
<img src="/images/ajax-loader.gif"> Please wait...
</div>
<div>
<%= link_to 'Get', 'finished', :id => "mylink", :remote => true %>
</div>
<%= javascript_tag do %>
Event.observe('mylink', 'ajax:before', function(event) {
$('wait').show();
});
Event.observe('mylink', 'ajax:complete', function(event) {
$('wait').hide();
});
<% end %>
This works well, but I wish it was possible to write these ajax events "triggers" with the help of the prototype and scriptaculous helpers, just like when we use link_to_function for example:
<%=
link_to_function("toggle visibility") do |page|
page.toggle "wait"
end
%>
Is there a way to do that, or are we supposed to write ajax events "triggers" in javascript directly, either prototype or jquery?
Best regards,
Philippe Lang
The idea of UJS is to move the javascript code out of the views into separate js files. The way you're doing it is defeating that goal. Instead, I believe you should have a js file with a "dom:loaded" or similar handler that sets up handlers for rails callbacks and other events.
Something like (using prototype):
(function () {
$(document).on('dom:loaded', function (event) {
$$('a[data-remote=true]').each(function (link) {
link.on('ajax:complete', function (request) {
// do something
});
});
});
}());
This way all javascripts are separated from the view, which is the idea of unobtrusive javascript.
After looking at rails source code, I came up with this solution:
def javascript_event_tag(name, event, &block)
content = "Event.observe('#{name}', '#{event}', function() {"
content = content + update_page(&block)
content = content + "});"
content_tag(:script, javascript_cdata_section(content))
end
This makes it easier to react to UJS events:
<div id="wait" style="display:none">
<img src="/images/ajax-loader.gif"> Please wait...
</div>
<%= link_to 'ajax call', 'code_on_controller', :id => "mylink", :remote => true %>
<%=
javascript_event_tag('mylink', 'ajax:before') do |page|
page.show 'wait'
end
%>
<%=
javascript_event_tag('mylink', 'ajax:complete') do |page|
page.hide 'wait'
end
%>
Instead of having to write raw prototype or jquery code, you can use rails helpers.

Resources