This is the code for my side bar. When a user clicks on one of the links, the js.erb file is called, but I don't know how to make the js.erb file be able to differentiate which link the user clicked on. My idea is to use an id, so basically pass the instance variable to the js.erb file. This is how I think it might be done, but I'm not sure at all.
<li>
<%= link_to 'User Details', '/dashboard', :id => 'User Details', remote: true %>
</li>
<li>
<%= link_to 'Projects', '/dashboard', :id => 'Projects', remote: true %>
</li>
There's the js.erb file that's run with this code:
<% if :id == 'User Details' %>
$('#ajax').html("<%= escape_javascript(render :partial => 'users/edit', :locals => { :user => #user } ) %>");
<% elsif :id == 'Projects' %>
$('#ajax').html("<%= escape_javascript(render :partial => 'projects/index', :locals => { :projects => #projects } ) %>");
<% end %>
What am I doing wrong or how should I pass some sort of flag or id to the js.erb file so that I can show the correct information?
I'm not sure if you understand how websites work. Ruby is a server-side language, it is executed and html + js are sent to the web browser. JS files are (in most cases) executed just once on asset compilation/first run and never get updated again.
So there's no way to refer to Ruby code from js on the runtime as you are doing.
Also you're using illegal characters in id attributes, see What characters are allowed in DOM IDs?
Back to ruby/js thing.
You may want to request a partial via ajax, passing an id attribute
$('#ajax').load('<%= here_put_helper_method_to_some_path %>');
And then in ProjectsController#index render what you wish (based on current user for example).
Also - a good rule is to first make things work without ajax and then add ajax calls.
Related
So I am trying to do an AJAX request in my form_tag. Basically, a user can enter a song name or an artist's name and I want to simply post what they searched for into a playlist (very simply here)
These are my files:
My form
<%= form_tag({:action => 'capp'}, method:'GET', class: 'ui form', remote: true , id: 'song_form') do %>
<div class="one field">
<div class="field" style="width: 100%">
<%= text_field_tag :query %>
</div>
</div>
<%= submit_tag("Search Song" , class: 'ui large green button') %>
<% end %>
Where I am trying to put the query entered
<div id="query"></div>
My 'app' Controller which has that action
class AppController < ApplicationController
respond_to :html, :js
def create
passcode = params[:passcode]
if passcode != nil && passcode.length > 1
redirect_to :controller => app, :action => capp, :passcode => passcode
end
end
def capp
#passcode = params[:passcode]
#query = params[:query] <-- I used pry and the query was being updated but the view itself was not.
if #query != nil
respond_to do |format|
format.html
format.js {}
end
end
end
end
My capp.js.erb file
addSongToPlaylist("<%= #query %>");
// For the record. I tried to also do this:
// addSongToPlaylist("<%= j render #query %>"); <-- But the app errored out saying render was an undefined method name...and all the online tutorials have their function rendering for some reason.
My capp.js file
function addSongToPlaylist(query) {
var c = "</br>" + query;
$("#query").append(c);
}
All I am hoping for is that the query I entered in the form above be placed in the
location below. But the as soon as I hit submit, the application doesn't do anything. the request goes through (I can see the server sending the GET request) but the view doesnt update. Please help!
I followed the tutorial on doing AJAX calls and for some reason it's still not working
Firstly, why aren't you using a path helper for your form_tag?
You'd benefit from using the likes of:
#config/routes.rb
get "/search/:query", to: "application#search", as: :search
This will allow you to use the following:
<%= form_tag search_path, remote: true, method: :get %>
<%= text_field_tag :query %>
<%= submit_tag "Search" %>
<% end %>
This will send a get request to your /search/:query path, which you'll then be able to process with your JS (explained in a second):
#app/controllers/application_controller.rb
class ApplicationController < ActionController::Base
respond_to :html, :js
def search
#passcode = params[:passcode]
#query = params[:query]
end
end
This should handle the request for you, looking to open app/views/application/search.js.erb
--
JS
For sake of clarity, let's just put the function into your called JS file:
#app/views/application/search.js.erb
$("#query").append("<br> <%=j #query %>");
This will do what your addSongToPlaylist function is doing.
Considering you've populated the #query variable, and are passing the ajax properly, this should work.
Debug
One of the main problems you'll have is that you're not debugging your application.
In this instance, there are a number of potential issues which could prevent your Ajax from firing:
Your ajax isn't being passed (IE JQuery is not loaded)
Your path is incorrect
Your controller isn't handling the request properly
You're not handling the JS correctly
The way to initially test is to look at the network tab of your browser's developer console:
To access it, right-click, inspect element, then select network. This will give you a list of all the requests you've sent to your server, and their responses.
When you click your "form submit" button - check to see whether a new request is invoked. If not, it will generally mean you don't have jquery in your app (which is required by the Rails UJS).
--
Next, you need to check your Rails console to see if you're getting any requests. If not, it will not show anything coming through.
What you're expecting is to see a new set of commands triggered when you submit your "search" form. This will show you which controller#action has been triggered. If it's right, move forward.
--
Finally, you need to check your JS.
You can do this by using alerts:
#app/views/application/search.js.erb
alert("<%=j #query %>");
$("#query").append("<br> <%=j #query %>");
If the alert fires positively, you've got a hit.
In my views I have recently started implementing remote javascript updates of only parts of my pages using commands such as:
$("#flash_messages").html("<%= escape_javascript(render 'shared/flash_messages') %>");
I now have a scenario where I have a list of items, each one within tags with a unique id and when the user clicks on a link within an item I want to only replace the contents of the corresponding
i.e.
<span id="article-123">
html here
</span>
create.js.erb
$("#???????").html("<%= escape_javascript(render 'shared/article') %>");
My question is how to I pass the span id "article-123" through to my create.js.erb file and include it as a variable in the above command.
Try with locals variable in render response, in YourController#method
respond_to do |format|
format.js { render "create", :locals => {:article_id => article_id} }
end
now you can use article_id in create.js.erb file.
I have a partial that I'm rendering via javascript:
$('#calendar').html('<%= escape_javascript(render :partial => "schedules/calendar", :locals => {:schedule_tasks => #schedule_tasks}) %>');
and everything works but this one line doesn't work, the params[:day] is in the original URL string:
<%= params[:day] == day.to_s ? 'green':'' %>
Is there something special I need to do to pass in the params[:day]? It's still in the URL.
I am following Michael Hartl's book to put in some following functionality into my app and when I attempt to use the AJAX on my follow and unfollow buttons I am receiving these errors when trying to change the buttons that are rendered:
Completed 500 Internal Server Error in 81ms
ActionView::MissingTemplate (Missing template users/follow_user, application/follow_user with {:locale=>[:en], :formats=>[:js, :html], :handlers=>[:erb, :builder, :coffee]}. Searched in:
* "/Users/hugo/Web Development/Rails/sample/app/views"
* "/Users/hugo/.rvm/gems/ruby-1.9.2-p318/gems/kaminari-0.13.0/app/views"
* "/Users/hugo/.rvm/gems/ruby-1.9.2-p318/gems/devise-2.0.4/app/views"
):
app/controllers/users_controller.rb:73:in `follow_user'
lib/ct_gems/dm-core-1.2.0/lib/dm-core.rb:263:in `block in repository'
lib/ct_gems/dm-core-1.2.0/lib/dm-core/repository.rb:114:in `scope'
lib/ct_gems/dm-core-1.2.0/lib/dm-core.rb:263:in `repository'
Rendered /Users/hugo/.rvm/gems/ruby-1.9.2-p318/gems/actionpack-3.2.3/lib/action_dispatch/middleware/templates/rescues/missing_template.erb within rescues/layout (0.5ms)
This is the code in my controller:
def follow_user
#other_user = User.get(params[:user_id].to_i)
current_user.follow(#other_user)
respond_to do |format|
format.html {redirect_to user_profile_path(#other_user)}
format.js
end
end
This is my form...well not form but the link to follow function:
<% unless current_user == #user %>
<div id="follow_form">
<% if current_user.following?(#user) %>
<%= render 'users/unfollow' %>
<% else %>
<%= render 'users/follow' %>
<% end %>
</div>
<% end %>
And this is one of the partials I am trying to render:
<%= link_to "Follow", user_follow_user_path(#user), :class => "btn btn-primary", :style => "margin-bottom:20px;", :remote => true %>
And this is the file to render the right button, I'm using this code my Michael's book:
$("#follow_form").html("<%= escape_javascript(render('users/unfollow')) %>")
However I am getting the error above that my partial is not found; can anyone explain to me why? Thanks
It's saying it's trying to render a template, which from my experience is a file in the views/ folder without the underscore preceding the name. Add the underscore to the start of the file name and do render :partial => 'users/follow' and see if that helps
Bad reading on my part, the problem was the naming of my javascript file. The name of that has to match your controller action.
My plan was to update a partial via a klick-event where I fetch some data via ajax.
So i opened my assets/javascripts directory and put the code in the js file of the module I planed to call it on. I managed to fetch the data and to call some "html() or text()" on the div. But as soon as I tried to call
.html("<%= escape_javascript( render( :partial => 'job') ) %>")
my controller told me unknown method "render". So I red in many other Threats that the assets directory was not build for static content.
But now comes the question where to put it if not in assets?
I tried to put it in the view/model folder (with the same name as the aktion 'show'). But it wouldn't load. Yes I told the Controller in the show action to respond_to format.js.
So where should I put the js-File and how to call it? Or is there even a method to let it in the assets-directory and beeing able to call render?
Thanks for your answer! Sadly I do exactly that but I doesnt work. So here is my Code:
/app/views/events/show.js.erb.coffee:
$(document).ready ->
url = window.location
url = String(url).split('/')
event_id = url[$.inArray( "events" , url) + 1]
$('.position').click ->
position_id = $(this).attr("id")
$.ajax '/events/'+event_id+'/eventpositions/'+position_id+'/eventjobs'
dataType: 'json'
success: (result)->
$( '#'+position_id ).find('.jobs').html("<%= escape_javascript( render( :partial => 'job') ) %>")
alert result[1].job_id
/app/views/events/show.html.haml:
%p#notice{:xmlns => "http://www.w3.org/1999/html"}= notice
%p
%b Name:
= #event.name
\
%b Plz:
= #event.plz
%p
%b Personal:
- #eventpositions.each do |p|
.position{:id => "#{p.id}"}
%b
Position: #{Position.find(p.position_id).name} Anzahl: #{p.quantity} Aufträge: #{p.eventjobs.all.count}
.jobs
= link_to 'Neuer Auftrag', new_event_eventposition_eventjob_path(#event.id,p.id)
%br
%br
= link_to 'Neue Position', new_event_eventposition_path(#event.id)
= link_to 'Edit', edit_event_path(#event)
|
\#{link_to 'Back', events_path}
/app/views/events/_job.html.haml:
.jobs
- eventjobs.each do |j|
User: #{User.find(Job.find(j.job_id).user_id).email}
%br
/app/controllers/events_controller.rb:
def show
#agency = Agency.find(current_agent.agency_id)
#event = #agency.events.find(params[:id])
#eventpositions = #event.eventpositions.all
respond_to do |format|
format.html # show.html.erb
format.json { render json: #event }
format.js
end
end
So the Code does work without Javascript. All renders and is fine. But my main Problem now is that it wont even react to a click event if I place it in the app/views/events Folder. As soon as I place it in the assets directory I works like a charm, but wont render.
So what am I missing? Why does my js Code does not get loaded?
Thanks a lot for your help!
Generally for this kind of thing, I'll name it the same as a particular action, such as show.js.erb, and then use the format.js as you have in the controller. If you're using coffeescript, it will need to be named show.js.coffee.erb. If this does not work, can you post the code of your view where this onclick event is setup?
Edit for using the show javascript code
Because you're using the show action, should just be able to do this:
= link_to "Show", #event, :remote => true, :format => :js
Adjust the event variable there as you need to, but it should work