it seems funny, but I would start doing a search (with rails 3.0) and thought - "I'll take a look at Ryan's website." you're always one step ahead. When I grow up I want to be like you =D
VERY useful, once agin. The only thing I found "unnecessary" was to the carry the input field. If you're gonna do it in AJAX, this field isn't gonna be impacted by the "submit". That is, however, a good tip for when you're *not* doing it over Ajax.
@JohnDel: RJS was yesterday. Nowadays we do unobstrusive JS. Have you ever tried to debug a RJS produced JS? :) I did, and then I started learning JS.
like your railscasts, but I always have problems with the playback of the video files. Neither vlc/windows nor vlc/linux can play back the files without scrambling half of it.
Encoding issues? Any advice?
@Mark - Ryan has said before it is a problem in Quicktime and that he's hoping Apple will fix. If you momentarily pause playback in VLC, the video will catch up with the audio immediately. It only happens when he doesn't type or move the mouse but the screen changes.
@Everyone - I just reported UggOutletTug to Google - that's where they have their email and maybe hosting. Please help stop the spam and do the same with other spammers.
I'm using searchlogic for all search and also for sorting the results. It has simple helper 'order' that you can use for printing the link as column name and then use for sorting the columns.
Note to DataMapper users - will_paginate 3.0.pre2 will cause duplicate queries, affectively killing your rails app. I am not 100% sure if the issue is a dm-core or will_paginate but thought I would give a heads up.
Since I'm now facing a Rails3 upgrade on a large codebase with inadequate tests, I would offer the suggestion that you might consider using TDD for your screencasts. I have no idea how one might approach testing this.
@JohnDel: The other issue with RJS (at least when I looked a couple weeks ago) is that it's still hardcoded to use Prototype underneath. So while the rest of Rails is moving towards being agnostic, the Javascript generator helper methods are not...
To people having video troubles, I was having trouble viewing this one inside Chrome on my mac. I right-clicked (command-clicked) and downloaded it, then ran it externally in QuickTime Player, and it played fine.
Cool post. One comment though. Maybe it would be better to use e.preventDefault() instead of merely return false in jquery events, it's more cleaner: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/ .
I think you just blew my mind. Once again Ryan, you make the complex simple and make Rails seem even more like magic. Sure it is, but you make it feel like it is.
@mrbrdo: the .click() call will only work on the first display of the HTML. When those links are replaced via Ajax, the click monitoring will not be active anymore. The .live() call works even if the HTML containing the link is replaced via Ajax.
Ajax'ifying Rails applications is becoming more and more of a requirement. I have come across this gem/plugin that unobtrusively reconfigures a standard rails view set up to work seamlessly as a single html page Ajax updated, history enabled and crawlable application...
Have you had a go with that yet? I am planning on trying it out, but it would be really interesting to get your view on it!
https://github.com/kjvarga/ajax
After going through this awesome railscasts I realized that I wasn't sure how to make record deletions work well with this system.
For me, when I delete a record, I am redirected to the index, and not even on the same page of results I was on. This is totally jarring. I was thinking I could pass in the page param (and other params like sortable uses) to make the destroy links able to take us to the right page of results.
But if I wanted to do this with ajax, how could that be done? In the best case I was thinking you might delete the record locally with a fade out and then load one record at the bottom of the page of results you're on (this record would be from the next page - if you don't load it that one record won't show if you click to go to the next page).
The fade out is a nice visual touch. But another acceptable way to do this would be to just replace the products div with a new version of the current page of results you're on. This would handle loading that new record from the next page. What's the best way to implement this?
when we use "rails g scaffold products ...",the generated file products_controller.rb will crash the ajax.
to fix it ,we need to remove the follow code:
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @products }
end
I was trying to make this work with Metasearch and Simple_Form, but I couldn't get the Search Box to work with AJAX. It doesn't seem like it is even noticing that I am typing anything. Would love some pointers.
Just one remark - you can easily get rid of the last piece of JavaScript code (which I found very ugly). Read on my http://apohllo.pl/blog/rails-3-and-ujs-with-jquery.
I have a strange behavior with the WHERE statement you use in your search method. It works fine on development using sqlite. But I am using Heroku for production, and "Foo" does not match anything when"Foo" is in the table, while "oo" does match "Foo" . Any idea ?
I'm a little late to the party... but I just watched the video, got it working in development, and then ran into the same issue. Did you ever find a solution?
What would I do without Railscasts? Waste a bunch of time I suppose. Thanks again Ryan!! You do a great job of demonstrating how to program functionality that everyone needs.
It's 2:41am in Brazil right now, it's raining cats and dogs outside, and I've got a project to deliver tomorrow. You just saved me. Thank you a lot, keep up the good work and may God bless you with more knowledge.
Hi, I am using Mongoid as database, does anyone know if it is safe to use regular expression matching for a string field in that self.search method for individual users?
like current_user.projects.where(:name => /#{params[:search]}/i)
As html-<form>s may not be cascaded (e.g. you cannot put a <form> within a < form>) and I am using button_to for my destroy actions which generates forms I had to work around the input fields not being inside the table as I would have form in form then. this is my solution:
https://gist.github.com/754999
e.g. I just do two updates / insert two partials using jQuery
For getting rid of this 'certificate verify failed (OpenSSL::SSL::SSLError)' when using jquery-rails gem please you need to install a certificate and point to it in your open_uri.rb file. Please read more about it at http://bit.ly/fHXtHn
I'm trying to do this in a Sinatra app (made some adjustments) but something's not working.
The first time I click the link in question the whole page is loaded (ie not just the partial) on subsequent clicks (in the new nested page) it works as expected.
I'm not sure if it's changed since this 'cast came out but I had to do several more steps or the AJAX doesn't work:
Most importantly the jquery-rails install doesn't do all it needs to so you have to add "jquery rails" to your javascript_expansions[:default] yourself. i.e. in your config/application.rb file make sure you have:
config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
Next you need to add ", :remote => true" to the end of the form_tag line in your partial file:
<%= form_tag products_path, :method => 'get', :id => "products_search", :remote => true do %>
Hopefully that helps anyone having problems following your mostly excellent tutorial.
Hi everyone! i made everything as the episode said, but the AJAX its not working. I removed the respond_to block, doesnt worked, also i added the format.js line that Jamil said, but also didnt worked.
Also added the two lines of Mike Bethany, and nothing... Please someone that could help me. Thanks!
Ok... I think I found a fix for rails 3.1. The trick is to keep from using assets. You need the page to be rendered. This may seem hack-ish... I agree... but it does work. This can probably be better refined in the future.
What you need to do, is add an entry in the routes file before the "resources" for products like so:
and proceed as normal. What this does in essence is get Rails to skip using the brand-new asset manager system... and go back to the old-fashioned rendering setup. This is probably a good thing as the index.js is rendered per-request and won't be concat'd together with the other javascript and not minified.
Instead of just using name to search on, you can modify your model to include the field you wish to search on.
model
def self.search(search,type)
if search
case type
when "firstname"
where('firstname LIKE ?', "%#{search}%")
when "lastname"
where('lastname LIKE ?', "%#{search}%")
when "email"
where('email LIKE ?', "%#{search}%")
end
else
scoped
end
end
It works for me. thanks.
Do you know how to write where clause that search in User model for full user name from firstname and lastname attributes. Also you can type only firstname and get result.
You can also create a default one for any field. This will search for any value in any column.
Any Clause
when "allfields"
where('firstname LIKE ? OR lastname LIKE ? OR email LIKE ? OR manager LIKE ? OR address1 LIKE ? OR address2 LIKE ? OR city LIKE ? OR state LIKE ? OR zipcode LIKE ? ', "%#{search}%","%#{search}%", "%#{search}%","%#{search}%", "%#{search}%","%#{search}%", "%#{search}%","%#{search}%", "%#{search}%")
If you want to add a delay to the search to avoid overloading the db, an easy way to do it is by using the jquery.observe_field.js plugin and changing the search script to:
Nice tutorial, thank you very much Ryan.
Can you explain more clearly about sorting with Ajax, please? When user click header column (e.g: description), the js code in application.js is called. Then params[:sort] and params[:direction] are sent to controller. After variable @products is set, the js code in index.js.erb is executed, then product table is rendered. Do I think right, or not? If right, I don't understand why: when js code in application.js is called, the js code in index.js.erb is not executed immediately.
If I'm wrong, please explain for me about process flow when user click header column.
And one thing, what different between using ajax getScript and using :remote => true? If I want to use :remote for sorting, what things I need to change?
Thank you very much
I have a problem with will_paginate and sortable links. Since they are relative link, once I've update my partial after an edit or delete action the link includes the item ID like http://url/id?page=2 instead of http://url?page=2.
ps: this applied on 25/02/2013, rails 3.2
pps: this can also be done with coffeescript , in the relevant file! (products.js.coffee in the example given)
The javascript to handle the pagination link clicks sends the ajax for even the pagination links that are disabled. Even though their href is "#". Is there a way to filter out the live() call to not include the items in the pagination links which have a class of 'disabled' or 'active'?
Everything works great but I have one bug and can not understand why it doesnt work. My search script (which works on submit) works only on 2nd submission. First submit reloads the page and second submit sends AJAX request. After that if submit again -> reload, submit again -> ajax. (one after another)
Why it happens?
My application JS:
$(function () {
// Search form.
I am having this same issue. For some reason my submission only goes through the AJAX path for the first submit, after that it refreshes the page through the url. I would also really appreciate any thoughts on this
$(document).on('submit', '#identities_search', function () {
$.get(this.action, $(this).serialize(), null, 'script');
returnfalse;
It is really annoying because it doesn't throw any kind of error, the only reason I got it working is from having to get the sort working out before. Hope this helps someone.
We can even easily change the JavaScript to make the search ‘live’ so that the results automatically update with each keypress. Note that this is only a quick demo and isn’t the best way to do this. There are several jQuery plugins that you can use if you do something like this in a production app. To do this we’ll replace the JavaScript that we used to submit the form through AJAX with this.
Can someone explain why this isn't the best way to do this? And what jQuery plugins to look at?
I've added the jquery.observe_field.js plugin to add a delay but my search/sort is laggy on my production server.
Excellent Railscast. But for those who don't want to keep querying server, you can use DataTables and do sorting and searching on the client side. Example here: http://jsfiddle.net/GJYfe/1/
I guess the ↵ that has snuck into some of the ASCIICast is just a line break/continuation indicator? You can dump the entity and rejoin the lines.
One issue I am having at the moment is that when i search i get the new results fine but the new paginated links do not go anywhere, they just fire a get request
Richard,
I was having a similar issue. See Mizpah's solution above.
"We also need change how the line is written to include the nodes to stay bound to:
$(document).on("click","#game_classes th a, #game_classes .pagination a", function() {* would replace the line used in the original:
I also believe we now need the lines in application.js that load other documents (// = require somthing).
On rails 5 I couldn't get the code working correctly with the information presented by Luke Schoen. However, I got it working with the following code based on Rayn's code with the following adjustments:
app/models/product.rb: I used self.where for both cases and replaced "scoped" with "self.where(nil)".
app/helpers/application_helper.rb: I used request.query_parameters.merge to get the code working. (Also be aware of the double brackets) So: link_to title, request.query_parameters.merge({ sort: column_name, direction: direction, page: nil })
it seems funny, but I would start doing a search (with rails 3.0) and thought - "I'll take a look at Ryan's website." you're always one step ahead. When I grow up I want to be like you =D
Nice tutorial and nice getScript way of converting a link to ajax.
But why you chose ajax calls with jquery instead of rjs and remote? Are there any benefits?
VERY useful, once agin. The only thing I found "unnecessary" was to the carry the input field. If you're gonna do it in AJAX, this field isn't gonna be impacted by the "submit". That is, however, a good tip for when you're *not* doing it over Ajax.
@JohnDel: RJS was yesterday. Nowadays we do unobstrusive JS. Have you ever tried to debug a RJS produced JS? :) I did, and then I started learning JS.
MetaWhere is also a good alternative for Simple Search Form.
MetaWhere+MetaSearch is also a good alternative for Simple Search Form.
To save the server some work, you can do searching without ajax. Just do a simple jQuery search in the already loaded list.
Then you do not send a sql query everytime you have a keyup.
This works great on smaller lists
Hi Ryan,
like your railscasts, but I always have problems with the playback of the video files. Neither vlc/windows nor vlc/linux can play back the files without scrambling half of it.
Encoding issues? Any advice?
Anyway, thanks for great rails resource!
@Mark - Ryan has said before it is a problem in Quicktime and that he's hoping Apple will fix. If you momentarily pause playback in VLC, the video will catch up with the audio immediately. It only happens when he doesn't type or move the mouse but the screen changes.
@Everyone - I just reported UggOutletTug to Google - that's where they have their email and maybe hosting. Please help stop the spam and do the same with other spammers.
I'm using searchlogic for all search and also for sorting the results. It has simple helper 'order' that you can use for printing the link as column name and then use for sorting the columns.
Note to DataMapper users - will_paginate 3.0.pre2 will cause duplicate queries, affectively killing your rails app. I am not 100% sure if the issue is a dm-core or will_paginate but thought I would give a heads up.
Ryan you are truly a Magister Ludi, thank you.
Since I'm now facing a Rails3 upgrade on a large codebase with inadequate tests, I would offer the suggestion that you might consider using TDD for your screencasts. I have no idea how one might approach testing this.
@JohnDel: The other issue with RJS (at least when I looked a couple weeks ago) is that it's still hardcoded to use Prototype underneath. So while the rest of Rails is moving towards being agnostic, the Javascript generator helper methods are not...
@JohnDel: as Phillip state, RJS uses Prototype. But all the cool kids are using jQuery nowadays.
To people having video troubles, I was having trouble viewing this one inside Chrome on my mac. I right-clicked (command-clicked) and downloaded it, then ran it externally in QuickTime Player, and it played fine.
Great screencast, Ryan.
This technique is awesome. Can be used on other languages too.
Ryan,
Cool post. One comment though. Maybe it would be better to use e.preventDefault() instead of merely return false in jquery events, it's more cleaner: http://fuelyourcoding.com/jquery-events-stop-misusing-return-false/ .
Wow, i just wanted to see smtg about search+ajax and here it is!
Ryan great job!
I think you just blew my mind. Once again Ryan, you make the complex simple and make Rails seem even more like magic. Sure it is, but you make it feel like it is.
ps: getScript == "genius"
I didn't quite understand why you used .live() instead of .click()? Can you (or someone) explain more in depth?
Just a question... why did you put the partial in the form and the two hidden fields in the partial instead of updating hidden values in index.js?
@mrbrdo: the .click() call will only work on the first display of the HTML. When those links are replaced via Ajax, the click monitoring will not be active anymore. The .live() call works even if the HTML containing the link is replaced via Ajax.
For any new users reading this post, the .live() method was removed on JQuery 1.9, you can use the on() method instead.
Ajax'ifying Rails applications is becoming more and more of a requirement. I have come across this gem/plugin that unobtrusively reconfigures a standard rails view set up to work seamlessly as a single html page Ajax updated, history enabled and crawlable application...
Have you had a go with that yet? I am planning on trying it out, but it would be really interesting to get your view on it!
https://github.com/kjvarga/ajax
Ryan!!! you are the best! I love your work!!! You are my role model! i would like to be you when i grow up! Awesome work! :)
After going through this awesome railscasts I realized that I wasn't sure how to make record deletions work well with this system.
For me, when I delete a record, I am redirected to the index, and not even on the same page of results I was on. This is totally jarring. I was thinking I could pass in the page param (and other params like sortable uses) to make the destroy links able to take us to the right page of results.
But if I wanted to do this with ajax, how could that be done? In the best case I was thinking you might delete the record locally with a fade out and then load one record at the bottom of the page of results you're on (this record would be from the next page - if you don't load it that one record won't show if you click to go to the next page).
The fade out is a nice visual touch. But another acceptable way to do this would be to just replace the products div with a new version of the current page of results you're on. This would handle loading that new record from the next page. What's the best way to implement this?
Thanks for the amazing railscast!
when we use "rails g scaffold products ...",the generated file products_controller.rb will crash the ajax.
to fix it ,we need to remove the follow code:
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @products }
end
Aah, yes of course! Thanks for sharing. I was wondering why it didn't work.
Thanks so much, this just saved me after hours of struggling!
I was trying to make this work with Metasearch and Simple_Form, but I couldn't get the Search Box to work with AJAX. It doesn't seem like it is even noticing that I am typing anything. Would love some pointers.
Just one remark - you can easily get rid of the last piece of JavaScript code (which I found very ugly). Read on my http://apohllo.pl/blog/rails-3-and-ujs-with-jquery.
I have a strange behavior with the WHERE statement you use in your search method. It works fine on development using sqlite. But I am using Heroku for production, and "Foo" does not match anything when"Foo" is in the table, while "oo" does match "Foo" . Any idea ?
I'm a little late to the party... but I just watched the video, got it working in development, and then ran into the same issue. Did you ever find a solution?
What would I do without Railscasts? Waste a bunch of time I suppose. Thanks again Ryan!! You do a great job of demonstrating how to program functionality that everyone needs.
to 58. zhubo : your comment is very important! It helps me fix my problem. Thanks a lot!
It's 2:41am in Brazil right now, it's raining cats and dogs outside, and I've got a project to deliver tomorrow. You just saved me. Thank you a lot, keep up the good work and may God bless you with more knowledge.
Hi, I am using Mongoid as database, does anyone know if it is safe to use regular expression matching for a string field in that self.search method for individual users?
like current_user.projects.where(:name => /#{params[:search]}/i)
Thank you
To 43. zhubo:
You don't have to remove the respond_to block.
Just add another responder in there to respond to javascript like so:
respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @products }
format.js # index.js.erb
end
Thanks Jamil - that fixed my problem
and me
I just wanted to say...
... i love you :)
thank you SOO much :)
p.s. please add some episode based on this one that adds jquery-bbq - I can'T make it work for hours!
As html-<form>s may not be cascaded (e.g. you cannot put a <form> within a < form>) and I am using button_to for my destroy actions which generates forms I had to work around the input fields not being inside the table as I would have form in form then. this is my solution:
https://gist.github.com/754999
e.g. I just do two updates / insert two partials using jQuery
Nice One
A newbie question here
How can I do the ajax part for my rails 2.3.8
For getting rid of this 'certificate verify failed (OpenSSL::SSL::SSLError)' when using jquery-rails gem please you need to install a certificate and point to it in your open_uri.rb file. Please read more about it at http://bit.ly/fHXtHn
I'm trying to do this in a Sinatra app (made some adjustments) but something's not working.
The first time I click the link in question the whole page is loaded (ie not just the partial) on subsequent clicks (in the new nested page) it works as expected.
Any clues on how to solve this?
Thanks in advance!
I'm not sure if it's changed since this 'cast came out but I had to do several more steps or the AJAX doesn't work:
Most importantly the jquery-rails install doesn't do all it needs to so you have to add "jquery rails" to your javascript_expansions[:default] yourself. i.e. in your config/application.rb file make sure you have:
config.action_view.javascript_expansions[:defaults] = %w(jquery rails)
Next you need to add ", :remote => true" to the end of the form_tag line in your partial file:
<%= form_tag products_path, :method => 'get', :id => "products_search", :remote => true do %>
Hopefully that helps anyone having problems following your mostly excellent tutorial.
Kaminari ajax pager, details in gist:
https://gist.github.com/876500
No extra application.js hooks needed.
it works great but with a simple and small search what if we have an Array as returned on our search method
If I don't want to use AJAX, how can I remove the "utf=?" from the url? That's so annoying.
Thanks.
Hi everyone! i made everything as the episode said, but the AJAX its not working. I removed the respond_to block, doesnt worked, also i added the format.js line that Jamil said, but also didnt worked.
Also added the two lines of Mike Bethany, and nothing... Please someone that could help me. Thanks!
Hi ! Really nice tutorial. Everything work without AJAX :( It
s mean keyup :( I
don`t now why.I thought the controller had to have a respond_to block to do the ajax or will it just default to to index.js.erb in this case?
It's great for rails 3.0. But how it works with rails 3.1 without js.views, just with coffeescript... ?
I'm also having trouble getting AJAX functioning in a Rails 3.1 environment. See my question on stackoverflow here.
Can you help me please?
I have this error:
undefined method render for #<#<Class:0x9e54e54>:0xa860f24>
(in /var/www/final/evidencia02/evidencia/app/assets/javascripts/application.js.erb)
My application.js.erb:
In index.html.erb render 'zoznam' is OK. "zoznam/index" is list of my products with custom sql select.
@quatermain ... I ran into the same thing. Apparently, "render" is not available to assets in rails 3.1. I'm still poking around for a solution...
Our problem here too: Stack overflow
So, is there another solution for ajax(search, sort, paginate)??
Ok... I think I found a fix for rails 3.1. The trick is to keep from using assets. You need the page to be rendered. This may seem hack-ish... I agree... but it does work. This can probably be better refined in the future.
What you need to do, is add an entry in the routes file before the "resources" for products like so:
and proceed as normal. What this does in essence is get Rails to skip using the brand-new asset manager system... and go back to the old-fashioned rendering setup. This is probably a good thing as the index.js is rendered per-request and won't be concat'd together with the other javascript and not minified.
Did it work for you? For me it doesn't and it also broke the sort
Did it work for you? For me it doesn't and it also broke the sort
This is a fantastic tutorial on writing degradable ajax.
Instead of just using name to search on, you can modify your model to include the field you wish to search on.
<%= select_tag "fieldtype", options_for_select([ "firstname", "lastname", "email" ], "firstname") %>
+1 thanks for this. :)
It works for me. thanks.
Do you know how to write where clause that search in User model for full user name from firstname and lastname attributes. Also you can type only firstname and get result.
You can also create a default one for any field. This will search for any value in any column.
Nice Tutorial! I just want to post here a fix I discovered. Sorry if this would be a repost:
In your tutorial:
$('#products').html('<%= escape_javascript(render("products")) %>');
But in Rails 3.1, you have to explicitly define it as a partial:
$('#products').html('<%= escape_javascript(render :partial => "products" %>');
I hope this helps anyone who had the same issue. :)
Thanks for this very nice and clean tutorial.
If you want to add a delay to the search to avoid overloading the db, an easy way to do it is by using the jquery.observe_field.js plugin and changing the search script to:
In case anyone wants the coffeescript. Note that I kept the
.submit
bit in addition to.keyup
in case the user hits submit.I must say thanks, 2 years later.
Nice tutorial, thank you very much Ryan.
Can you explain more clearly about sorting with Ajax, please? When user click header column (e.g: description), the js code in application.js is called. Then params[:sort] and params[:direction] are sent to controller. After variable @products is set, the js code in index.js.erb is executed, then product table is rendered. Do I think right, or not? If right, I don't understand why: when js code in application.js is called, the js code in index.js.erb is not executed immediately.
If I'm wrong, please explain for me about process flow when user click header column.
And one thing, what different between using ajax getScript and using :remote => true? If I want to use :remote for sorting, what things I need to change?
Thank you very much
Hi guys, i've ran into this problem.
ActionView::MissingTemplate in Notes#index
Which fails at: <%= render 'notes' %>
Should i be adding anythign else to my controller?
def index
end
I have a problem with will_paginate and sortable links. Since they are relative link, once I've update my partial after an edit or delete action the link includes the item ID like http://url/id?page=2 instead of http://url?page=2.
Can somebody help me solve it?
There seems to be a syntax error in the ASCIIcast for the ajax search jQuery. Bardwin's coffee-script worked for me however.
Anyone know how to nicely fadeIn the results? Thnx!
Never mind I figured it out :)
Change:
$("#products").html("<%= escape_javascript(render("products")) %>");
To:
$("#products").hide();
$("#products").html("<%= escape_javascript(render("products")) %>").fadeIn(500);
Im using rails 3.2 and the ajax doesn't work for me
i got this error Uncaught SyntaxError: Unexpected identifier
in
$.get($('#playlists_search').attr('action'), ↵
$('#playlists_search').serialize(), null, 'script');
return false;
The different parameters and the jQuery don't seem to work together for me. Do you guys have any idea why this happens?
http://stackoverflow.com/questions/14569721/rails-parameters-get-lost-because-of-jquery-link
By the way: since jQuery 1.9 it is ".on("click", function()" instead of ".live("click", function()".
Firstly am new to this so if anything is wrong, apologies and please correct it!
If you use application.js as is written in the example, no ajax will happen... (it would of worked when it was first written).
This is due to the 'live' event being replced with 'on' in the current version of jquery.
However live, used to stay bound to all future nodes. 'on' by default does not.
Thus if you just change 'live' to 'on' it will work once (for one click per page), and then fallback to non ajax.
We also need change how the line is written to include the nodes to stay bound to:
I also believe we now need the lines in application.js that load other documents (// = require somthing).
Thus my complete application.js looks like this:
ruby...
//= require jquery
//= require jquery_ujs
//= require_tree .
$(function() {
$(document).on("click","#game_classes th a, #game_classes .pagination a", function() {
$.getScript(this.href);
return false;
});
$("#game_classes_search input").keyup(function() {
$.get($("#game_classes_search").attr("action"), $("#game_classes_search").serialize(), null, "script");
return false;
});
});
...
Hopefully this helps someone!
ps: this applied on 25/02/2013, rails 3.2
pps: this can also be done with coffeescript , in the relevant file! (products.js.coffee in the example given)
I've used this code to try to get my search working using keyup. And I get an error in the console Uncaught SyntaxError: Unexpected token }
I literally cut/paste the code and changed the id name to patient_search.
Am I doing something wrong?
Thanks for the $(document).on("click","#game_classes th a, #game_classes .pagination a", function() line Mizpah :)
The javascript to handle the pagination link clicks sends the ajax for even the pagination links that are disabled. Even though their href is "#". Is there a way to filter out the live() call to not include the items in the pagination links which have a class of 'disabled' or 'active'?
Ok, the jQuery selector in the javascript to prevent ajax from sending a request to the server for the pagination links which have an href='#' is...
This prevents attaching a click event to pagination links where href='#'.
Everything works great but I have one bug and can not understand why it doesnt work. My search script (which works on submit) works only on 2nd submission. First submit reloads the page and second submit sends AJAX request. After that if submit again -> reload, submit again -> ajax. (one after another)
Why it happens?
My application JS:
$(function () {
// Search form.
$('#identities_search').submit(function () {
$.get(this.action, $(this).serialize(), null, 'script');
return false;
});
$('#sortbut a, #sortbutq a, #identities .pagination a, #pagination a').live('click',
function () {
$.getScript(this.href);
return false;
}
);
});
I am having this same issue. For some reason my submission only goes through the AJAX path for the first submit, after that it refreshes the page through the url. I would also really appreciate any thoughts on this
I just figured it out!
For the search form you need to use on()
It is really annoying because it doesn't throw any kind of error, the only reason I got it working is from having to get the sort working out before. Hope this helps someone.
I new in rails, i try to this work on rails 4, somebody had tried with this
In this approach, the searching is case-sensitive, how can i make that case-insensitive?
Also, i need to search the text in multiple fields using where clause and or operation in MongoDB. How can i do that?
This will make it case insensitive
You can use:
Can someone explain why this isn't the best way to do this? And what jQuery plugins to look at?
I've added the jquery.observe_field.js plugin to add a delay but my search/sort is laggy on my production server.
Excellent Railscast. But for those who don't want to keep querying server, you can use DataTables and do sorting and searching on the client side. Example here: http://jsfiddle.net/GJYfe/1/
Wow. There is a lot of JS code in there.
Easily you can use just it:
$(document).ready(function() {
$('#example').dataTable();
});
Where #example is the ID of the table.
Remember to use dataTable as a class, and to read the documentantion:
https://datatables.net/
Check out smart_listing - our rails gem that makes easy to present data lists with built-in filtering, sorting and in-place editing.
I guess the
↵
that has snuck into some of the ASCIICast is just a line break/continuation indicator? You can dump the entity and rejoin the lines.Hi,
One issue I am having at the moment is that when i search i get the new results fine but the new paginated links do not go anywhere, they just fire a get request
"http://localhost:3000/public/rehome_=1415284148389&animal_town=Pontypool&animal_type=Dog&page=2&rehomed=false&utf8=%E2%9C%93"
but the content does not change
Anyone have any ideas?
Richard,
I was having a similar issue. See Mizpah's solution above.
"We also need change how the line is written to include the nodes to stay bound to:
$(document).on("click","#game_classes th a, #game_classes .pagination a", function() {* would replace the line used in the original:
I also believe we now need the lines in application.js that load other documents (// = require somthing).
Thus my complete application.js looks like this:
ruby...
//= require jquery
//= require jquery_ujs
//= require_tree .
$(function() {
$(document).on("click","#game_classes th a, #game_classes .pagination a", function() {
$.getScript(this.href);
return false;
});
$("#game_classes_search input").keyup(function() {
$.get($("#game_classes_search").attr("action"), $("#game_classes_search").serialize(), null, "script");
return false;
});
});
"
DO THIS INSTEAD!!
$(document).on("click", "#products .pagination a", function() {
$.getScript(this.href);
return false;
});
Ajax search is not working though simple search works fine. I am not getting any error as well in my log file. Following is my code:
show_workers.haml
= form_tag show_workers_agencies_path, :method => 'get' do
= hidden_field_tag :direction, params[:direction]
= hidden_field_tag :sort, params[:sort]
%p
= text_field_tag :search , params[:search]
= submit_tag "Search", :name => nil
workers= render 'workers'
_workers.haml
%table.pretty
%thead
%tr
%th= sortable "name"
%th Phone number
%th City
%th{:colspan => "3"}
%tbody
- @workers_list.each do |worker|
%tr
%td= worker.name
%td= worker.phone_number
%td= worker.city
%br
= paginate @workers_list
show_workers.js.haml
$("#workers").html("#{escape_javascript(render("workers"))}");
agencies_controller.rb
def show_workers
@workers_list = Worker.where(agency_id: current_user.agency.id).order(sort_column + " " + sort_direction).search(params[:search]).page(params[:page]).per(5)
respond_to do |format|
format.html
format.js
end
end
application.js
$(function() {
$("#workers th a").on("click", function() {
$.getScript(this.href);
return false;
});
});
Please tell if I am missing anything.
On rails 5 I couldn't get the code working correctly with the information presented by Luke Schoen. However, I got it working with the following code based on Rayn's code with the following adjustments:
app/models/product.rb: I used self.where for both cases and replaced "scoped" with "self.where(nil)".
app/helpers/application_helper.rb: I used request.query_parameters.merge to get the code working. (Also be aware of the double brackets) So: link_to title, request.query_parameters.merge({ sort: column_name, direction: direction, page: nil })
Hi Luke,
I was wondering, would I replace the word column with my div's class if I was to use div's instead of tables?