mardi 2 juin 2015

Rails AJAX live search using helper method

I am trying to replicate the Spotify search in which it updates the search results on every key press. It currently works on submit but on key press and I'm getting a bad request error in my console. How can I get my page to update on key press? A little background info: I'm using the RSpotify gem in a helper method that is called on search entry.

static_controller.rb:

class StaticController < ApplicationController
  include ApplicationHelper

  def home
  end

  def search
    @search = user_search(params[:query])

    render :home

  end
end

application_helper.rb:

module ApplicationHelper

def artist_search(query)
    artists = RSpotify::Artist.search(query)
  return artists
end

def track_search(query)
  tracks = RSpotify::Track.search(query)
  return tracks
end

def album_search(query)
  albums = RSpotify::Album.search(query)
  return albums
end

def user_search(query)
  results = {"artist" => artist_search(query), "tracks" => track_search(query), "album" => album_search(query)}
  return results
end

end

home.html.erb:

<%= form_tag search_path, method: :get, :id => "search" do %>
    <%= text_field_tag :query %>
    <%= submit_tag 'Search' %>
<% end %>

<% if params.include?(:query) %>
    <div id="music"><%= render 'music' %></div>
<% end %>

_music.html.erb:

<h1>Artists</h1>
<div class="ui cards">
    <% @search["artist"].each do |artist| %>
      <div class="card">
        <!-- Artist image should go here -->
        <div class="content">
          <a class="header"><%= artist.name %></a>
        </div>
      </div>
    <% end %>
</div>

<h1>Albums</h1>
<div class="ui cards">
<% @search["album"].each do |album| %>
  <div class="card">
    <a class="image">
      <img src="<%= album.images.first["url"] %>">
    </a>
    <div class="content">
      <a class="header"><%= album.name %></a>
    </div>
  </div>
<% end %>
</div>

<h1>Songs</h1>
<% @search["tracks"].each do |song| %>
    <div class="ui list">
      <div class="item">
        <img class="ui avatar image" src="<%= song.album.images.first["url"] %>">
        <div class="content">
          <a class="header"><%= song.name %></a>
          <div class="description"><%= song.album.name %></div>
        </div>
      </div>
    </div>
<% end %>

index.js.erb:

$("#music").html("<%= escape_javascript(render("music")) %>")

application.js:

$(function() {
  $("#search input").keyup(function() {
    $.get($("search").attr("action", $("#search").serialize(), null, "script"));
    return false;
  });
});

Aucun commentaire:

Enregistrer un commentaire