Updating from Rails 2 to Rails 3 with JQuery AJAX - ruby-on-rails-3

I am moving a site from Rails 2 to Rails 3 and need to replace the following deprecated methods, with JQuery:
periodically_call_remote
button_to_remote
In the view, there is a button that when pressed executes a callback every 12 seconds:
#index.html.erb (Rails 2.2.2)
<%= periodically_call_remote(:url => { :action => 'check' }, :frequency => '12', :update => 'log') %>
[...]
<div id="generate_test_btn"><%= button_to_remote "Generate Test Order",
:url => { :action => "check", :should_generate => "YES" },
:update => "log" %>
</div>
[...]
#controller
def check
[...Generate content...]
render :partial => "log" and return
end
My Partial Implementation
Not sure how to glue button_to code to the JQuery AJAX stuff
### index.html.erb (Rails 3.1)
<script>
$(document).ready(function(){
$("#generate_test_button").click(function() {
setInterval(updateTest,12000);
});
});
function updateTest(){
$("#log").load("???");
}
</script>
<%= button_to "Generate Test Order",
{ :controller => :test, :action=> :check, :should_generate => "YES" },
{ :remote => true }
%>

in rails 3 you have unobtrusive javascript
so basically, any link you create with :remote => true would call that controller#action but with a js.erb ending
so in your case the button would call the check action in the test controller
if you create a check.js.erb and place it in the views/test folder and have inside
alert("UJS!");
it should pop up once you press that button
also note that you should have the rails-ujs gem and require it in the application.js manifest

Related

How config url in Kaminari pagination? '.json' appended automatically

Load table with Kaminari pagination using AJAX.
The pagination itself is using AJAX as well.
In my controller:
def update_user_list
modal = render_to_string('tables/_user_table', :layout => false, :formats=>[:html]).html_safe
data = {
:table => modal
}
respond_to do |format|
format.json { render :json => data }
end
end
In tables/_user_table
# Table part and content notrelated
<%= paginate #users, :params => {:controller => 'product', :action => 'more_users'}, :remote => true, :theme => 'twitter-bootstrap-3' %>
The response JSON of update_user_list looks like:
{
table=" // the table part
// the pagination part shows as follows
<li class="page">3</li>
<li class="page">4
"
}
What I want is to remove ".json" in the url.
If I just render tables/_user_table without AJAX, not in a JSON object, it doesn't have ".json" in the url.
version:
rails: 3.2.17
kaminari: 0.13.0
bootstrap-kaminari-views: 0.0.3
Find the problem. It's actually not included in the question.
$.ajax({
url: '<%= user_product_index_url %>.json',
success: function(data) {
// not important......
});
remove ".json" here solve the problem...

Trying to implement an Ajax function rails 3 .load()

This is my first time trying to implement an Ajax call in rails 3, though I am using the .load function ( I still hope this is Ajax otherwise im understanding this incorrectly)
So i have a search form that returns results via a get request which renders on a different page, i would like the results to appear on the same page as the search form
<%= form_tag({:controller => 'search', :action => 'search'}, {:method => 'get'}) do |select| %>
<%= label_tag :search, "Enter Keywords Here" %>
<%= text_field_tag :search, params[:search] %>
(I have shortened the form)
<%= submit_tag "Search", :class => "searchbutton" %>
<% end %>
Jquery/Ajax call
$(document).ready(function() {
$('.searchbutton').click(function() {
$('#searchres').load('shared/searchresults');
});
});
View
<h3>Search Recipes here</h3>
<%= render 'shared/searchrecipes' %>
<div id ="searchres">
</div>
What am i doing wrong?
Due to this being an AJAX call, you need to add remote: true besides method: :get, getting an html parameter hash like this:
{:method => 'get', :remote => true}
When Rails finda remote call, it prevents the default automagically. Otherwise, you would need to modify you javascript like this:
$(document).ready(function() {
$('.searchbutton').click(function(evt) {
$('#searchres').load('shared/searchresults');
evt.preventDefault();
});
});

Rails 3.2.8 Remote Form Not Working

I have this form, which is not bound to any model, that I want to ajaxify. I've tried to figure out how to get it to submit via ajax, but I must be doing something wrong because it is not working (it just does a regular POST).
I can confirm that the form tag renders with a 'remote' attribute, but there is not js added anywhere to the form. I also added the :confirm just to see if that would work as well. It does not.
jquery and jquery_ujs are both loaded on the page.
%form{ :action => "/newsletter", :confirm => "Are you sure?", :remote => true, :method => "post", :id => "newsletterForm"}
%p
= label_tag(:q, "Subscribe to our newsletter:")
%p
= text_field_tag(:q, nil, :placeholder => "Your email address")
= button_to("Subscribe", :remote => true)
I just wrote this doing something similar with a form get:
= form_tag('/signup', :method => "get", :remote => true, :id=> 'signup-form') do
%label{:id => 'signup-label', :for=> 'signup-box'}
Enter your email address
= text_field_tag "signup-box", params[:signup], :class => 'text', :required => true, :id => 'signup-box'
= submit_tag "Sign Up", :id => 'signup'
Controller:
class SignupController < ApplicationController
def index
puts "***************************************************"
puts "email sign up"
puts "***************************************************"
render :nothing => true
end
end

Using jquery tokeninput and acts_as_taggable_on

I've implemented the framework outlined in this post: How to use jquery-Tokeninput and Acts-as-taggable-on with some difficulty. This is working insofar as prepopulating with the appropriate theme and ajax search, but when I enter a new tag, it is immediately deleted when the text area loses focus. I'm not sure what I'm doing wrong. Here's some of my relevant code:
User Model (does the tagging):
class User < ActiveRecord::Base
[...]
# tagging
acts_as_tagger
Item Model (accepts a tag):
class Item < ActiveRecord::Base
attr_accessible :title, :tag_list
#tagging functionality
acts_as_taggable_on :tags
Item Controller:
def tags
#tags = ActsAsTaggableOn::Tag.where("tags.name LIKE ?", "%#{params[:q]}%")
respond_to do |format|
format.json { render :json => #tags.collect{|t| {:id => t.name, :name => t.name }}}
end
end
On my form partial:
<%= f.input :tag_list, :label => "Tags", :input_html => { :class => "text_field short", "data-pre" => #item.tags.map(&:attributes).to_json }, :hint => "separate tags by a space" %>
my routes:
get "items/tags" => "items#tags", :as => :tags
resources :items
[almost there!!!]
the js on the form [note: the id of the element is assigned dynamically]:
<script type="text/javascript">
$(function() {
$("#item_tag_list").tokenInput("/art_items/tags", {
prePopulate: $("#item_tag_list").data("pre"),
preventDuplicates: true,
crossDomain: false,
theme: "facebook"
});
});
</script>
If you still want to use Jquery TokenInput and add tags there are different ways to do it.
1.
This is actually from my same question; the newest answer: How to use jquery-Tokeninput and Acts-as-taggable-on
This could go in your controller.
def tags
query = params[:q]
if query[-1,1] == " "
query = query.gsub(" ", "")
Tag.find_or_create_by_name(query)
end
#Do the search in memory for better performance
#tags = ActsAsTaggableOn::Tag.all
#tags = #tags.select { |v| v.name =~ /#{query}/i }
respond_to do |format|
format.json{ render :json => #tags.map(&:attributes) }
end
end
This will create the tag, whenever the space bar is hit.
You could then add this search setting in the jquery script:
noResultsText: 'No result, hit space to create a new tag',
It's a little dirty but it works for me.
2.
Check out this guy's method: https://github.com/vdepizzol/jquery-tokeninput
He made a custom entry ability:
$(function() {
$("#book_author_tokens").tokenInput("/authors.json", {
crossDomain: false,
prePopulate: $("#book_author_tokens").data("pre"),
theme: "facebook",
allowCustomEntry: true
});
});
3.
Not to sure about this one but it may help: Rails : Using jquery tokeninput (railscast #258) to create new entries
4.
This one seems legit as well: https://github.com/loopj/jquery-tokeninput/pull/219
I personally like the first one, seems easiest to get and install.

how do specfiy :with attribute in rails 3 link_to

This is link_to_remote code for rails 2.3.8
link_to_remote "Click here",
:update=>'flowtracker',
:with=>"'topcount='+$('topcount').value,
:url=>{
:controller => 'sessions',
:action => 'session_for_tracker',
:layout=>1
}
link_to_remote deprecated in rails 3
so how can i specify the :with attribute in link_to rails 3
And i'm using prototype.js
Use link_to helper with :remote => true option and do whatever you want in your js view file to your action.
EXAMPLE
in view:
<%= link_to 'ajax call', :controller => "sessions", :action => "session_for_tracker", :remote => true %>
in controller:
def session_for_tracker
#topcount = 1000; #get actual value here
respond_to do |format|
format.js
end
end
in js view for action:
page << %|
$('flowtracker').update("#{#topcount}");
|