Diego Fernandez
Diego Fernandez

Reputation: 11

ruby, ajax and backbone

I'm new at ruby and backbone and I'm trying to send data to ruby controller, but I can't get the params on ruby. I'm forgotting something?

on coffescript page

doLogin: ->
  username = $(@el).find('#username').val()
  password = $(@el).find('#password').val()

  params = {username: username, password: password}

  $.ajax
    type: 'POST'
    url: '/users/login'
    data: params
    cache: false
    contentType: false
    processData: false
    success: (response) =>
      if response.success
        debugger
        ......

on Router

match '/users/login' => 'user#login', via: :post

on UserController < ApplicationController

def login
  username = params[:username]
  password = params[:password]

  @user = User.where({username: username, password: password}).first
  ......
end

on Pry Console

[1] pry(#<UserController>)> params
=> <ActionController::Parameters {"controller"=>"user", "action"=>"login"} permitted: false>

Upvotes: 0

Views: 49

Answers (1)

Peter Haight
Peter Haight

Reputation: 1924

Without all your code, I'm not sure what the problem is exactly. I think the most likely thing is that you need to get rid of contentType: false and processData: false.

contentType: false means you aren't sending a content type and without that Rails doesn't know how to parse the parameters in the POST body. You probably want the default here which is application/x-www-form-urlencoded which is what you will get if you remove that option.

processData: false tells jQuery not to turn your params object into the proper format for the POST body and you want jQuery to do that because you want to send your data in application/x-www-form-urlencoded format which Rails will parse and turn into parameters.

Next is you probably should send the CSRF token with your request. You can do that by adding these lines to your Coffeescript before you call $.ajax:

token = $('meta[name="csrf-token"]').attr('content')
$.ajaxSetup
  beforeSend: (xhr) -> 
    xhr.setRequestHeader('X-CSRF-Token', token)

$.ajax
  type: 'POST'
  url: '/users/login'
  data: params
  cache: false
  success: (response) =>
    console.log(response)

You can put this $.ajaxSetup call in some more centralized place because you'll probably want it for every AJAX call instead of just doLogin.

If neither of those are the problem, you should edit your post to include the console log from the rails process and also the console log from the browser as well.

Upvotes: 1

Related Questions