0

What I want to do:

I'm creating a ruby on rails app, which possess a playlist. The playlist belongs to a user object, and is a hash. There are two crucial buttons that I need. One to add new music to the hash, and another to remove music from the hash. I'm using javascript to keep track of the current song, which whenever the add button is pressed it should be sent back to the add_song controller via ajax, which the string will then be added to the playlist hash. However I strongly believe my implementation is off because I keep getting a 500 error. Presently I'm only worried about the add_song button. Any help is well appreciated!

Present Error: POST http://localhost:3000/adding 500 (Internal Server Error)

Below is my unobtrusive javascript code:

var player = new Audio("File1.mp3");
var value = 1 ;
var track = "File.mp3";


function backward() {
         var temp2 = player.src[player.src.length - 5] ;


          if ( temp2 != 1){
                value = parseInt(temp2);
                value  -= 1;
                player.src = "/File"+value+".mp3";
                player.play();
}
}

function forward() {
           var temp2 = player.src[player.src.length - 5] ;

           if ( temp2 != "5")  {
                value = parseInt(temp2);
                value  += 1;
                player.src = "/File"+value + ".mp3";
                player.play();
}
  }

  function play(){
        player.src  = "/File"+value + ".mp3";
         player.play();
} 

  function pause( ) {
         player.pause();
}


 //add button
 //delete button




function get_song() {
 return player.src
}

$(document).ready(function() {
$("div div").click( function(){

 if ( this.id  ==  'play' ) {
        play();
 }else if(this.id == 'backward'){
        backward();
 }else if(this.id == 'forward'){
        forward();
  }else if(this.id == 'stop') {
    pause() ;
  }else if(this.id == 'add_song') {
    $.ajax({
    url: "adding",
    type: "post",
    data: {data_value: JSON.stringify(player.src)}
 });
 }

});
});

Below is my staticpages controller

   class StaticPagesController < ApplicationController

  respond_to :js, :json, :html

    def add_song()
           if user_signed_in?
                session[:user_id] = current_user.id
                present_user = User.find(session[:user_id])
                puts present_user
                present_user.playlist.store(params[:data_value], 1)
                present_user.save
                puts "It works"
        else
        end
        end

        def remove_song()
            if user_signed_in?
             session[:user_id] = current_user.id
             present_user = User.find(session[:user_id])
             present_user.playlist.delete(params[:data_value])
             present_user.save
            else
        end
        end





  def home
   end

end

Lastly below is my routes:

 devise_for :users, :controllers => { :sessions => "sessions" , :registrations => "registrations"}
  devise_scope :user do
    get   "/log_in" => "sessions#new" ,as: :new_user_sessions
     post  '/log_in' => "sessions#create" ,as: :user_sessions
    delete "/destroy" => "devise/sessions#destroy", as: :destroy_user
    get   '/edit' => 'devise/registrations#edit'
    get   "/sign_up" => "registrations#new", as: :new_user_registrations
    post  "/sign_up" => "registrations#create", as: :user_registrations
 end

  root 'static_pages#home'
  match '/home', to:'static_pages#home', via: 'get'
  match '/adding',   to: 'static_pages#add_song',   via: 'post'
9
  • what's the error in the llog? Commented Apr 12, 2016 at 1:01
  • It works Completed 500 Internal Server Error in 71ms (ActiveRecord: 1.1ms) ActionView::MissingTemplate (Missing template static_pages/add_song, application/add_song with {:locale=>[:en], :formats=>[:html, :text, :js, :css, :ics, :csv, :vcf, :png, :jpeg, :gif, :bmp, :tiff, :mpeg, :xml, :rss, :atom, :yaml, :multipart_form, :url_encoded_form, :json, :pdf, :zip, :web_console_v2], :variants=>[], :handlers=>[:erb, :builder, :raw, :ruby, :coffee, :jbuilder]} Commented Apr 12, 2016 at 1:06
  • Alright, so you're sending the data. And its' trying to render a view, because that's a normal rails mechanism unless you override it. Can you post your controller actions for add_song? Commented Apr 12, 2016 at 1:14
  • @trh is this what you're looking for? adding POST /adding(.:format) static_pages#add_song Commented Apr 12, 2016 at 1:17
  • actually, the real action from app/controllers/static_pages_controller.rb - the add_song method is what's needed. Commented Apr 12, 2016 at 1:20

1 Answer 1

1

You need to do somthing like this:

Whatever is after the 'render json:' will be returned to the ajax call as the result. In this case, if the user saves it returns the words "it works":

def add_song()
 if user_signed_in?
   session[:user_id] = current_user.id
   present_user = User.find(session[:user_id])
   present_user.playlist.store(params[:data_value], 1)
   if present_user.save
     render json: { success: "It works" }
   end
 end
end

Now on the Ajax call we need to define the callback to handle the response in case of success. You also need to add a class in your view (in this example the id of this class is 'result') and in that element you will render the response you want to show: ...

else if(this.id == 'add_song') {
 $.ajax({
   url: "adding",
   type: "post",
   data: {data_value: JSON.stringify(player.src)},
   success: function(response) {
      $('#result').html(response.success);
   }
 });
}
Sign up to request clarification or add additional context in comments.

2 Comments

This worked like a gem! Do you care to explain @Victoria Castro ? So from what I understand I sent a ajax Json request, however there needs to be a response, which one wasn't given. Why is it that something needs to be rendered?
@acampbe222 A response is optional. You could've done the ajax call and end the controller code with the user.save, and that would have worked. Ajax provides the 'success' function which will run if the ajax call is successful. In this case we wanted to render the 'It works!' bit, so we needed to use it. The first parameter of the function is the response sent from the controller (the hash with the text want to render). You can also handle the call in case of error. check out all the options available on ajax: api.jquery.com/jquery.ajax

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.