Pavel
Pavel

Reputation: 1974

Ruby on Rails: Get json from controller in Javascript file

in my controller I've some json:

votes_controller.rb:

def create
  ...
  vote_status = current_user.user_votes.pluck(:recipient_uid).include?(@user.uid)
  render json: vote_status
end

I need to get vote_status in javascript file

votes.js:

jQuery(function($) {
  $(".doWant").click( function () {
    var status = vote_status.evalJSON();
    var uid = $(this).parents("#dialog")[0];
    var username = $(this).parents("#dialog")[0];
    if(confirm("Are you sure?")) {
      $.ajax({
        url: '/votes' + "?uid=" + $(uid).attr("data-user-uid") + "&username=" + $(username).attr("data-user-username"),
        type: 'POST',
        success: function(data) {
          console.log(data)
        }
      });
    };
  });
});

But there is an error Uncaught ReferenceError: vote_status is not defined. What am I doing wrong?

Thanks!

Upvotes: 1

Views: 1531

Answers (2)

xiaoboa
xiaoboa

Reputation: 1953

The vote_status is returned in success json callback, init the status there

$.ajax({
    url: '/votes' + "?uid=" + $(uid).attr("data-user-uid") + "&username=" + $(username).attr("data-user-username"),
    type: 'POST',
    success: function(data) {
      var status = JSON.parse(data);
    }
  });

Upvotes: 2

Ryan Bigg
Ryan Bigg

Reputation: 107738

You're not defining this variable:

var status = vote_status.evalJSON();

You must define that variable.

It seems likely that you intended for that code to go into the success function, which returns the data from the ajax call as the first argument in that function:

success: function(data) {
  console.log(data)
}

Upvotes: 3

Related Questions