I have the following jQuery js to insert a form in my view (in application.js):
$("#add_new_quote").click(function() {
$(".quote:first").prepend("<form action=\"" + window.location + "\" accept-charset=\"UTF-8\" method=\"post\"> " +
"Quote: <input id=\"quote_text\" name =\"quote_text\" type=\"text\" maxlength='145' size='100'>" +
"<input name=\"submit\" type=\"submit\" value=\"Add\">" +
"</form>" +
"<br>");
});
When I click submit, all session vars I have set are somehow lost, and I have no idea why and how. For example, I’m setting user’s id in a session variable (session[:user_id]) for references, and it is blank after the submit. I tried adding a form using form_tag in the view, and it works fine, so I guess I’m missing something important …
I’m using Rails 3 and jQuery 1.5.
Apparently when I submit the hand-crafted form with jQuery, Rails does not add the authenticity token to the POST parameters, therefore the “problem” is probably caused by a security feature in Rails which clears the session. An alternative is to use form_tag to create the form in the view, use jQuery to hide() it when the page loads, and use toggle() to unhide/hide the form when the user clicks on a link or button. Thanks to Dimitry and moo-is-too-short for their help.