Created
May 26, 2013 01:11
-
-
Save esromneb/5651374 to your computer and use it in GitHub Desktop.
Quick intro on how to do ajax on rails. This was simplified from my autocomplete code. In this example the autocomplete is removed and just ajax is presented.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#routes.rb | |
get 'scraped_episodes_search' => 'scraped_episodes#search' | |
#scraped_episodes_controller.rb | |
# used for autocomplete search | |
def search | |
searchTerm = params[:s] | |
# only search db if 3 or more chars | |
if( searchTerm.length >= 3 ) | |
@searchItems = ScrapedEpisode.find(:all, :conditions => ["title LIKE ?", "%#{searchTerm}%"]) | |
else | |
fake = ScrapedEpisode.new | |
fake.title = "..." | |
@searchItems = [fake] | |
end | |
respond_to do |format| | |
format.html # this will render search.html.erb | |
format.json { render json: @searchItems } | |
end | |
end | |
# whatever.erb | |
<script type="text/javascript"> | |
var params = {}; | |
params.s = 'searching for text'; | |
//pass request to server | |
$.getJSON("/scraped_episodes_search.json", params, | |
function(data) { | |
alert(JSON.stringify(data)); | |
} // end of callback | |
); // end of getJSON | |
</script> | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment