Using ajax to send data to ruby controller

时间:2016-04-12 00:56:52

标签: javascript ruby-on-rails ruby ajax hash

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'

1 个答案:

答案 0 :(得分:1)

你需要做这样的事情:

'render json:'之后的任何内容都将返回到ajax调用结果。在这种情况下,如果用户保存它,则返回“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

现在,在Ajax调用中,我们需要定义回调以在成功的情况下处理响应。您还需要在视图中添加一个类(在此示例中,此类的id为'result'),在该元素中,您将呈现要显示的响应: ...

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);
   }
 });
}
相关问题