Calling an action within javascript function w/ ajax


#1

I am trying to call an action within a javscript function using ajax,
but I am having some problems. I need the ajax call to return a value
and am thinking I can do this using onComplete and Ajax.Request but I
am running into some problems. This is the code I am using for the
Ajax.Request:

new Ajax.Request( '/users/username', {
  method: 'post',
  parameters: { username: $('new_user_username').value},
  onComplete: parseResults()
});

I have an action called username in my users controller in which I am
taking the username params passed by the Ajax.Request and seeing if it
exists in the database. I want to return true/false depending on if
it exists or not. But I am having trouble even getting the
Ajax.Request to work.

This is some of the output from the console:

Processing UsersController#username (for 192.168.1.105 at 2008-12-13
19:52:39) [POST]
Session ID:
BAh7BzoMY3NyZl9pZCIlYmNjM2YxODllZWIwMGM1NDkyMzQ0NjUyODMxODAz
ZTUiCmZsYXNoSUM6J0FjdGlvbkNvbnRyb2xsZXI6OkZsYXNoOjpGbGFzaEhh
c2h7AAY6CkB1c2VkewA=–d0d5fc597c61c2a295570ee9b118db7ba4285f3f
Parameters: {“username”=>“d”, “action”=>“username”,
“controller”=>“users”}

ActionController::InvalidAuthenticityToken
(ActionController::InvalidAuthenticityToken):

Im not sure how to get around this InvalidAuthenticityToken, anyone
have any idea whats going on here. Ive been struggling with this for
a while and am somewhat new to ajax so I could use some help.


#2

Im thinking this needs to be a ‘GET’ request in order to return a
response, but when I change the method to a GET, it calls the show
action:

Parameters: {“username”=>“f”, “action”=>“show”, “id”=>“username”,
“controller”=>“users”}

Stumped…


#3

Just use remote_function and it will generate the appropriate ajax
call for you - this will make your code much less brittle to Rails
changes.

http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html

HY