We've moved discussions to Discord

Updating User Record Using AJAX

Jason Ackerman
Hi All,

I'm trying to update a field on the User model using AJAX, but when I use byebug to inspect the params in the controller (registrations_controller.rb > update_resource method) the params are always { }.

Here's the JS:
var data = JSON.stringify({ user: { show_getting_started: true} })
Rails.ajax({
	type: "PATCH",
	url: "/users",
	data: data,
	contentType: 'application/json',
	dataType: "JSON",
    success: function(data) {
        console.log(data);
    }
})

I added the following to application_controller to permit the new parameter:
def configure_permitted_parameters
    extra_keys = [:avatar, :name, :time_zone, :show_getting_started]

Any idea what I'm missing here?
Darren Smyth
Do you have to add the CSRF token?
Jason Ackerman
I'm making AJAX update and delete records (not Users, other record types) and haven't needed to add it and haven't had any issues.
Jason Ackerman
I was able to get the params to pass through by changing the way the data was being sent. Once I set my data variable as follows it worked:
var data = 'user[show_getting_started]=false';
Jason Ackerman
Follow-up question - This is my AJAX call now (the database is being updated correctly):

var data = 'user[show_getting_started]=false';
Rails.ajax({
	type: "PATCH",
	url: "/users",
	data: data,
    success: function(data) {
    	alert("You can always find Getting Started in the dropdown menu.")
    }
})

This is in Users::RegistrationsController < Devise::RegistrationsController:

def update_resource(resource, params)
    # Jumpstart: Allow user to edit their profile without password
    resource.update_without_password(params)
end

I have two issues now:
  1. After the AJAX call there is a redirect_to the home page, when it should not redirect at all because it is an AJAX call that I want to just return a JSON response to be used in the success callback (if I want). Any ideas on how to prevent the redirect?
  2. The alert box in the success callback is appearing twice (it appears, then when you click Okay it reappears one more time)

Any help would be much appreciated!

PS - Happy Thanksgiving!
Notifications
You’re not receiving notifications from this thread.