简体   繁体   中英

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 with data 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!

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!

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