Hansontable on rails load data from json response - javascript

If I have a controller that return a json, How can I load the json data result into the page using jquery, also my webpage is using the remote true, so the request will be ajax, the result json is return to the page, bu t now I need to load the json array into the handsontable. I need somekind of binding of the data returned by the json call into the handsontable object.
class GradesController < ApplicationController
def index
logger.debug params
respond_to do |format|
format.html
format.json { render json: GradesDatatable.new(view_context) }
#format.js { #result = GradesDatatable.new(view_context).as_json }
end
end
end
Webpage
<div class="row">
<%= simple_form_for :filters, url: grades_index_path('json'), method: :get, :remote => true do |f| %>
<div class="small-4 columns">
<%= f.input :curso, collection: Curso.all, :label_method => "nombre", :value_method => "nombre" %>
<%= f.input :seccion, collection: Seccion.all, :label_method => "nombre", :value_method => "nombre" %>
<%= f.collection_radio_buttons :tanda, [['M', 'Matutina'] ,['D', 'Despertina'],['N', 'Nocturna']], :first, :last, :checked => 'M' %>
</div>
<div class="small-3 columns">
<div class="form-actions">
<%= f.button :submit, "Filtrar", :class => "button large" %>
</div>
</div>
<% end %>
</div>
<div class="row">
<div id="grades"></div>
</div>
JS
$(function(){
data = []
window.data = data.aaData
var container = document.getElementById('grades');
window.hot = new Handsontable(container,
{
data: window.data,
...

Related

Cannot Attach ajax:error handler to Form ID

I am having trouble binding an ajax:error response to a form ID. Can someone point me in the right direction to solve this problem?
Here is the code.
<%= form_for #person,
html: {
id: '#person_form',
class: 'js_inline_validate'
},
data: { validate_url: validate_field_people_path },
remote: true,
url: people_path do |f| %>
<div class="form-group">
<div class='form-group-label'>
<%= f.label :first_name %>
</div>
<%= f.text_field :first_name,
:id => 'first_name',
class: 'js_new_person_frm_validate js_new_person_first_name' %>
<div class="text-error small">
<span>
<%= #person.errors.full_messages_for(:first_name).first if #person.errors[:first_name].any? %>
</span>
</div>
</div>
<div class="form-group">
<div class='form-group-label'>
<%= f.label :last_name %>
</div>
<%= f.text_field :last_name,
:id => 'last_name',
class: 'js_new_person_frm_validate js_new_person_last_name' %>
<div class="text-error small">
<span>
<%= #person.errors.full_messages_for(:last_name).first if #person.errors[:last_name].any? %>
</span>
</div>
</div>
<div class="form-group">
<%= f.submit "Create", data: { disable_with: false } %>
</div>
<% end %>
Controller
class PeopleController < ApplicationController
......
def create
#person = Person.new(create_params)
if(#person.save)
flash[:success] = "person created successfully"
redirect_to root_path
else
respond_to do |format|
format.html { render :action => 'new' }
format.any(:js, :json) {
render :json => { :error => #person.errors }, :status => 422
}
end
end
end
.....
end
CoffeeScript
$ ->
$("#person_form").on "ajax:error", (event, data, status, xhr) ->
alert "ajax:error!"
#do more stuff
The issue I cannot solve is this works as below when I use 'document', but I need this to be specific to my #person_form. And I get no response when I replace document with my form_id. Am I missing something simple here?
$ ->
$(document).on "ajax:error", (event, data, status, xhr) ->
alert "ajax:error!"
#do more stuff
Thank You!
I'm leaving this simple answer out here for anyone else who may run across this issue. Hopefully, it's this simple for the next person. It took me HOURS to track down the problem.
It turns out the error was happening because of a very simple mistake:
<%= form_for #person,
html: {
id: '#person_form', <= ERROR IS HERE!!
class: 'js_inline_validate'
},
data: { validate_url: validate_field_people_path },
remote: true,
url: people_path do |f| %>
The #person_form should have been person_form (excluding the pound sign). Just a very simple error in code I didn't catch when switching from script to ruby.
The global event handler would catch the ajax:error and execute the code properly. The pound sign in the identifier was preventing the proper registration of the local ajax event.

rails - adding JavaScript function to form field not saving filed value in database

I wrote a rails form and it was working fine until I added a javascript to it. This javascript sums field values enter by user and saves them in a total field so user don't have to manually total it.
here is my code:
<script type="text/javascript">
function findTotal(){
console.log("this is working")
var arr = document.getElementsByName('qty');
var tot=0;
for(var i=0;i<arr.length;i++){
if(parseInt(arr[i].value))
tot += parseInt(arr[i].value);
}
document.getElementById('total').value = tot;
}
</script>
<%= bootstrap_form_for(#payment) do |f| %>
<div class="field">
<%= f.text_field :student_id,label: "Admission Number of Student" %>
</div>
<div class="field">
<%= f.number_field :tuition_fee , onblur: "findTotal()", id: "qty1", name: "qty" %>
</div>
<div class="field">
<%= f.number_field :fine, onblur: "findTotal()", id: "qty2", name: "qty" %>
</div>
<div class="field">
<%= f.number_field :previous_books, onblur: "findTotal()", id: "qty3", name: "qty" %>
</div>
<div class="field">
<%= f.number_field :annual_fund, onblur: "findTotal()", id: "qty4", name: "qty" %>
</div>
<div class="field">
<%= f.hidden_field :total, name: "total", id: "total" %>
</div>
<div class="actions">
<%= f.submit class: "btn btn-success" %>
</div>
<% end %>
Now when I fill the form, the function works fine and submitting button creates record as well but all the values entered in these number fields are not stored in the database and it shows nil. If I remove it from number fields, these work fine. Any idea what I am doing wrong? thanks.
EDIT:
here are my params:
private
# Use callbacks to share common setup or constraints between actions.
def set_payment
#payment = Payment.find(params[:id])
end
# Never trust parameters from the scary internet, only allow the white list through.
def payment_params
params.require(:payment).permit(:student_id, :section_id, :year, :month, :date, :payment_mode, :tuition_fee, :fine, :previous_books, :annual_fund, :total)
end
end
and relevant controller method:
def create
#payment = Payment.new(payment_params)
#payment.student_id = Student.find_by_admission_number(#payment.student_id).id
#payment.section_id = Student.find(#payment.student_id).section_id
respond_to do |format|
if #payment.save
format.html { redirect_to new_payment_path, notice: 'Payment Record was successfully created.' }
format.json { render :show, status: :created, location: #payment }
else
format.html { render :new }
format.json { render json: #payment.errors, status: :unprocessable_entity }
end
end
end
The problem is that you are overriding the 'name' attributes. They should be like, for example: name="payment[fines]". So, when you do submit, it generates the following object:
Parameters=> { payment => { fines: value} }
That is spected in your controller (payment_params)

Why is the link_to submitting form twice?

I am trying to use JavaScript with jquery in rails to update a div without reloading the page. Its working but the comment is being created twice. I know something is wrong in the form partial but couldn't figure it out. Any help?
The following are the files -
_new_comment.html.erb
<%= form_for [:home, Comment.new], :url => home_comments_path, :html => {:id => "comment-new-" + post.id.to_s} do |f| %>
<div>
<%= f.text_area :message, :class => "message-area-" + post.id.to_s, :placeholder => "Add comment..." %>
<%= f.hidden_field :post_id, :value => post.id %>
<span class="new-comment"><%= link_to 'Add', '#', remote: true, :onclick => "$('#comment-new-#{post.id}').submit()" %></span>
</div>
<% end %>
comments_controller.rb
def create
#comment = Comment.new(comment_params)
#comment.user_id = current_user.id
if #comment.save
flash[:notice] = 'Comment added sucessfully'
respond_to do |format|
format.html { redirect_to home_posts_url }
format.js
end
end
end
create.js.erb
$("#comment-new-83").before('<div class="notice"><%= escape_javascript(flash[:notice]) %></div>');
$("#comment-new-83")[0].reset();
home.js
jQuery.ajaxSetup({
'beforeSend': function(xhr) {xhr.setRequestHeader("Accept", "text/javascript")}
})
$(document).ready(function() {
$("#comment-new-83").submit(function() {
$.post($(this).attr("action"), $(this).serialize(), null, "script");
return false;
})
})
form_for will automatically post to the controller. You need not submit the form explicitly using jquery.
Reference

undefined method `item_path' while working with ajax

Im trying to update my create item action to work with Ajax but Im getting an error of undefined methoditem_path` which i wasn't getting before when it was responding in regular html format. The item is created and saved but ajax doesn't seem to work properly though.
Here is my _from partial :
<%= form_for [#user, item], remote: true do |f|%>
<div class="form-group">
<%= f.label :name, class: 'sr-only' %>
<%= f.text_field :name , class: 'form-control', placeholder: "Enter a new item " %>
</div>
<%= f.submit "Submit Item", class: 'btn btn-primary pull-right' %>
<% end %>
item#create:
def create
#item = Item.new(item_params)
#item.user = current_user
if #item.save
flash[:notice] = 'Item saved successfully.'
else
flash[:alert] = 'Item not saved. Title is too short or missing. Please try again.'
end
respond_to do |format|
format.html
format.js
end
end
create.js.erb:
$('.js-items').prepend("<%= escape_javascript(render(#item)) %>");
$('.new-item').html("<%= escape_javascript(render partial: 'items/form', locals: {user: #user , item: #item }) %>");
User#show view
<div class='new_item'>
<%= render :partial => 'items/form', :locals =>{:item => Item.new , :user => #user} %>
</div>
<div class='js-items'>
<%= render #user.items %>
</div>
routes:
user_items GET /users/:user_id/items(.:format) items#index
POST /users/:user_id/items(.:format) items#create
new_user_item GET /users/:user_id/items/new(.:format) items#new
edit_user_item GET /users/:user_id/items/:id/edit(.:format) items#edit
user_item GET /users/:user_id/items/:id(.:format) items#show
PATCH /users/:user_id/items/:id(.:format) items#update
PUT /users/:user_id/items/:id(.:format) items#update
DELETE /users/:user_id/items/:id(.:format) items#destroy
The error im getting in rails s :
ActionView::Template::Error (undefined method `item_path' for #<#<Class:0x007fa4f0d30cd8>:0x007fa4f31b26b0>):
1: <%= form_for [#user, item], remote: true do |f|%>
2: <div class="form-group">
3: <%= f.label :name, class: 'sr-only' %>
4: <%= f.text_field :name , class: 'form-control', placeholder: "Enter a new item " %>
app/views/items/_form.html.erb:1:in `_app_views_items__form_html_erb__331698480542899910_70173200751480'
app/views/items/create.js.erb:2:in `_app_views_items_create_js_erb___3618987352886002527_70173200313760'
app/controllers/items_controller.rb:17:in `create'
Do something like that.
<%= form_for [#user, item], user_items, remote: true do |f|%>
If it doesn't work then run
rake routes
in terminal see what's your path.

Passing Form object when using Ajax in rails

I have a complex form for a survey. A survey
belongs_to :template
has_many :questions, :through => :template
has_many :answers, :through => :questions
I.e. User creates a new survey, and he must select a survey template. The survey template will create some default questions and answer fields.
<%= form_for #survey do |f| %>
<p>Select a template:</p>
<%= render #templates, :locals => {:patient => #patient }, :f => f %>
<% end %>
Then I render the _templates partial, and I still have access to the form object. From here, the idea is that a user can click on a template name, and the template questions and answers will be rendered via Ajax.
<% #templates.each do |template| %>
<div class="thumbnail">
<%= link_to template.name,
{ :controller => "surveys",
:action => "new",
:template_id => template.id,
:patient_id => nil,
:f => f,
:remote=> true },
:class=> "template", :id=> template.id %>
</div>
<% end %>
surveys#new:
respond_to :js, :html
def new
#template = Template.find(params[:template_id])
#patient = Patient.find(params[:patient_id])
end
new.js.erb:
$('#assessment').append("<%= j (render new_survey_path, :locals => {:f => f} ) %>");
new_survey_path:
<%= f.fields_for :questions do |builder| %>
<% #template.questions.where(category:"S").each do |question| %>
<p><%= question.content %></p>
<%= render 'answer_fields', :question=> question %>
<% end %>
<% end %>
But I'm having trouble passing the original |f| object from #survey to new_survey_path. The last place I can access the form object is in the templates partial.
How can I fix this?

Categories

Resources