1

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!

3
  • How / when is that votes_controller action called? Commented Mar 19, 2014 at 0:19
  • where does vote_status in var status = vote_status.evalJSON(); defined? Commented Mar 19, 2014 at 0:25
  • @enchante that is my question. I dont know clearly how and where should I defined it. How can I get json from controller in javascript? Commented Mar 19, 2014 at 0:29

2 Answers 2

3

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)
}
Sign up to request clarification or add additional context in comments.

2 Comments

but how should I define this variable? I need to get value of json from votes_controller
@Gvcci The data variable contains the rendered vote_status data.
2

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);
    }
  });

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.