Javascript Response from Rails Controller leads to Uncaught SyntaxError: Unexpected token : - javascript

I have a form that creates a relation and when the form is submitted, javascript code that addes the newly connected nodes and the relations connecting them to the cytoscape graph should be returned:
The form:
<%= form_for Relation.new, :url => url_for(:controller => 'relations', :action => 'add_dependency'), remote: true do |f| %>
<%= f.hidden_field :to_id, :value => #article.id %>
<%= f.hidden_field :graph, :value => 1 %>
<%= f.select :from_id, [], {}, {class: "select-article"} %>
<%= f.submit "Add a dependency of this article." %>
<% end %>
The controller code:
def add_dependency
#relation = Relation.find_or_create_by(relation_params)
#relation.user << current_user
respond_to do |format|
if #relation.save
elements = json_for_cytoscape(#relation.from.self_and_all_dependencies_of_depth_and_less(3))
format.json { render :show, status: :created, location: #relation }
format.js { render js: "ancestors.add( #{elements} ); console.log('Hello');" }
else
format.json { render json: #relation.errors, status: :unprocessable_entity }
end
end
end
I get this error (and no "Hello") in the javascript console:
Uncaught SyntaxError: Unexpected token :
at processResponse (rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:244)
at rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:173
at XMLHttpRequest.xhr.onreadystatechange (rails-ujs.self-8944eaf3f9a2615ce7c830a810ed630e296633063af8bb7441d5702fbe3ea597.js?body=1:228)
This is the response:
ancestors.add( {:edges=>[], :nodes=>[{:data=>{:id=>200, :title=>"Test Yourself: Area & arc length using calculus", :href=>"http://localhost:3000/articles/200", :rank=>0.000459770114943, :color=>"grey"}}]} ); console.log('Hello');

I solved the problem by adding to_json:
json_for_cytoscape(#relation.from.self_and_all_dependencies_of_depth_and_less(3)).to_json

That response is not valid javascript and the reason is pretty simple. When you cast a Ruby hash to a string the result is not valid JS:
irb(main):001:0> { :foo => 'bar'}.to_s
=> "{:foo=>\"bar\"}"
Instead you need to encode it as JSON.
irb(main):003:0> { :foo => 'bar'}.to_json
=> "{\"foo\":\"bar\"}"
Due to quoting issues is easier done if you actually create a view instead of rendering inline:
ancestors.add( <%= elements.to_json %> );
console.log('Hello');

Related

Rails: Using remote: true to stop page refresh

I have a projects/show.html.erb page. A project has_many project_messages and from the projects/show.html.erb page, a user can create a new project_message successfully, however, when the new project_message is created through a _formpartial, the page refreshes.
I want to use :remote => true to add project_messages to the project without having to refresh the page.
Please see the code I used below. This does not work and the page still refreshes. I am new to rails so any help would be greatly appreciated.
Please see the code for each file below
In projects/show.html.erbto display the project_message and create a new project_message, I have the following code which is successful:
<div class="au-chat au-chat--border">
<div class="au-message-list">
<% #project.project_messages.each do |project_message| %>
<%= render partial: 'project_messages/project_message', locals: { project_message: project_message } %>
<% end %><br>
</div>
<div class="au-chat-textfield">,
<%= render partial: 'project_messages/form', locals: { project_message: #project_message } %>
</div>
</div>
In the project_messages_controller.rb file the create method is as follows, I have added format.js { }
def create
#project_message = ProjectMessage.new(project_message_params)
#project_message.user_id = current_user.id if current_user
#project_message.project_id = current_user.team.project_id if current_user
respond_to do |format|
if #project_message.save
format.html { redirect_to #project_message.project }
format.json { render :show, status: :created, location: #project_message }
format.js { }
else
format.html { render :new }
format.json { render json: #project_message.errors, status: :unprocessable_entity }
end
end
end
The project_message _form partial then includes the :remote => true
<%= form_with(model: project_message, local: true, :remote => true) do |form| %>
<% if project_message.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(project_message.errors.count, "error") %> prohibited this project_message from being saved:</h2>
<ul>
<% project_message.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<%= form.text_field :pMessage, id: :project_message_pMessage, :class => 'au-input au-input--full au-input--h65', placeholder: 'Type a message' %>
<div class="actions" >
<%= form.submit "Send" %>
</div>
<% end %>
I then created a new create.js.erb file in views/project_messages/create.js.erb and added the following code:
# confirm file called
console.log('create.js.erb file');
# add new comment to end of comments section
$("#project_message").append("<%= j render(#project_message) %>");
With the code above, the page still refreshes.
When I remove local: true from the project_message _form partial, it does not refresh and creates the model but the projects/show.html.erb view is not updated!
I used the following link here and also other posts on stackoverflow
respond_to do |format|
format.js { render 'project_messages/create.js'}
end
it seems you are using Rails 5
remove remote: true and local: true from your code
read about this in here
and make sure that you a html element with id = project_message
your code is $("#project_message").append("<%= j render(#project_message) %>");
so check your HTML code , is there any element with ID like that
you can use traditional form_for http://guides.rubyonrails.org/working_with_javascript_in_rails.html#remote-elements
update below code in your views
<%= form_for project_message, :remote => true do |form| %>
and make sure that you a html element with id like <div class="au-message-list" id="project_message">

render follow/unfollow button in rails with ajax

I have implemented follow/unfollow functionality and would like to add AJAX call to it, but I am stuck.
My partial _follow_button.html.erb for follow/unfollow which is rendered on Users->index, looks like:
<% if current_user.id != user.id %>
<% if !current_user.following?(user) %>
<%= form_for(current_user.active_relationships.build, remote: true) do |f| %>
<div><%= hidden_field_tag :followed_id, user.id %></div>
<span class="follow"><%= f.submit "Follow User", class: "btn btn-primary btn-sm" %></span>
<% end %>
<% else %>
<%= form_for(current_user.active_relationships.find_by(followed_id: user.id),
html: { method: :delete }, remote: true) do |f| %>
<span class="unfollow"><%= f.submit "Unfollow User", class: "btn btn-secondary btn-sm" %></span>
<% end %>
<% end %>
<% end %>
Then my controller for relationships looks like:
class RelationshipsController < ApplicationController
respond_to :js, :json, :html
def create
user = User.find(params[:followed_id])
#follow = current_user.follow(user)
end
def destroy
user = Relationship.find(params[:id]).followed
#unfollow = current_user.unfollow(user)
end
end
My view on user profile looks like:
<div class="col-5" style="margin-left: -5px;">
<%= render '/components/follow_button', :user => User.find_by_username(params[:id]) %>
</div>
My routes.rb have the following routes defined:
resources :users do
member do
get :following, :followers
end
end
resources :relationships, only: [:create, :destroy]
My Views folder structure has subfolders Users and Relationships. Both of them have separate controllers, and I have tried adding simple alert function 'alert("Works");' to the create.js.erb in both of those subfolders to try and match them with the controller, but none don't seem to work. This is my first Rails project, and I do not quite understand what the issue could be. Any suggestions?
Calling the partial follow/unfollow
<% if current_user.id != user.id %>
<%= render partial: 'follow_links', locals: { user: user }
<% end %>
Partial follow_links.
<% show_follow_link = current_user.following?(user) ? 'hidden' : '' %>
<% show_unfollow_link = current_user.following?(user) ? '' : 'hidden' %>
<!-- links to follow/unfollow have data-attributes that include the path to make the ajax post and the user to follow, that is used to find the link to show after the ajax call. You should use the path to the controller that will create or destroy the relationship -->
<%= link_to 'Follow', '#', { class: 'follow-user btn-success #{show_follow_link}', "data-url": follow_user_path(user.id), "data-followee": user.id } %>
<%= link_to 'Unfollow', '#', { class: 'unfollow-user btn-danger #{show_unfollow_link}', "data-url": unfollow_user_path(user.id), "data-followee": user.id } %>
Javascript for the partial. Ajax post to follow/unfollow
$('.follow-user').on("click",function() {
follow_unfollow($(this), "follow")
});
$('.unfollow-user').on("click",function() {
follow_unfollow($(this), "unfollow")
});
function follow_unfollow(target, what_to_do)
url = target.attr('data-url')
followee = target.attr('data-followee')
if (what_to_do == "follow") {
other_button = $('.unfollow-user[data-followee="'+followee+'"]')
} else {
other_button = $('.follow-user[data-followee="'+followee+'"]')
}
$.ajax( {
url: url,
type: 'post',
success: function() {
// Hide this link
target.addClass('hidden');
// Show the other link
other_button.removeClass('hidden');
},
error: function(ret) {
alert(ret.responseJSON.error);
}
});
};
Changes in your controller.
class RelationshipsController < ApplicationController
def create
user = User.find(params[:followed_id])
#follow = current_user.follow(user)
respond_to do |format|
if #follow.valid?
format.html
format.json: { render json: #follow }
return
else
format.html
format.json: { render json: { :error => 'Follow failed', :status_code :not_found } }
end
end
end
def destroy
user = Relationship.find(params[:id]).followed
#unfollow = current_user.unfollow(user)
respond_to do |format|
if #unfollow.valid?
format.html
format.json: { render json: #unfollow }
else
format.html
format.json: { render json: { :error => 'Unfollow failed', :status_code :not_found } }
end
end
end
end
An advice
An advice, also regarding your last question: I would recommend - instead of posting questions about debugging code on StackOverflow - create a good debugging environment for yourself.
Byebug or Binding pry is a good place to start, but before you can use those properly you need to understand the code you are using. I would recommend reading Working with Javascript in depth! - it really helped me getting the hang of it and understanding the dataflow of Rails and ajax.
This would, i think, break the unbreakable Stackoverflow-loop, that i myself were tied to for a long time:
loop do
puts "Try code"
sleep 1000
puts "Arrhh! an error!"
sleep 1000
puts "Posting on Stackoverflow"
sleep 1000
puts "Waiting for answer"
sleep 1000
end
I hope you figure it out!

Rails 'nil' is not an ActiveModel-compatible object. It must implement :to_partial_path. ajax

I am following section 4 (Server Side Concerns) to set up ajax on a page. I've copied the tutorial text completely (replacing the model names with my own) and it creates and saves my "Participants" record, but does not automatically refresh the ajax partial.
This is the error I get...which looks like it's referrring to my create.js.erb
ActionView::Template::Error ('nil' is not an ActiveModel-compatible object. It must implement :to_partial_path.):
1: $("<%= escape_javascript(render #participant) %>").appendTo("#participants");
2: // $('#participants').html("<%= j (render #participants) %>");
app/views/participants/create.js.erb:2:in `_app_views_participants_create_js_erb___1675277149181037111_70181034249880'
Here's my code
class ParticipantsController < ApplicationController
def new
#participant = Participant.new
#participants = #participants.recently_updated
end
def create
#participant = Participant.new(participant_params)
respond_to do |format|
if #participant.save
format.html { redirect_to #participant, notice: 'Helper Invited!' }
format.js {}
format.json { render json: #participant, status: :created, location: #participant }
else
format.html { render action: "new" }
format.json { render json: #participant.errors, status: :unprocessable_entity }
end
end
end
_form.html.erb
<ul id="participants">
<%= render #participants %>
</ul>
<%= form_for(#participant, remote: true) do |f| %>
  <%= f.label :email %><br>
  <%= f.email_field :email %>
<%= f.submit 'SUBMIT' %>
<script>
$(document).ready(function() {
return $("#new_participant").on("ajax:success", function(e, data, status, xhr) {
return $("#new_participant").append(xhr.responseText);
}).on("ajax:error", function(e, xhr, status, error) {
return $("#new_participant").append("<p>Oops. Please Try again.</p>");
});
});
</script>
<script>
$(function() {
return $("a[data-remote]").on("ajax:success", function(e, data, status, xhr) {
return alert("The helper has been removed and notified.");
});
});
</script>
_participant.html.erb
<li >
<%= participant.email %> <%= link_to participant, remote: true, method: :delete, data: { confirm: 'Are you sure?' } do %>REMOVE<% end %>
</li>
create.js.erb
$("<%= escape_javascript(render #participant) %>").appendTo("#participants");
destroy.js.erb
$('#participants').html("<%= j (render #participants) %>");
It's on line 2 of your create.js.erb file, it's the missing #participants not the #participant.
You've commented the line out in JS, but the ERB is still going to be processed by Rails, so it's still trying to do the render #participants
Update
For future... it's the last line of that error that's the key:
app/views/participants/create.js.erb:2
See the 2 at the end, that's telling you which line the error happened on, and so that's where you need to focus when looking for the problem.

Rails update model without leaving page

What would be the best way to update a record and display a flash success notice without leaving the page?
Here is part of my code but it redirects back to root path:
View
<%= form_for #user, url: record_testimonial_path(#user) do |f| %>
<%= f.text_area :testimonial %>
<%= f.submit "Submit"%>
<% end %>
Controller
def record_testimonial
#user.update_attribute(:testimonial, params[:user][:testimonial])
flash[:success] = "Thank you!"
redirect_to root_path
end
You can redirect back:
redirect_to :back, flash: { success: t('flash.thank_you') }
Or you have to do it via remote:
<%= form_for #user, url: record_testimonial_path(#user), remote: true do |f| %>
<%= f.text_area :testimonial %>
<%= f.submit "Submit"%>
<% end %>
And in the controller:
def record_testimonial
if #user.update_attribute(:testimonial, params[:user][:testimonial])
respond_to do |format|
format.js { render 'record_testimonial', layout: false }
end
else
render nothing: true # This will silently fail. Probably not intended.
end
end
And then the record_testimonial.js.erb:
$('#some_id').html('<%= j render "some_partial", user: #user %>');
These are the most common and I would say sensible ways. If you use ajax don't forget to manually display the flash message, should be 1 line of JS.
Best way to avoid a page refresh completely would be to set the form to use :remote => true like this
<%= form_for #user, url: record_testimonial_path(#user), :remote => true do |f| %>
and then respond accordingly in the controller:
def record_testimonial
respond_to do |format|
if #user.update_attribute(:testimonial, params[:user][:testimonial])
render :success
else
render :error
end
end
end
You would need a corresponding template for success and error here, with which to handle the displaying of a success or error message.
For further info, look here.

CoffeeScript keeps triggering Error when I'm getting a 200 response back?

I'm trying to do a remote: true form and I have it all setup, and when I click the submit button, the error action triggers every time. This is how my CoffeeScript is setup:
$(document).ready ->
$("#new_report").on("ajax:success", (e, data, status, xhr) ->
$("#new_report").append "<p>SUCCESS</p>"
).bind "ajax:error", (e, xhr, status, error) ->
$("#new_report").append "<p>ERROR</p>"
And my Reports_Controller
def create
#report = Report.new(params[:report])
respond_to do |format|
if #report.save
format.json { render json: "Created", :status => :created }
else
format.json { render json: #report.errors, status: :unprocessable_entity }
end
end
And my form:
<%= form_for(#report, remote: true ) do |t| %>
<p id="reportalert"></p>
<%= t.text_field :plant_site, placeholder: "Plant Site" %>
<%= t.text_field :route_number, placeholder: "Route Number" %>
<%= t.text_field :driver_name, placeholder: "Driver name if available" %>
<%= t.date_select :date_recorded, html: { class: "input-block-level" } %>
<%= t.text_field :action, placeholder: "Action taken" %>
<%= t.text_area :report_body, placeholder: "What you witnessed",
style: "height: 300px;",
class: "input-block-level" %>
<%= t.submit "File Report", class: "btn btn-primary btn-large" %>
<% end %>
But I check the rails log, and it's nothing but a 200 response, no errors, and the information is submitted to the database, so why is the ajax:error triggering? I have also tried replacing the ajax:error and ajax:success with ajaxSuccess and ajaxError but then it just doesn't do anything. Any information would be great thanks.
I'm trying to follow: http://edgeguides.rubyonrails.org/working_with_javascript_in_rails.html
It appears you're not returning a status in the JSON response from the controller. This is what triggers the ajax:success in jQuery:
if ( status >= 200 && status < 300 || status === 304 ) {....}
So your respond_to block should look like this:
respond_to do |format|
if #report.save
format.json { render json: "Created", :status => :created }
else
format.json { render json: #report.errors, status: :unprocessable_entity }
end
end

Categories