Friday, December 2, 2011

jQuery AJAX Post to a Rails Create Function

Alright, I was going to do this posting when I discovered my solution, but I got super busy and never got around to it.

Basically the problem I ran into was knowing how to call Rails Create function using JQuery AJAX. There were a few parameters I didn't know about - like what was the URL, what was the type of AJAX call, how did I pass the data etc.

So, my setup was that I had a controller for my sessions and I was using rails "resources" routing to generate the routes for it. The "create" action of the SessionsController required a "session" object that contained an "email" and a "password" and the session was expected to be incoming via the parameters. That is, the SessionController.create was looking for params[:session][:email] and params[:session][:password].

So how do I get all this to happen with an AJAX JQuery call:

$.ajax({
type: "POST",
url: "/sessions",
dataType : "json",
data: { session : { email : var_email, password : var_password } },
success : function(data, textStatus, jqXHR) {
},
error : function(jqXHR, textStatus, errorThrown) {
}
});

The thing that took me a while to figure out was the URL and the type and the data. Probably would have helped if I reviewed my "resources" routing in Rails and also new that you could pass a JSON object to a Rails controller.

No comments: