Reputation: 4251
this is my ajax call section in js file :
$("#sign_submit").click(function(){
email_id = $("#user_email").val();
password = $("#user_password").val();
data = {email: email_id, password: password };
url = user/sign_in';
$.ajax({
url: url,
data: data,
cache: false,
type: "post",
success: function(data){
console.log(data);
}
});
});
This is my controller Action :
def create
@user = User.find_by_email(params['email'])
if @user.nil?
respond_to do |format|
format.json {render :json => {:response => 'User is invalid'} } #how to pass json response here.
end
end
if @user.check_valid_user?(params['password'])
set_dashboard_location
set_current_user(session[:customer_id])
render js: %(window.location.href='#{session["spree_user_return_to"]}')
else
#redirect_to '/' and return
#how to psas json response here.
end
end
In in create actions (else part), I need to pass json response regarding( invalid user/ invalid user credentials) to my ajax call, which I can alert user on the View Page.
Upvotes: 0
Views: 8019
Reputation: 4093
I have difficulty to understand where is the problem but I will do my best to help you.
The basic command to render json from a Rails controller is
render json: @user
for example. I saw that you wrote something like that but inside a certain block. When you write
respond_to do |format|
format.json { render json: @foo }
end
The json rendering will only occur when the url for the query finishes by .json (The format of the query)
So here url = user/sign_in.json
will render json but url = user/sign_in
will assume the format is html (the default format, that you can change in your routes definitions) and won't render anything.
If you need to render json no matter the url. Do not put it in the block respond_to
. If you need 2 different behaviors if it's an ajax call or another call, use the url foo/bar.json
If you run rake routes
in your rails root folder, you will see urls like /users/sign_in(.:format)
, that means that /users/sign_in.toto
will set the :format
to toto
I hope it was clear ! If you prefer to set a default format in your routes :
How to set the default format for a route in Rails?
Upvotes: 6