I’m trying to send a login request to rails Restful API from my Phonegap app on iOS.
Following code works with jQuery 1.5 but not with jQuery 1.4.2.
Does anyone know why this is the case?
$.ajax({
type: 'POST',
url: urlFactory.getLoginURL(),
data: { 'email': emailVal, 'password': passwordVal },
success: onSuccess,
error: onError,
dataType: "json"
});
The web server gives me the following error:
Started POST "/login.json" for 127.0.0.1 at Mon Apr 18 00:29:38 +0100 2011
Processing by SessionsController#create as JSON
Parameters: {"password"=>"[FILTERED]", "email"=>"example@gmail.com"}
User Load (0.3ms) SELECT users.* FROM users WHERE (users.id IS NULL) LIMIT 1
Completed in 251ms
ActionController::InvalidAuthenticityToken (ActionController::InvalidAuthenticityToken):
app/controllers/application_controller.rb:37:in require_authorisation_happened'
Rendered /usr/local/lib/ruby/gems/1.8/gems/actionpack- 3.0.3/lib/action_dispatch/middleware/templates/rescues/_trace.erb (2.4ms)
Rendered /usr/local/lib/ruby/gems/1.8/gems/actionpack- 3.0.3/lib/action_dispatch/middleware/templates/rescues/_request_and_response.erb (14.1ms)
Rendered /usr/local/lib/ruby/gems/1.8/gems/actionpack- 3.0.3/lib/action_dispatch/middleware/templates/rescues/diagnostics.erb within rescues/layout (23.4ms)
It returns following in the successful case:
users
Started POST "/login.json" for 127.0.0.1 at Mon Apr 18 00:16:25 +0100 2011
Processing by SessionsController#create as JSON
Parameters: {"password"=>"[FILTERED]", "email"=>"example@gmail.com"}
User Load (0.3ms) SELECT.* FROMusersWHERE (users.idIS NULL) LIMIT 1users
User Load (19.4ms) SELECT.* FROMusersWHERE (users.email= 'example@gmail.com') LIMIT 1
Completed 200 OK in 306ms (Views: 4.6ms | ActiveRecord: 19.7ms)
You are missing an authenticity token. In rails2 you can use form_authenticity_token in your view to render the authenticity token and then you’ll need to add that to the parameters submitted by the form.
In Rails3 it’s easier. Just add <%= csrf_meta_tag %> in the head of your layout and then ensure you use the rails.js library for the ajax. This will pickup the authenticity token and submit it with the form.
There is a short writeup here http://www.themodestrubyist.com/2010/02/24/rails-3-ujs-and-csrf-meta-tags/
And an example app here https://github.com/grigio/rails3-ujs-demo.git