简体   繁体   中英

How to pass json response from controller to ajax call in rails

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.

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?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM