Abdul Ahmad
Abdul Ahmad

Reputation: 10021

rails - devise keeps returning html responses to ajax requests

I've been trying to get devise to return json to ajax requests, but it keeps sending back html instead. I followed this (and other, I literally looked at every link on 2 google search pages) tutorial(s) but it still sends html. Here's what I changed and where:

config/initializers/devise.rb:

added: config.http_authenticatable_on_xhr = false

created app/controllers/sessions_controller:

class SessionsController < Devise::SessionsController
  respond_to :json
end

created app.controllers/registrations_controller:

class RegistrationsController < Devise::RegistrationsController  
  respond_to :json
end

added under config/routes.rb

devise_for :users, :controllers => {
  sessions: 'sessions', 
  registrations: 'registrations'
}

and I think that's it. but I keep getting html back. Should I delete the partial views associated with devise?

Here's what a request looks like:

Started POST "/users/sign_in" for ::1 at 2016-06-17 09:01:19 -0400 Processing by SessionsController#create as / Parameters: {"user"=>{"email"=>"", "password"=>"[FILTERED]"}, "authenticity_token"=>"HDlnoiGZXXoarFjdlfxZL6AF0EY8Xf1K5mRwceVmVw647lG+NPJxDYstXLhiH4BGGwmNrrX8U5gZD8B3IfhS+w=="}

Upvotes: 0

Views: 361

Answers (1)

Abdul Ahmad
Abdul Ahmad

Reputation: 10021

I was missing the dataType property on the ajax request, after setting it to `application/json' it worked.

$.ajax({
    method: "POST",
    url: "/users/sign_in",
    dataType: 'application/json', <--- here
    headers: {
      'X-CSRF-Token': csrfTokenContent
    },
    data: {
      user: {
        email: email,
        password: password,
      },
      authenticity_token: csrfTokenContent
    }
  })

Upvotes: 0

Related Questions