I have a page which shows a highchar. I'd like to use Javascript to fetch several pieces of information for a specific user. I want to fetch from my database and place it on the highcharts graoh. I have set up a JSfiddle which shows static data. But
What I am trying to do is:
Make javascript call a Rails action with parameters.
Query the rails database(projectHours table).
Rails returns the response.
Javascript updates highcharts and maps the information stored in the projectHours table.
So my question is What if I want to use information from my db?
Two of the following models
Effort.rb
class Effort < ActiveRecord::Base
belongs_to :project_task
belongs_to :user
end
Users.rb
class User < ActiveRecord::Base
has_many :projects
has_many :efforts
A further note, I think that in my efforts controller I may need to add some form of render action
rails reponds_to do |f| f.json
{ render :json => some_hash
}
end
You can use jQuery's get function in order to send a GET request to your rails app like so
$.get("/efforts/24", { name: "John", time: "2pm" } );
And in your controller you could do something like
def show
#effort = Effort.find(params[:id])
# or find by some of the name of time params
respond_to do |f|
format.json { render :json => #effort }
end
end
Depending on how you want to render the results you can either let javascript handle the ajax:success by adding in to the original jQuery get
$.get("/efforts/24", { name: "John", time: "2pm" } ).success(function(data) {
alert(data)
// Or do whatever you want :)
});
Or you can change the respond_to to
respond_to do |f|
format.html { render :nothing => true }
format.js
end
And create a show.js.erb in your app/views/efforts directorty. In this file you can use the responded object
$('body').html("<h1><%= escape_javaScript(#effort.title) %></h1>").append("
<%=escape_javaScript(#effort.content) %>");
Some good tutorials
Rails and jQuery
jQuery GET
Related
I'm trying to implement javascript polling in my app but I'm running into a few problems. I'm pretty much following along with this railscasts. My problem is in trying to prepending any new data found. It prepends all of the data old and new and if there isn't any new data found it just prepends all of the old data. My other problem is that my setTimeout is only being called once, even after I try to keep it polling like they show in railscast. Below is my code. What am I doing wrong here?
polling.js
var InboxPoller;
InboxPoller = {
poll: function() {
return setTimeout(this.request, 5000);
},
request: function() {
return $.getScript($('.inbox_wrap').data('url'), {
after: function() {
$('.conversation').last().data('id')
}
});
}
};
$(function() {
if ($('.inbox_wrap').length > 0) {
return InboxPoller.poll();
}
});
polling.js.erb
$(".inbox_wrap").prepend("<%= escape_javascript(render #conversations, :locals => {:conversation => #conversation}) %>");
InboxPoller.poll();
conversations_controller.rb
class ConversationsController < ApplicationController
before_filter :authenticate_member!
helper_method :mailbox, :conversation
def index
#messages_count = current_member.mailbox.inbox({:read => false}).count
#conversations = current_member.mailbox.inbox.order('created_at desc').page(params[:page]).per_page(15)
end
def polling
#conversations = current_member.mailbox.inbox.where('conversation_id > ?', params[:after].to_i)
end
def show
#receipts = conversation.receipts_for(current_member).order('created_at desc').page(params[:page]).per_page(20)
render :action => :show
#receipts.mark_as_read
end
def create
recipient_emails = conversation_params(:recipients).split(',').take(14)
recipients = Member.where(user_name: recipient_emails).all
#conversation = current_member.send_message(recipients, *conversation_params(:body, :subject)).conversation
respond_to do |format|
format.html { redirect_to conversation_path(conversation) }
format.js
end
end
def reply
#receipts = conversation.receipts_for(current_member).order('created_at desc').page(params[:page]).per_page(20)
#receipt = current_member.reply_to_conversation(conversation, *message_params(:body, :subject))
respond_to do |format|
format.html { conversation_path(conversation) }
format.js
end
end
private
def mailbox
#mailbox ||= current_member.mailbox
end
def conversation
#conversation ||= mailbox.conversations.find(params[:id])
end
def conversation_params(*keys)
fetch_params(:conversation, *keys)
end
def message_params(*keys)
fetch_params(:message, *keys)
end
def fetch_params(key, *subkeys)
params[key].instance_eval do
case subkeys.size
when 0 then self
when 1 then self[subkeys.first]
else subkeys.map{|k| self[k] }
end
end
end
def check_current_subject_in_conversation
if !conversation.is_participant?(current_member)
redirect_to conversations_path
end
end
end
index.html.erb
<%= content_tag :div, class: "inbox_wrap", data: {url: polling_conversations_url} do %>
<%= render partial: "conversations/conversation", :collection => #conversations, :as => :conversation %>
<% end %>
_conversation.html.erb
<div id="conv_<%= conversation.id %>_<%= current_member.id %>" class="conversation" data-id="<%= conversation.id %>">
<div class="conv_body">
<%= conversation.last_message.body %>
</div>
<div class="conv_time">
<%= conversation.updated_at.localtime.strftime("%a, %m/%e %I:%M%P") %>
</div>
</div>
Javascript polling is extremely inefficient - basically sending requests every few seconds to your server to listen for "updates". Even then, in many cases, the updates will be entire files / batches of data with no succinctness
If we ever have to do something like this, we always look at using one of the more efficient technologies, specifically SSE's or Websockets
--
SSE's
Have you considered using Server Sent Events?
These are an HTML5 technology which work very similarly to the Javascript polling - sending requests every few seconds. The difference is the underlying way these work -- to listen to its own "channel" (mime type text/event-stream -- allowing you to be really specific with the data you send)
You can call it like this:
#app/assets/javascript/application.js
var source = new EventSource("your/controller/endpoint");
source.onmessage = function(event) {
console.log(event.data);
};
This will allow you to create an endpoint for the "event listener":
#config/routes.rb
resources :controller do
collection do
get :event_updates #-> domain.com/controller/event_updates
end
end
You can send the updates using the ActionController::Live::SSE class:
#app/controllers/your_controller.rb
Class YourController < ApplicationController
include ActionController::Live
def event_updates
response.headers['Content-Type'] = 'text/event-stream'
sse = SSE.new(response.stream, retry: 300, event: "event-name")
sse.write({ name: 'John'})
sse.write({ name: 'John'}, id: 10)
sse.write({ name: 'John'}, id: 10, event: "other-event")
sse.write({ name: 'John'}, id: 10, event: "other-event", retry: 500)
ensure
sse.close
end
end
--
Websockets
The preferred way to do this is to use websockets
Websockets are much more efficient than SSE's or standard JS polling, as they keep a connection open perpetually. This means you can send / receive any of the updates you require without having to send constant updates to the server
The problem with Websockets is the setup process - it's very difficult to run a WebSocket connection on your own app server, hence why many people don't do it.
If you're interested in Websockets, you may wish to look into using Pusher - a third party websocket provider who have Ruby integration. We use this a lot - it's a very effective way to provide "real time" updates in your application, and no I'm not affiliated with them
Are you sure that polling is happening only once? Did you check in the console to make sure of that?
To me it looks like it might be happening, because I see issues in your javascript that prepends the content. What you have is this:
$(".inbox_wrap").prepend("<%= escape_javascript(render #conversations, :locals => {:conversation => #conversation}) %>");
This will actually insert the new content before inbox_wrap div. I think your intention is to prepend to the conversations list. For that, you should change it to this (Reference jQuery Docs: http://api.jquery.com/prepend/):
$(".conversation").prepend("<%= escape_javascript(render #conversations, :locals => {:conversation => #conversation}) %>");
The next thing is that I am assuming you want to prepend the new conversations on top of the list, which means two things.
The controller will return new conversations ordered by date in descending order.
Assuming above is correct, you would need to get the first conversation's id in your InboxPoller to pass to the controller as after parameter.
$('.conversation').first().data('id')
One More Thing
Another thing is that you can use the native Javascript function setInterval instead of setTimeout. setInterval executes a given function periodically, as opposed to setTimeout which does it only once. This way you won't have to initiate your InboxPoller after every call to the back-end, in .js.erb file.
Update
Again, looking at jQuery Documentation, it looks like $.getScript() does not pass any parameters back to the server. Instead use $.get as below:
InboxPoller = {
poll: function() {
return setInterval(this.request, 5000);
},
request: function() {
$.get($('.inbox_wrap').data('url'), {
after: function() {
return $('.conversation').first().data('id');
}
});
}
};
Also, I think you need to add .order('created_at desc') in polling method in your controller.
I have the following code:
= link_to "#{icon('heart')} Props".html_safe, vote_picture_path(picture), class: 'tiny radius secondary button vote', method: :put, remote: true
Which goes here:
# VOTE /pictures/1.json
def vote
respond_to do |format|
if #picture.toggle_vote(current_user)
format.json { render json: #picture }
else
format.json { render json: #picture }
end
end
end
And what I'm trying to do is update the total count of votes on a picture via:
$ ->
$(".vote").on "ajax:success", (e, data, status, xhr) ->
vote_count_size = $(".vote-count .size").html()
vote_count_size_integer = parseInt(vote_count_size)
console.info data
However the part that confuses me is the console.info data. It seems to be returning something from a source I can't tell. I'm editing /pictures/show.json.jbuilder but it's not affecting what's coming in from data. I want to return a json structure with the total votes in data so I can update the count on the page from the success callback.
Firstly, your respond_to block can be refactored dramatically:
# VOTE /pictures/1.json
respond_to :json
def vote
#picture.toggle_vote(current_user)
respond_with #picture
end
This should return a JSON object for your #picture var. You'll have to detail what data you're getting in your console? If you provide the data you're receiving back, it will be a huge help!
You should respond with a javascript file (vote.js.erb) within this you can mix javascript and erb expressions to change the desired page element:
$('.vote-count .size').html('<%=#picture.vote_count%> votes');
your controller would look like:
# VOTE /pictures/1.js
def vote
respond_to do |format|
#picture.toggle_vote(current_user)
format.js
end
end
Creating an update.js.erb, or edit.js.erb javascript file is connected to the rails 3 actions?
I'm new to rails 3 but know javascript.
If I add respond_to to each action to accept javascript, then will this code be called upon the action?
Thanks
Unable to understand your question, but based on what I understand you might looking for this.
You can render js files using render :js like:
render js: "$('#div_name').some_event;"
In Rails 3 you should set different respond types on the top of your controller class.
Something like this (probably it does not make any sense, but this is a dummy example):
class UsersController < ApplicationController::Base
respond_to :html
respond_to :xml, :json, :except => [ :edit ]
respond_to :js, :only => [:create]
def index
respond_with(User.all)
end
end
Then, you are responding using respond_with, and Rails will recognize type of request based on Accept header or request.format like (/users.json, /users.xml, etc.) and render proper files (index.html.erb, create.js.erb, etc.) depending on format
"Creating an update.js.erb, or edit.js.erb javascript file is connected to the rails 3 actions?" not necessarily, but it should be. conventionally, the file name should be the same as the method name. its a logical relation. but u can specify a file name(if the file name is different the method name) by
respond_to do |format|
format.js { render :action => "different_action" }
end
I am trying to access a field in a Ruby on Rails object from my view inside some JavaScript. Here is the relevant code in my view pick.html.erb:
var directionDisplay;
var start = <%= #route.from %>;
var end = <%= #route.to %>;
From and to are text fields that hold zipcodes. Here is my relevant Route controller code:
class RoutesController < ApplicationController
# GET /routes/1/pick
def pick
#routes = Route.find(params[:id])
end
I read somewhere that I need to use ActiveSupport::JSON in order to access an object field...Do I need to do this instead? If so, how do I install it and could you possibly give me an example on how to get started? I've been searching for examples everywhere the past few days and I can't find any.
Let me know if you need any more code and thank you in advance for any reply!
The file name should be (according to convention) pick.js.erb and not pick.html.erb based on the fact that you have JavaScript code included.
If you want to include a partial inside this one, you can use the escape_javascript helper to render the partial.
If you have more than one possible file to be rendered from the pick action, you should look into using respond_to such as:
#route = Route.find(params[:id])
respond_to do |format|
format.html
format.js { render :js => #route }
end
Greetings,
I have an application which contains a calendar as alternative index view for Courses (Project has_many Courses). There I have two arrows for navigating to the next/previous month, it works via AJAX. Now, that's my action for updating the calendar:
def update_calendar
#project = Project.find params[:id]
#date = Date.parse(params[:date]).beginning_of_month
#courses = #project.courses.all(:conditions => {:date => (#date - 1.month)..(#date + 1.month)})
respond_to do |format|
# format.html { redirect_to :action => 'index' }
format.js { render :partial => 'calendar', :locals => {:calendar_date => #date, :courses => #courses} }
end
end
The important part is format.js { ... }. I thought it should just answer js/AJAX requests, but it doesn't. It renders the partial when I hit the URL http://localhost:3000/projects/1/update_calendar?date=2010-08-01 for example. I don't want that behaviour, I just want it to answer correctly when it's coming in via AJAX. Do I need to use request.xhr?? And what is format.js { ... } supposed to do than?
Best regards
Tobias
You need to tell it what you want to happen when someone goes to that action with an html request, ie you need to put your format.html block back in. If you don't have the braces it will do the default behaviour which is to show the update_calendar view. You probably want to redirect to a different action though.