Rendering one ERB page into another using Ruby/Sinatra/AJAX

586 Views Asked by At

I am making a Ruby/Sinatra app that uses the Twitter API to retrieve timelines. I have an index page with a form that asks for a Twitter handle to search. When the submit button is clicked, I'd like for the timelines to appear underneath the form on the same page, instead of on result.erb where they're going now.

I am probably rendering the result page wrong in my AJAX call ("<%= erb :result %>" is literally what is showing up) but I've been failing to find the right way to do that and can't tell if that's the only problem.

app.rb:

class App < Sinatra::Base
  get '/' do
    erb :index
  end

  post '/result' do
    @username = params[:username] || "justinbieber"    
    connection = GetTweets.new(@username)
    @all_tweets = connection.get_search_results
    erb :result, :locals => {'username' => @username}
    end
  end
end

index.erb:

<html>
  <head>
    <link rel="stylesheet" type="text/css" href="/stylesheets/style.css">
    <script src="//code.jquery.com/jquery-1.11.3.min.js"></script>
    <script src="/javascripts/script.js.erb"></script>
  </head>
  <body>
    <div id="input-form">
      <form action="/result" method="POST">
        @ <input type="text" name="username">
        <input type="submit">
      </form>
    </div>
    <div id="loading"></div>
    <div id="result"></div>
  </body>
</html>

result.erb:

<%= @all_tweets.first.user.name %>

<% @tweet_array.each do |tweet| %>
  <p><span class="username">@<%= @username %>: </span>
    <span class="tweet"><%= tweet %></span>
  </p>
<% end %>

script.js.erb:

$(document).ready(function() {
  $('form').submit(function(e){
    e.preventDefault();
    $('#loading').html("<img src='images/loading.gif' height='325' width='325'><br>processing...");
      $.ajax({
      type: "POST",
      url: "/result",
      data: $('form').serialize(),
      success: function(){
          $('#loading').hide();
          $('#result').html("<%= erb :result %>")
      },
      error: function(){
        $("#result").html("No success.")
      }
    });
  });
});

Thanks!

1

There are 1 best solutions below

0
On

Fixed... the answer was in script.js... I forgot to include an argument in the success function. Whoops 8)

   success: function(result){
              $('#loading').hide();
              $('#result').html(result)
          },