MikeHolford
MikeHolford

Reputation: 1931

Render multiple params from rails controller with jquery/ajax request

Hey so I am new to Ajax but trying to get my head around this. The below code works and allows me to update the text in my view with Jquery. I want to be able to do this twice but can't figure out how to define more params in the ajax request.

My ajax function fires perfectly well on click.

$.ajax({
url: '/check-existing-user?email=' + user_email,
type: 'get',
dataType: 'html',
processData: false,
success: function(data) {
    if (data == "nil") {
        alert('No existing user');
    }
    else {
        $('form#new_user').submit();
        $('.current_user_thanks span').text(data);
    }
}
});

I am able to successfully update $('.current_user_thanks span').text withdata which is passed from my controller below:

def check_existing_user
  @user = User.find_by_email(params[:email])
  if @user.present?
      if @user.confirmed?
          render :text => @user.first_name,
      else
          render :text => "nil"
      end
  else
      render :text => "nil"
  end
end

Is there any way I can pass multiple variables within data? Such as data.user_name and data.user_email for example? Would I have to use Json? and if so how as I have looked at plenty of examples and the above code is all I can get to work. Thanks!

Upvotes: 0

Views: 706

Answers (1)

Rajdeep Singh
Rajdeep Singh

Reputation: 17834

Try sending the whole object in json format

render :json => @user

or, do this

json_data = { username: @user.username, email: @user.email, ... }
render :json => json_data

Hope that helps!

Upvotes: 2

Related Questions