简体   繁体   中英

Use Ajax to request for rails controller data

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'

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

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'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM