I am a little stumped as to why my Ajax call is failing, It was working and cannot think of any changes that would have affected it. When i make the call i get an error in firebugs console that points to this in my jquery.js file
// Do send the request
// This may raise an exception which is actually
// handled in jQuery.ajax (so no try/catch here)
xhr.send( ( s.hasContent && s.data ) || null );
Firstly what does this mean?
My setup is like so
index.js.erb
<% if params[:type] == 'Tynewydd' %>
$('#newsResults').html('<%= escape_javascript(render partial: 'tynewyddposts') %>');
<% end %>
index.html.erb
<div id="newsResults">
<div class="hero-unit">
<h2> Welcome to your admin area</h2>
<p> xxxxxxxx.</p>
<p>xxxxxxxxx</p>
</div>
</div>
Link for ajax request
<li><%= link_to 'Tynewydd', posts_path(:type => 'Tynewydd'), :remote => true %></li>
Can anyone see what is going wrong here please or offer some debugging suggestions?
Any help appreciated
Edit
Controller
def index
#posts = Post.all
#tynewyddpost = Post.tynewydd_posts
#woodsidepost = Post.woodside_posts
#elmspost = Post.elms_posts
#sandpiperpost = Post.sandpiper_posts
#outreachpost = Post.outreach_posts
#companypost = Post.company_posts
#staffpost = Post.staff_posts
respond_to do |format|
format.html
format.js
end
Ok so i am no longer getting the error, i had an undefined method error for nil class in the called partial, so now in the console I can see the response but the partial that is supposed to render does not display on my page
Thanks
ok so just in-case anyone else runs into a similar issue changing $ to jQuery has solved the problem, so this
<% if params[:type] == 'Tynewydd' %>
$('#newsResults').html('<%= escape_javascript(render partial: 'tynewyddposts') %>');
<% end %>
was changed to this
<% if params[:type] == 'Tynewydd' %>
jQuery('#newsResults').html('<%= escape_javascript(render partial: 'tynewyddposts') %>');
<% end %>
Related
When calling render The view is not being updated, however, I do notice in the network tab, after the POST request is made to me POST route, it's returning HTML as the response, and the response has my rendered error message. It's just not updating the page. I don't know what to make of that.
In my POST action, I'm forcing this to be called
flash.now[:notice] = responseMessage
render :deactivate_show
Which renders the action:
def deactivate_show
#user = User.find(params[:id])
authorize! :deactivate_user, #user
if current_user.role == "admin"
if #user.broker?
#companyUsers = User.where(parent_id: #user.id)
#properties = Property.where(user_id: #user.id)
.or(Property.where(user_id: #companyUsers.ids))
elsif #user.broker_manager?
# get all agents in company
# exclude current user
# get broker
#companyUsers = User.where(parent_id: #user.parent_id)
.where.not(id: #user.id)
.or(User.where(id: #user.parent_id))
#properties = Property.where(user_id: #companyUsers.ids)
.or(Property.where(user_id: #user.parent_id))
else #user.agent?
#properties = #user.properties
if #user.parent_id?
#companyUsers = User.where(parent_id: #user.parent_id)
.where.not(id: #user.id)
.or(User.where(id: #user.parent_id) )
else
# dealing with owner.
#companyUsers = User.where('role IN (2,4,1)')
.where.not(id: #user.id)
end
end
else
end
end
which renders a view I have that displays the form.
I added to my show view:
<div class="messages">
<% flash.each do |key, value| %>
<div class="hello"><%= value %></div>
<% end %>
</div>
Note the class of "hello".
When I make a POST request, the response in the network tab has the notice:
Rendered from POST request response:
<div class="messages">
<div class="hello">testing errors</div>
</div>
Edit: here's the form:
<div class="form-wrap">
<%= form_with do %>
<%= button_tag( id: 'button--submit', class: 'button button--secondary') do %>
<i class="icon-arrow-right"></i>
<span>Deactivate</span>
<% end %>
<% end %>
</div>
Well the actual answer was something no one could have provided since I didn't share my form. I was using form_with, which apparently does AJAX by default, thus not rendering the view.
Thanks for the help from this question: Rails render not showing in browser, despite positive server reply
I've changed
<%= form_with do %>
to
<%= form_with local: true do %>
and now it works.
The Flash is only rendered upon a new request, which you don't make with render. Instead, you should use flash.now[:notice] to have it display on render.
I realize there are dozens of similar questions here on this topic, I have looked through many of them and tried to duplicate the solutions and nothing has worked for me.
I have a list of tasks displayed in the index view as a partial, when the user adds a task I would like list to show the newest task (as well as all the others already there).
Here is the create controller:
def create
#task = current_user.tasks.build(task_params)
if #task.save
flash[:success] = "Task added"
respond_to do |format|
format.js
end
else
flash[:error] = "Task not added"
render 'new'
end
The _new partial:
<%= form_for(#task, method: :post, remote: true) do |f| %>
<%= f.label :comments %>
<%= f.text_field :comments, id: "task-comments" %>
<%= f.submit "Insert" %>
<% end %>
Index.html.erb
<div id="new-task-form">
<%= render 'new' %>
</div>
<div id="current-tasks">
<%= render partial: 'show_list', locals: {tasks: #tasks} %>
</div>
create.js.erb
console.log("create.js.erb called");
document.getElementById("task-comments").value = "";
document.getElementById("current-tasks").html('<%= j(render partial: "show_list") %>');
I have been able to get the console to log the message and even been able to clear the input box but the partial does not render, I have tried this in a few different ways and the script always seems to stop executing when it gets to the escape javascript line.
There are no JS errors, as stated above, the console logs the message when the "submit" button is pressed. There is a warning [Violation] Forced reflow while executing JavaScript took 114ms but I don't think that is relevant to this issue.
Here is the partial that I am trying to render _show_list.html.erb
<% unless #tasks.nil? %>
<ul>
<% tasks.each do |tsk| %>
<li><%= tsk.comments %></li>
<% end %>
</ul>
<% end %>
def create
#task = current_user.tasks.build(task_params)
if #task.save
flash[:success] = "Task added"
#respond_to do |format|
#format.js
#end
else
flash[:error] = "Task not added"
render 'new'
end
end
It's always good practice to use local variable in partial
1) => Index.html.erb
<div id="new-task-form">
<%= render 'new' %>
</div>
<div id="current-tasks">
<%= render partial: 'show_list', locals: {tasks: #tasks} %>
</div>
2) => If you are using jquery (create.js.erb)
console.log("create.js.erb called");
$("#task-comments").val('');
$("#current-tasks").html('<%= j render "show_list", tasks: #tasks) %>');
3) => _show_list.html.erb(Use tasks instead of #tasks)
<% unless tasks.blank? %>
<ul>
<% tasks.each do |tsk| %>
<li><%= tsk.comments %></li>
<% end %>
</ul>
<% end %>
ok you have some problem here with your validation on the show_list partial.
you have this line
<% unless #tasks.nil? %>
try to use something more readable like
<% if #tasks.present? %>
and on your controller create action, you don't fill the #tasks variable, so that's the problem in reality, add on you controller the load for all the tasks after saving the new one.
if #task.save
#tasks = Task.all
flash[:success] = "Task added"
and that will make it work, but I recommend to load just the created one and add just one column to the table and not update the complete list again if you have all the others on the client already.
In my show view I have this div:
<% if #question.answers.any? %>
<div class="parent">
<%= render :partial => #question.answers %>
</div>
<% else %>
<p class="hideAns">No answers yet. Be the first first to answer!</p>
<% end %>
As shown from the code above, I am displaying a paragraph if the question has no answers. The problem that I am facing is checking if the question has answers again with ajax.
In my create.js.erb file, I have this block of code that hides the paragraph:
$("#answers").append("<%= j render #answer %>");
tinyMCE.activeEditor.setContent('');
$(".hideAns").css("cssText", "display: none;");
In my delete.js.erb file, (This is where I am getting the Internal server error.) I have this block of code that checks whether the question has any answers or not:
$("#answer_<%= #answer.id %>").remove();
<% if #questions.answers.any? %>
console.log("has answers");
<% else %>
$(".hideAns").css("cssText", "display: block;");
<% end %>
Why is it not working? Am I not allowed to put an if statement inside a .js.erb file?
EDIT
Server log:
ActionView::Template::Error (undefined method `answers' for nil:NilClass):
1: $("#answer_<%= #answer.id %>").remove();
2:
3: <% if #question.answers.any? %>
4: console.log("has answers");
5: <% else %>
6: $(".hideAns").css("cssText", "display: block;");
7: <% end %>
Answer was to simply define the instance variable in the destroy method.
The fix:
def destroy
#question = Question.find(params[:question_id])
#answer.destroy
respond_to do |format|
format.html { redirect_to :back }
format.js
end
end
I cannot figure out why my rails views are not recognizing flash[:notice] or flash[:error]. I keep getting the following error regarding the partial view being rendered. The specific error is:
ActionView::Template::Error (You have a nil object when you didn't expect it!
You might have expected an instance of Array.
The error occurred while evaluating nil.[]):
In my controller I have
def index
#organisms = Organism.all
flash[:error] = "test"
flash[:notice] = "test"
respond_to do |format|
format.html
format.json { render :json => #organisms }
end
end
In my index.html.erb file I render out a partial through:
<%= render "shared/flash" %>
The partial has the following code.
<div id="flashes">
<% if flash[:notice] %>
<p id="flash_notice" class="messages notice"><%= flash[:notice] %></p>
<%= javascript_tag "$('#flash_notice').effect('highlight',{},1000);" %>
<% end %>
<% if flash[:error] || flash[:errors] %>
<p id="flash_errors" class="messages errors"><%= flash[:error] || flash[:errors] %></p>
<%= javascript_tag "$('#flash_errors').effect('highlight',{},1000);" %>
<% end %>
<% flash[:error] = flash[:errors] = flash[:notice] = nil %>
</div>
However, if instead of rendering the partial I throw in <%= notice %> it renders out the notice.
If I take the partial code and stick it in the top of the index.html.erb file it renders correctly. Thus, I assume that I am rendering the partial view wrongly?
Any help is much appreciated. Thanks!
Don't name your partial flash. Ruby on Rails creates a local variable with the same name as the partial. In your case, a flash local variable is being created.
Rename your partial to something other than flash and it should work.
Also, you shouldn't need to set flash to nil at the bottom of your partial. Let Rails take care of that for you.
You have to pass the flash to the partial:
<%= render 'shared/flash', flash: flash %>
Or a bit longer:
<%= render partial: 'shared/flash', locals: { flash: flash } %>
I'm creating a simple demo app that allows a user to enter their email address to register their interest in receiving beta access. The app then sends them a confirmation email that lets them know we've received their request. If you've ever signed up to be notified of a beta launch then you get the idea.
I'm curious about how to handle errors in Rails 3 while using AJAX. Before implementing my respond_to block I had a form that rendered a shared errors partial.
Here's the form.
<% if flash[:notice] %>
<p><%= flash[:notice] %></p>
<% end %>
<p>Sign up to be notified when the beta launches.</p>
<%= form_for #user, :remote => true do |form| %>
<%= render '/shared/errors', :target => #user %>
<%= form.label :email, "Your Email Address" %>
<%= form.text_field :email %>
<%= form.submit "Notify Me" %>
<% end %>
And here's the aforementioned errors partial.
<% if target.errors.any? %>
<ul>
<% target.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
<% end %>
Very standard stuff. The controller action looks like this.
def create
#user = User.new(params[:user])
respond_to do |format|
if #user.save
format.html { redirect_to :back, flash[:notice] = "Thanks for your interest! We'll let you know when the app is in beta." }
format.js
else
format.html { render :action => :new }
format.js
end
end
end
Everything works perfectly before implementing ajax. If the form passes validation then they see the success flash message and if not then they see a list of errors. So now that i have a create.js.erb file how should I handle the errors without repeating myself or is that impossible. I obviously want to keep this as DRY as possible.
You can still render a shared partial for all .js errors in your js.erb file.
<% if #user.errors.any? %>
var el = $('#create_user_form');
// Create a list of errors
<%= render :partial=>'js_errors', :locals=>{:target=> #user} %>
<% else %>
$('#users_list').append("<%= escape_javascript(render :partial=>"users/show", :locals=>{:user => #user }) %>");
// Clear form
el.find('input:text,textarea').val('');
el.find('.validation-errors').empty();
<% end %>
And your partial could look like (Assuming jquery):
<% target.errors.full_messages.each do |error| %>
var errors = $('<ul />');
errors.append('<li><%= escape_javascript( error ) %></li>');
<% end %>
But there's also ANOTHER option...It's even DRYer.
http://www.alfajango.com/blog/rails-3-remote-links-and-forms/
If you are working your way through ajax in rails 3, this guide is really the best for understanding responses and ajax rendering as it currently stands.
I worked through this guide and posted in the comments how you can actually use your HTML partials for both HTML and AJAX request responses. I did it by accident and then followed up on how to do it.
Enjoy!
You can actually return straight-up html with your response just like before.
Here's the short version:
def create
#something = Somethng.new(params[:something])
if #something.save
respond_with( #something, :status => :created, :location => #something ) do |format|
format.html do
if request.xhr?
render :partial => "something/show", :locals => { :billable => #billable }, :layout => false
end
end
end
else
respond_with( #something.errors, :status => :unprocessable_entity ) do |format|
format.html do
if request.xhr?
render :partial => "something/new", :locals => { :something => #something }, :layout => false
else
render :action => :new
end
end
end
end
end
I'm not sure the rails remote form way to do it, but my standard mode of operation is to return objects on ajax request in this format:
{ success: true|false,
data: "html or some other data",
errors: {} } // jsonified ActiveModel::Errors object
It works very well and lets you render partials into the data field for use on the page, or you can loop through errors in the error object to insert error messages or highlight fields.
I have been facing the same problem a few days ago. I used remote => true option in my form to use Ajax in my Rails 3 application. After that, I have been looking for solution for validating my form fields. After trying a good number of jQuery / Javascript approaches (none of them worked for me though) I came to know about a superb gem called client_side_validations. It is very easy to install by following the instructions on github link (https://github.com/bcardarella/client_side_validations). It works like charm for client side validation of form fields, an awesome gem indeed. Hope this helps with people who are tired of looking for a simple solution for client side validation of model fields after using Ajax in Rails 3 application.