0

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.

usha
  • 28,973
  • 5
  • 72
  • 93
Ajay
  • 4,199
  • 4
  • 27
  • 47

1 Answers1

6

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?

Community
  • 1
  • 1
Uelb
  • 3,947
  • 2
  • 21
  • 32
  • 1
    I understand your explanation. And tried to just pass the @user in json: , but when it's nil, it should execute our if block & return nil to my ajax file. but in actual it's not returning nil value to my ajax. how to pass that nil value to ajax ? – Ajay Mar 03 '14 at 17:25