Ruby rails - text field change event and ajax - ajax

Ok.. I am running into this types of issues more often. Most of my html is ajax rendered and I use fields and values from rendered page to make new ajax requests. But none of the events seem to fire. Need to understand this why is that.
This is a simple form with text field which I want to make ajax call on a change event, to skip the form/button. And it is not working. What do I change here?
<div><%= form_tag users_search_path, :remote => true, :id => 'search_form' do %>
<%= text_field_tag :keyword, nil, :maxlength => 11, :size => 20 %># Tried this putting outside of this form, didn't work.
<%= submit_tag " Search ", :id => "search_button", :onclick => "javascript:user_search()"%>
<% end %></div>
<%= text_field_tag :keyword, nil, :maxlength => 11, :size => 20 %> Tried this putting outside of this form, didn't work.
$(function(){
$("#keyword").change(function() {
alert('ok');
$.post('/users/search', function(data) {
$("#search").html(data);
});
});
}

Because the last jquery code is a function, it's not executed until you call it. Remove the first and last line, then it will be run when the page is loaded so it will attach the function defined inside to your text box.

Related

wait for ajax request till user stops typing

I have a live search field which makes ajax call while typing. My problem is that it makes the call for every letter being typed.
Here is my code
in js file
$(document).ready(function(){
$("#employees_search input").keyup(function() {
$.get($("#employees_search").attr("action"), $("#employees_search").serialize(), null , "script");
return false;
});
});
in html file
<div align="center" id="empName">
<%= form_tag employees_path, :method => 'get', :id => "employees_search" do %>
<p>
<%= text_field :search, params[:search], placeholder: 'Search Employees Here', id: 'search_field' %>
</p>
<% end %>
</div>
in controller
#employees = Employee.where("department='Delivery'").paginate(:per_page => 6, :page => params[:page]).searchByEmp(params[:search][0]).order('name ASC')
in model
def self.searchByEmp(search)
if search
where('name LIKE ?', "#{search}%")
else
scoped
end
end
Actually I need to send ajax request only after the user stops typing the word other than for every letter typed. How can I do that?
Thanks in advance.
var liveSearchTimer;
$liveSearchInput.keyup(function() {
clearTimeout(liveSearchTimer);
liveSearchTimer = setTimeout(liveSearchDoAjax, 500);
});
The request will be sent only when there has been half a second in which no key has been pressed.

How to call an `f.action` to a custom :delete callback in an Active Admin form

In order to remove (paperclip) images from my objects, I have a custom callback (and route) defined:
ActiveAdmin.register Camping do
#...
member_action :destroy_image, :method => :delete do
camping = Camping.find(params[:id])
camping.image.destroy
redirect_to({:action => :show}, :notice => "Image deleted")
end
end
This works as expected; trough a named route destroy_image_admin_camping => /admin/campings/:id/destroy_image.
The problem is that I cannot find how to add this to the form:
ActiveAdmin.register Camping do
form do |f|
f.inputs "Camping" do
f.input :name
f.input :image
f.action :delete_image, :url => destroy_image_admin_camping_path(#camping.id), :button_html => { :method => :delete }
f.input :description
end
f.actions
end
#...
end
More detailed: I don't know how to pass the "id of the current item we are editing" into destroy_image_admin_camping_path; #camping is nil, f.camping not defined and so I don't know how to pass the item in there.
Is this the right approach? I prefer this "ajax-ish" interface over a more common checkbox-that-deletes-images-on-update, but I am not sure if this will work at all.
There's a few questions here, I'll try to address them all.
How to access the "id of the current item we are editing"
You are pretty close in looking for f.camping. What you want is f.object, so:
destroy_image_admin_camping_path(f.object.id).
NOTE: f.object.id will be nil when it's a new form (as opposed to an edit form), you'll want to check for that with unless f.object.new_record?
"Is this the right approach?"
I'm not sure, really. To me it seems like making requests without actually saving the currently rendered form could create complications, but it might turn out to be a better interface. Anyway, if you want to do the checkbox-that-deletes-images-on-update, this should help you out: Rails Paperclip how to delete attachment?.
However, if you want the ajax-ish approach I think you'll want an <a> tag styled as a button. The problem with actually using a button is that you don't want to submit the form.
Here's an example:
f.inputs do
link_to 'Delete Image', delete_image_admin_camping_path(f.object.id), class: 'button', remote: true, method: :delete
end
remote: true will make it an ajax request and ActiveAdmin gives you a pretty reasonable button class for <a> tags. Updating the interface based on success / failure is left as an exercise to the reader.
Also, you'll probably want to use erb templates for this instead of the Active Admin DSL (see http://activeadmin.info/docs/5-forms.html at the bottom).
Like this:
# app/views/admin/campings/_form.html.erb
<%= semantic_form_for [:admin, #post] do |f| %>
<%= f.inputs do %>
<%= f.input :name %>
<%= f.input :image %>
<%# Actually, you might want to check for presence of the image, I don't know Paperclip well enough to demonstrate that though %>
<% unless f.object.new_record? %>
<%= image_tag f.object.image_url %>
<%= link_to 'Delete Image', delete_image_admin_camping_path(f.object.id), class: 'button', remote: true, method: :delete %>
<% end %>
...
<% end %>
<%= f.actions %>
<% end %>

Multiple pagination with kaminari via Ajax

I want to apply multiple pagination with Kaminari via Ajax now here is my code for controller
def user_note
#user = current_user
#notes = Bookmark.where('user_id = ? && note is not NULL',current_user.id).order('created_at DESC').page(params[:page_1]).per(4)
#bookmarks = Bookmark.where('user_id = ? && note is NULL',current_user.id).order('created_at DESC').page(params[:page_2]).per(4)
respond_to do |format|
format.html
format.xml{ render :xml => #user}
end end
now for views i have two partials to render this arrays
<div id="bookmarks">
<%= render :partial =>"users/bookmark",:locals => { :bookmark => #bookmarks} %>
</div>
<%= paginate #bookmarks,:remote => true, :param_name => 'page' %>
inner partial is
<% bookmark.each do |bookmar| %>
<%= render :partial => 'show_bookmark.html.erb' , :locals => { :bookma => bookmar} %>
<%end%>
script for pagination update is being handled in a separate file
$('#bookmarks').html('<%= escape_javascript render(:partial =>"users/bookmark",:locals => { :bookmark => #bookmarks}) %>');
$('#paginator').html('<%= escape_javascript(paginate(#bookmarks, :remote => true).to_s) %>');
But by doing every thing it is not updating to state of page neither the contain in the page.
you are missing to pass params at this line
$('#paginator').html('<%= escape_javascript(paginate(#bookmarks, :remote => true).to_s) %>');
i think it should be like this
$('#paginator').html('<%= escape_javascript(paginate(#bookmarks, :remote => true, :param_name => 'page_2').to_s) %>');
and you are also passing wrong param at this line
<%= paginate #bookmarks,:remote => true, :param_name => 'page' %>
it should be like this
<%= paginate #bookmarks,:remote => true, :param_name => 'page_2' %>
and please also check that whether you are sending the response correctly to the JS file or not.
I found this question searching for paginating multiple models on the same page. It's not clear to me how the pagination for the #notes collection is intended to work, but as presented, the solutions will only paginate the #bookmarks collection via AJAX.
There will be issues if you want to maintain pagination for both collections via html OR if you change the js file to render both collections.
I implemented a solution to my similar problem like this:
An html view that renders a template with two partials: one for #notes (including its pagination helper) and another that renders #bookmarks with its pagination helper
Pagination links marked with remote: true
One js view that re-renders the two partials, something like
$('#notes_container').html('<%= j(render partial: 'paginated_notes_list') %>');
$('#bookmarks_container').html('<%= j(render partial: 'paginated_bookmarks_list'); %>');
This is the key: Pagination links that take the current page of the other model as a parameter. This way you do not "lose" which page you are on in the other model.
<%= paginate #notes, param_name: 'page_1', params: {page_2: params[:page_2]} %>
<%= paginate #bookmarks, param_name: 'page_2', params: {page_1: params[:page_1]} %>
Again, I'm not really clear on how the asker's system is supposed to function, but this solution will allow user to page through both models without losing their "place" in the other model via AJAX or html.

rails3 ajax: What is the best way of persisting local variables via ajax?

This is how my view looks (please ignore the opening and closing tags):
#obj1.leaves.each do |l|
<div id = "form">
if <some_condition>
render :partial => 'shared/view1', :locals => { :l => l }
else
render :partial => 'shared/view2', :locals => { :l => l }
end
</div>
end
And the final action on view1 causes view2 to display and vice versa thru ajax. But when view1 or view2 are rendered the local variable 'l' is not recognized anymore and throws an error causing the forms not to display (except on manual page refresh). What do I do to make the forms work and persisting my 'l'?
Thanks for your help in advance.
EDIT: My create.js.erb file for view1 (view2 i actually the destroy method so vice versa):
$("#form").replaceWith("<%= escape_javascript(render('shared/view2')).html_safe %>")
And my actual view:
<%= form_for([l, l.likes.build], :remote => true) do |f| %>
<div class="actions"><%= f.submit "Like" %></div>
<% end %>
(Not an answer.)
#obj1.leaves.each do |l|
partial = <some_condition> ? 'shared/view1' : 'shared/view2'
render :partial => partial, :locals => { :l => l }
end
Locals are just that; local. It's not clear to me what Ajax you're talking about--replaceWith just replaces content, it doesn't make a request. If it's all in the same request, you could make l an instance variable (#l) and see if that clears things up.

Rails 3 - jQuery returned from AJAX call is not being evaluated

I have a Rails 3 form with :remote => true, like this:
<%= form_for :line_item, :url => line_items_path(:product_id => product), :remote => true do |f| %>
<%= f.submit "Add to Cart" %>
<% end -%>
Then in my view file, create.js.erb, I have some jQuery code:
$('#cart').html('test')
The Net tab in Firebug shows that this code does get returned, but it doesn't do anything. As if it's not getting evaluated. I have the jquery-rails gem installed. What am I missing?
You mast rename the file to create.rjs and to write in file
page << "$('#cart').html('test')"

Resources