The Spaghetti Refactory Established 2015

Easy peasy AJAX requests, couched in a Rails / Coffeescript environment

What follows is a pretty standard POST using ajax, but I've had to do this sporadically enough that I felt the need to write it down for my own posterity. Since I'm most comfortable in Rails, the setting for this exercise will still be a Rails app.

Let's say you have a UsersController and POST route to /users. In order to POST to that route within a CoffeeScript (for example, users.js.coffeefile:

$.ajax(
url: '/users'
type: 'POST'
data: { name: 'Bob Roberts', age: '52' }
).done (data) ->
// do something with data returned
return

Inside your UsersController#create method, the params hash will have the data you submitted, so:

params[:name]
# => 'Bob Roberts'
params[:age]
# => '52'

Then, in your create method, you can do this:

def create
@user = User.create(name: params[:name], age: params[:age])
render json: @user
end

Fairly standard. The only thing slightly different is the render call, which will convert the object to a JSON hash and return it to the ajax POST as a data packet. That data object gets returned in the .done section of the ajax call for you to do with whatever you want.

This approach has come in handy for me on a surprising number of occasions, despite how little JS code I write on a daily basis, so it's very good to know.

Tags