0

I'm making a little program with Ruby and Sinatra that compares different types of media. In this case, I'm comparing movies. I'll post my code, then explain the problem.

ERB file:

<!DOCTYPE html>
<html>
  <head>
    <title>
      Media Comparison
    </title>

    <script src="//code.jquery.com/jquery-1.10.2.min.js"></script>

    <script type="text/javascript">
      //when the document is ready to be manipulated
      $(document).ready(function(){

        //add a click handler to the button
        $("#add_movie").submit(function() {

          $.post("/movie", //url
            {name: $("#name").val(), releaseDate: $("#release_date").val().toString(), director: $("#director").val(), ratingCritic: $("#ratingc").val(), ratingMPAA: $("#ratingm").val(), genre: $("#genre").val()}, //data 
            function(data) { //function to call on return
              //empty out the select box
              $("#movie1").empty();
              $.each(data, function( key, val ) {
                //refill it

                $("#movie1").append("<option value=" + val.name + "> " + val.name  + "</option>"
                  );
              });
              $("#movie2").empty();
              $.each(data, function( key, val ) {


                $("#movie2").append("<option value=" + val.name + "> " + val.name  + "</option>"
                  );
              });

              //clear out the name and email textboxes - possibly arbitrary
              $("#name").val("");
              $("#release_date").val("");             
              $("#director").val("");
              $("#ratingc").val("");
              $("#ratingm").val("");
              $("#genre").val("");  
              }
            );
        });
      });
    </script>
  </head>
  <body>
    <FORM METHOD="LINK" ACTION="/">
        <input id='backButton' type='submit' value='Go back' />
    </FORM>
    <h1>Would you like to compare movies...</h1>
    <p>
    <div id= "movies">      
      <select id = "movie1">
        <% @movie_list.each do |movie| %>       
          <option value="<%= movie.name %>"><%= movie.name %></option>
        <% end %>
      </select>
      <select id = "movie2">
        <% @movie_list.each do |movie| %>       
          <option value="<%= movie.name %>"><%= movie.name %></option>
        <% end %>
      </select>
      <input id='compare_movies' type='submit' value="Compare these movies!" />
    </div>
    <div id= "compare">
      <script type="text/javascript">
      $("#compare").empty();
        $(document).ready(function(){

          $("#compare_movies").click(function() {
            if($("#movie1").val() == $("#movie2").val()){
              alert("You can't compare the same two movies!");
            }
            else{
              $("#compare").empty();
              $("#compare").append("<table border=\"1\" style=\"width:300px\"><tr><td>" + $("#movie1 option:selected").text() + "</td><td>" + $("#movie2 option:selected").text() + "</td></tr><tr><td>Great</td><td>Movies</td></tr></table>");
            }
          });
        });
      </script>
    </div>
    <h1>...Or add one?</h1>
    <form>
      Name: <input id='name' type='text' required>
      <br/>
      Release Date: <input id='release_date' type='date' required>
      <br/>
      Director: <input id='director' type='text' required>
      <br/>
      Critical Rating: <input id='ratingc' type='number' step=0.5 min="0" max="5" required>
      <br/>
      MPAA Rating: <input id='ratingm' type='text' required>
      <br/>
      Genre: <input id='genre' type='text' required>
      <br/>
      <input id='add_movie' type='submit' value="Add movie" >
    </form>
  </body>
</html>

.rb file:

require 'sinatra'
require 'sequel'
require 'sinatra/json'

DB = Sequel.connect('sqlite://Comparison.db')

DB.create_table? :tvs do
  primary_key :id #auto incrementing primary key
  String :name #name of the show
  Integer :season #number of seasons the show has had
  Integer :startYear #The year the show first aired
  Boolean :current #whether or not the show is currently running
  String :endYear, :default=>"Currently Airing"   #The year the show finished. Able to be false if it's current
  Float :rating #The show's rating, out of five
end 
DB.create_table? :movies do
  primary_key :id #auto incrementing primary key
  String :name #name of the Movie
  String :releaseDate #Date the movie was release
  String :director #Director of the
  Float :ratingCritic #Does it suck?
  String :ratingMPAA #MPAA rating
  String :genre #genre of movie
end
DB.create_table? :musics do
  primary_key :id #auto incrementing primary key
  String :albumTitle #The title of the album
  String :releaseDate #The date the album was released
  String :artist #Album artist
  Boolean :advisory #True if there is a parental advisory
  String :genre #Genre of the music
  Float :rating #Critical rating
end
DB.create_table? :games do
  primary_key :id #auto incrementing primary key
  String :name #Name of the game
  String :ratingESRB, :size=>1 #Game rating, only one character long
  String :releaseDate #Game's release date
  String :publisher #Game's publisher
  String :platform #Game's platform
  Float :ratingCritic #Critical rating
end

require_relative 'Game'
require_relative 'Movie'
require_relative 'Music'
require_relative 'Tv'

def addMovie
  Movie.create(:name => "The Lion King", :releaseDate => "1996-10-26", :director => "John Lasseter", :ratingCritic => 4.5, :ratingMPAA => "PG", :genre => "Family")
  Movie.insert(:name => "Cats and Dogs", :releaseDate => "2000-4-16", :director => "Mr. Director", :ratingCritic => 2.3, :ratingMPAA => "PG", :genre => "Family")
end
def print_movies
  #get all the students and print them (each row comes back as a hash)
  Movie.all.each do |movie|
    #print
    puts "Name: #{movie[:name]}
Release Date: #{movie[:releaseDate]}
Director: #{movie[:director]}
Critical Rating: #{movie[:ratingCritic]}
MPAA Rating: #{movie[:ratingMPAA]}
Genre: #{movie[:genre]}\n\n"
  end
end

def delete_media_db
  DB[:movies].delete
  DB[:games].delete
  DB[:tvs].delete
  DB[:musics].delete
end

get '/' do
  erb :welcome
end
get '/movie' do
  @movie_list = Movie.all
  erb :movie
end
post '/movie' do
  Movie.create(:name => params[:name],
         :releaseDate => params[:releaseDate],
         :director => params[:director],
         :ratingCritic => params[:ratingCritic],
         :ratingMPAA => params[:ratingMPAA],
         :genre => params[:genre])
    movies = Movie.all.map do |movie|
    {:name => movie.name, :releaseDate => movie.releaseDate, :director => movie.director, :ratingCritic => movie.ratingCritic, :ratingMPAA => movie.ratingMPAA, :genre => movie.genre}
  end

  #turn the array of hashes into json
  return json movies
end

My problem comes from the form at the bottom of the ERB file. This allows the user to add a movie to the database they'd like to be compared. Originally, there were no form tags, and the data would get passed to the database by referencing the input field by ID in these lines:

name: $("#name").val(), releaseDate: $("#release_date").val().toString(), director: $("#director").val(), ratingCritic: $("#ratingc").val(), ratingMPAA: $("#ratingm").val(), genre: $("#genre").val()},

However, I wanted to do simple data validation that makes sure there was something in the input fields, so I made the fields required and put them in a form. However, now that they're in a form and I changed the click to a submit, I don't seem to be entering the submit anymore. I couldn't do a click, as it would process the POST whether or not the values were valid, since it was waiting for a click, not a submit.

1 Answer 1

1
  • First of all you probably in most occations don't need a from unless you want to submit it

  • If you have a form, and you just need to process it's data on client side without submitting it, you can simply use a normal button instead of submit button

  • If you want to process the data on client side and then submit the from, in your submit button handler call e.preventDefault // where e is the event object and after processing the data access the from and submitting using submit() function

from your code, an example would be like

<input id='compare_movies' type='submit' value="Compare these movies!" />

$("#compare_movies").click(function(e) {
e.preventDefault();
        if($("#movie1").val() == $("#movie2").val()){
          alert("You can't compare the same two movies!");
        }
        else{
          $("#compare").empty();
          $("#compare").append("<table border=\"1\" style=\"width:300px\"><tr><td>" + $("#movie1 option:selected").text() + "</td><td>" + $("#movie2 option:selected").text() + "</td></tr><tr><td>Great</td><td>Movies</td></tr></table>");
        }
$('selector').submit() // do this if you want to submit the form. selector can be an id, class etc of the form
});

side note: your code looks alien to me :)

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the response! Problem is, I'm not worried about that submit. That one is working fine. I'm talking about the submit that submits the new movies below. The part of code you highlighted isn't a form, either. I was moreso talking about this: <form> Name: <input id='name' type='text' required> ... <input id='add_movie' type='submit' value="Add movie" > </form>

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.