Reputation: 48443
I have this scheme: JS:
jQuery.validator.addMethod(
"check_membership",
function() {
console.log('A');
$.ajax({
type: "POST",
url: "/subscriptions/check_validity",
dataType:"JSON",
data: {coupon: "12345"},
});
console.log('<%= @aaa %>');
},
"mmmmm"
);
and Rails action:
def check_validity
@aaa = 'xxx'
respond_to do |format|
format.js { render :text => @aaa }
end
end
My goal is to display in Javascript the value from Rails - @aaa
, but the output of
console.log('<%= @aaa %>');
is just an empty space...
But I am not sure what the proper workflow should be here (I need to pass just a kind of information like "yes"/"no").
Thanks guys!
Upvotes: 1
Views: 1397
Reputation: 12520
Ajax sends a params
variable of your data to the controller, just like a form for a new record. In your example, to retrieve the coupon value, you pass params the key you established in your ajax call:
def check_validity
value = params[:coupon] # returns "12345"
...
end
As noted in another answer, this will not yield the @aaa value in your console.log, or anywhere in your javascript. These variables are interpreted on the server side, but javascript only works on the client side (unless you're using server side javascript, but that's a horse of a different color). This can be confusing because we use Ruby variables in Views, but Views are interpreted on the server, before they are sent to the client. Javascript is not.
Once you pass a variable to Rails, through the params value, you'll need to send any new information back to the client, which is looks like you're trying to do with :text => @aaa
. Many ways to tackle this issue, but you could start with the Railscast:
http://railscasts.com/episodes/324-passing-data-to-javascript
and also
http://railscasts.com/episodes/136-jquery-ajax-revised
Upvotes: 1
Reputation: 14610
Hm, a lot of confusion going on here:
console.log('<%= @aaa %>');
Is mixing server side and client side stuff. If you
render :text => @aaa
in rails, you don't get a variable named @aaa in your browser.
I'd recommend rendering json to the browser anyway...
Upvotes: 0