Ajax : data retrieving in rails3 + formtastic - ajax

I have successfully tried ajax saving in my sample formtastic with ajax form.
The new value is added to the database. But the the problem is in retrieving the list from the database as soon as i save via ajax.
How to do it.?
As soon as I add a new record I want my displaying list to be update. Both the option to add new record and list the data from database is in same page
This is my Index page. The controller and all other created via scaffolding
<h1>Listing samples</h1>
<table>
<tr>
<th><%=t :Name%></th>
<th></th>
<th></th>
<th></th>
</tr>
<% #samples.each do |sample| %>
<tr>
<td><%= sample.name %></td>
<td><%= link_to 'Show', sample %></td>
<td><%= link_to 'Edit', edit_sample_path(sample) %></td>
<td><%= link_to 'Destroy', sample, :method => :delete, :data => { :confirm => 'Are you sure?' } %></td>
</tr>
<% end %>
</table>
<br />
<%= link_to 'New Sample', new_sample_path %>
<br /><br /><br /><br /><br />
<%= semantic_form_for #sample1,:url => samples_path, :remote => true do |f| %>
<%= f.inputs do %>
<%= f.input :name %>
<% end %>
<%= f.actions do %>
<%= f.action :submit, :as => :input %>
<% end %>
<% end %>

When you save via ajax, you may have to change the way your controller responds, kinda like this:
def create
# stuff
respond_to do |format|
format.js
end
end
When you do this, rails would expect you to have created a file named create.js.erb, in which you can manipulate the data of your view(append new content to your table, render a whole new partial with your new object list, etc):
$('#your_list').html(
"<%= escape_javascript(render('your_table_partial')) %>"
);
Or
$('#your_list').append(
"<%= escape_javascript(render('your_item_of_the_table_partial')) %>"
);
These are just examples, i don't know your code enough to write the correct code for you, but you sure can use these as a base for your work.

I did the CRUD operation using these guidelines and it worked perfect
http://stjhimy.com/posts/07-creating-a-100-ajax-crud-using-rails-3-and-unobtrusive-javascript

Related

Is there any way to include simple form fields after a request?

I'm using simple_form when the page loads the form is created, but I need and additional operation, I have to load a partial with multiple checkboxes, these correspond to data from a database, and the partial is rendered after the user click a button.
To do this I'm using js.erb with escape javascript, to render the partial. I already tried load with simple form directly, but I realize it didn't work as I expected.
$('.table-responsive.'+<%=#category_id%>).
html(
"<%= escape_javascript(render partial: 'backend/research_participants/research_participants',
locals: {companies: companies, category_id: category_id } ) %>"
)
<% for company in #companies %>
<tr>
<td>
<%= check_box_tag "#{category_id}company#{company.id}",
company.id,
checked = false,
class: "companies_check_#{category_id}" %>
</td>
<td><%= company.trade_name %></td>
<td><%= company.cnpj %></td>
<td><%= company.contact&.email %></td>
</tr>
<% end %>

approve multiple records at once

how to achieve this Scenario:
admin to select multiple records using a checkbox and click a button to approve selected, which will change the status of the selected items to approved at once. records are like posts.
here is my code:
config/routes:
resources :time_cards do
collection do
get 'management'
put 'approve_multiple'
end
member do
get 'review'
get 'tracking'
patch 'approve_or_reject'
end
end
html:
<%= form_tag({controller: 'time_cards', action: 'approve_multiple'}, method: 'put', id: 'approve_multiple_time_card_form') do %>
<% #time_cards.each do |time_card| %>
<tr>
<% if time_card.status.downcase == 'submitted' %>
<td><%= check_box_tag "time_cards_to_approve[]", time_card.id %></td>
<% else %>
<td> </td>
<% end %>
<td><%= time_card.id %></td>
<td><%= time_card.week_of.to_date.strftime('%B %-d, %Y') %></td>
<td><%= time_card.user.name %></td>
<td><%= time_card.status %></td>
<td><%= output_hours(time_card.time_card_entries) %></td>
<td>
<%= link_to review_time_card_path(time_card) do %>
<% if time_card.status.downcase == 'submitted' %>
<i class="material-icons">edit</i>
<% end %>
<% end %>
</td>
</tr>
<% end %>
<%= submit_tag "Approve Selected", class: 'btn btn-success' %>
<% end %>
controller:
#PUT /time_cards/approve_multiple
def approve_multiple
authorize TimeCard
#time_cards.update_all({status: 'Approved'}, {id: params[:time_cards_to_approve]})
respond_to do |format|
if !#time_cards.errors
format.json { render json: { notice: 'Time cards approved successfully.'} }
format.html { redirect_to redirect_to management_time_cards_path, notice: 'Time cards approved successfully.'}
else
format.json { render json: { error: #time_cards.errors, alert: 'There was a problem approving the time card.'}}
format.html { redirect_to management_time_cards_path, alert: #time_cards.errors}
end
end
end
??? I don't no where it is wrong?
Send these ids to an action like this
Post.where(id: params[:ids]).update_all(approved: true)
params[:ids] is an array of posts' ids
update_all returns the number of the updated records
Ops, I took for granted we were talking about rails but it's never mentioned.

Value is not submitting in using Rails ajax form

I want to store value in db using Rails ajax form but it is not storing anything.Please let me to know where i did the mistake and help me to resolve this issue.
I am explaining my code below.
users/index.html.ebr:
<script type="text/javascript">
$('form').submit(function() {
var valuesToSubmit = $(this).serialize();
console.log('hello')
$.ajax({
type: "POST",
url: $(this).attr('create'), //sumbits it to the given url of the form
data: valuesToSubmit,
dataType: "JSON" // you want a difference between normal and ajax-calls, and json is standard
}).success(function(json){
console.log("success", json);
});
return false; // prevents normal behaviour
});
</script>
<p><%= flash[:notice] %></p>
<%= form_for :user do |f| %>
<p>
Name : <%= f.text_field :name,placeholder:"Enter your name" %>
</p>
<p>
Email : <%= f.email_field :email,placeholder:"Enter your email" %>
</p>
<p>
Content : <%= f.text_field :content,placeholder:"Enter your content" %>
</p>
<p>
<%= f.text_field :submit,:onchange => "this.form.submit();" %>
</p>
<% end %>
<div id="sdf-puri" style="display:none" >
</div>
controller/users_controller.rb
class UsersController < ApplicationController
def index
#user=User.new
respond_to do |format|
format.html
format.js
end
end
def create
#user=User.new(params[:user])
if #user.save
flash[:notice]="user created"
end
end
end
create.js.erb
$("#sdf-puri").css("display", "block");
$("#sdf-puri").html("<%= escape_javascript (render 'table' ) %>");
$("#sdf-puri").slideDown(350);
create.html.erb
<%= render 'table' %>
_table.html.erb
<table>
<tr>
<th>Name :</th>
<th>Email :</th>
<th>Content :</th>
</tr>
<% #user.each do |user| %>
<tr>
<td><%= user.name %></td>
<td><%= user.email %></td>
<td><%= user.content %></td>
</tr>
<% end %>
</table>
After submit value should display in same index page.Please help me.
Rails has a built in Ajax system, on your form you need to add remote: true
form_for(#user, remote: true) do |f|
This tells rails to submit the form using Ajax under the hood... You don't need all of the script above the form
Your controller already correctly has the line:
responds_to js
So all you would do is have a create.js file in your views/user folder that handled your return Ajax stuff such as appending or fading etc
you need to add remote: true in form tag

XML Parsing Error: no element found when using rjs in rails

I implemented destroy functionality using rjs template in rails. i got an error "XML Parsing Error: no element found" when destroy one record from database. is this right my coding?
I used the following versions ruby and rails:
Ruby version: 1.8.7
Rails Version: 2.3.8
Controller file:
def destroy
begin
#task = Task.find(params[:id])
#task.destroy
respond_to do |format|
#format.html { redirect_to(tasks_url) }
format.js
format.xml { head :ok }
end
rescue Exception => e
puts e
end
end
partial template file _task.html.erb:
<tr id="<%= dom_id(task) %>">
<td><%= task.name %></td>
<td><%= task.note %></td>
<td><%= task.priority %></td>
<td><%= link_to 'Show', task %></td>
<td><%= link_to 'Edit', edit_task_path(task) %></td>
<td>
<%= link_to 'Destroy', task, :confirm => 'Are you sure?', :method =>:delete,:remote => :true %>
index.rhtml file:
<div id='newform'>
<% form_for([#task, Task.new]) do |f| %>
<div>
<%= f.label 'Add a new task: ' %>
<%= f.text_field :name %>
</div>
<div>
<%= f.submit %>
</div>
<% end %>
</div>
<table id="alltasks">
<tr id="tablehead">
<th>Name</th>
<th>Note</th>
<th>Priority</th>
<th></th>
<th></th>
<th></th>
</tr>
<%= render #tasks %>
<!-- expanded: render :partial => "task", :collection => #tasks -->
</table>
<br />
<%= link_to 'New Task', new_task_path %>
destroy.js.rjs file:
page.alert('Hi')
The problem is that the xml format is getting requested from your destroy action, not the js format, and something is trying to parse the empty xml response produced by the format.xml { head :ok } line in the controller. It used to be that you could get away with the empty xml response, but it also looks like you're using unobtrusive javascript, and something somewhere in ujs tries to parse it.
One potential solution is to make a destroy.xml.builder view that produces a simple response, and change your controller action to read format.xml { render :layout => false } or something similar. You can also do some fun things with changing the data type your link is requesting, but I'd recommend avoiding that unless you really want to do something with your js response in destroy.js.rjs.

Rails form_tag needs refreshing

Hi I have been stuck on the following issue for days, and I just dont know whats going wrong...
I have the following form_tag code in my partial view, which is displayed with a remote add to cart from a main view:
<tr>
<% form_tag line_item, :method => :put do %>
<td><%= line_item.product.title %></td>
<td class="item_price" ><%= number_to_currency(line_item.total_price) %></td>
<td>
<%= text_field :line_item, :quantity, :size => 1, :value => line_item.quantity %>
<%= submit_tag 'update' %>
</td>
<% end %>
<td>
<%= button_to 'Delete Line Item', line_item, :method => :delete, :remote => true %>
</td>
</tr>
now when i click add to cart, the above is rendered in the id where I have the replace.html function targeted but...
i can't actually update the cart using the update button unless I refresh the page!! I have no idea what the matter is and its driving me mad!
Has anyone got any ideas what I may be doing wrong?
I think form_tag needs :remote => true also.

Resources