AJAX Rails - Request Apparently Lost - No UI Results
I had some troubles with a JavaScript request earlier and the solution provided seems to have fixed the problem (since I get not error from the browser's console) however my app do
Solution 1:
You're using remote: true
, you should to use method respond_to
to handle ajax. This is an example, you can do step by step:
- Remove
app/assets/javascripts/stocks.js
Edit action
search
inapp/controllers/stocks_controller.rb
def search if params[:stock] @stock = Stock.find_by_ticker(params[:stock]) @stock ||= Stock.new_from_lookup(params[:stock]) end respond_to do |format| format.html format.js end end
Edit
app/views/stocks/_lookup.html.erb
<div id="stock-lookup"> <h3>Search for stocks</h3> <%= form_tag search_stocks_path, remote: true, method: :get, id: 'stock-lookup-form' do %> <div class="form-group row no-padding text-center col-md-12"> <div class="col-md-10"> <%= text_field_tag :stock, params[:stock], placeholder: "Stock ticker symbol", autofocus: true, class: 'form-control search-box input-lg' %> </div> <div class="col-md-2"> <%= button_tag(type: :submit, class: "btn btn-lg btn-success") do %> <i class="glyphicon glyphicon-search"></i> Look up a stock <% end %> </div> </div> <% end %> <div id='stock-lookup-results' class="results-block"></div> </div>
Create
app/views/stocks/_stock.html.erb
<% if stock.present? %> <strong>Symbol:</strong> <%= stock.ticker %> <strong>Name:</strong> <%= stock.name %> <strong>Price:</strong> <%= stock.price %> <% else %> <i>Stock not found</i> <% end %>
Create
app/views/stocks/search.js.erb
$("#stock-lookup-results").html("<%= j render 'stock', {stock: @stock} %>");
Done!!!
Post a Comment for "AJAX Rails - Request Apparently Lost - No UI Results"