Skip to content Skip to sidebar Skip to footer

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 i

Solution 1:

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

Solution 2:

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

Post a Comment for "Use Ajax To Request For Rails Controller Data"