Reputation: 83
I was hoping someone could help me out on this one, and a possible explanation. I have a rails controller called get_songs that will get a hash of songs from the currently logged in user. That said, whenever a particular button is clicked I want to get the data from the get_songs controller at put it in javascript variable. The following is what I have so far.
playlist.js.erb
function get_songs() {
var mysongs;
$.ajax({
type : 'GET',
url : "getSongs",
dataType : 'json',
success : function(response) {
}
});
}
My controlller
class StaticPagesController < ApplicationController
respond_to :js, :json, :html
def get_songs()
if user_signed_in?
session[:user_id] = current_user.id
present_user = User.find(session[:user_id])
present_user = present_user.playlist.keys
@songs = present_user
respond_to do |format|
format.json { render :json => @songs}
end
end
My routes:
match '/getSongs', to: 'static_pages#get_songs', via: 'get'
Upvotes: 0
Views: 852
Reputation: 249
If everything was working you would do:
success : function(response) {
mysongs = response;
}
The 'response' parameter on the success function is the result of the ajax call you are sending from your controller; the @songs json.
A simple way to debug your javascript (to check what is the value of your 'response' after the ajax request) is to right-click on your browser and click on 'inspect', then go to the 'Sources' tab, look for your javascript file and click the line where you want to add the debug point (in this case the line with 'mysongs = response', then refresh the page. It should stop running at that point and show the value of 'response'.
Upvotes: 1
Reputation: 2356
I think problem in session. When you send request using ajax, you don't send any cookies and session. So try this
$.ajax({
type:"GET",
beforeSend: function (request){
//your token is here
request.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr("content"));
},
url: "getSongs",
dataType : 'json',
success : function(response) {
console.log(response)
}
});
Also, make sure that you have <%= csrf_meta_tag %>
in layouts/application.html.erb
UPD
If you are using gem 'jquery-rails'
and have //= require jquery_ujs
in application.js file
Content of csrf_meta_tag
automatically will be added to all your ajax requests
Upvotes: 1