Dynamically changing a form from POST/CREATE to PUT/UPDATE


#1

For the life of me I can’t figure this one out, although I can’t find
anyone else who’s attempted to do this, and probably with good reason.

Context: blog using AJAX

What I’m trying to do: when the user initially saves a blog entry, or
when auto-saving, I want subsequent saves to not create a new blog
entry

Why I can’t just reload the partial:

  • That would interrupt the flow of blog-writing
  • I’m using FCKEditor, and it takes a few seconds to pop in place
    upon the reload of the partial (which is less than elegant)

The solution that I came up with was to use the returned and evaluated
javascript/jQuery to re-write parts of the form so that it would
submit to my blog_entries controller and be treated correctly. So, I
have to change the method from POST to PUT, which in rails means
creating a hidden form element like so:

and then changing the form action from

action="/blog_entries"
to
action="/blog_entries/21" - or whatever the id is of the newly created
blog entry

There’s also a little place in the onsubmit attribute that I’m also
changing from /blog_entries to /blog_entries/21

What’s happening is it will submit, the updates will be successful,
but my update method will always respond with format.html, not
format.js, which is meaning I’m getting forwarded to my default
scaffold “show” page, which greets me with a nice “Your blog entry was
successfully updated.”

My update method looks like:

def update
@blog_entry = @user.blog_entries.find(params[:id])

respond_to do |format|
  if @blog_entry.update_attributes(params[:blog_entry])
    flash[:notice] = 'Blog entry was successfully updated.'
    format.js { redirect_to(:action => 'success') } if

request.xhr?
format.html { redirect_to(@blog_entry) }
format.xml { head :ok }
else
format.html { render :action => “edit” }
format.xml { render :xml => @blog_entry.errors, :status
=> :unprocessable_entity }
end
end
end

I’ve checked the server console, and it is receiving the PUT method,
and my blog entry is getting updated, but it doesn’t make any sense to
me why it is always being redirected, seemingly skipping over the
format.js line every time. I’ve tried this line like this, and each
of them yields the same thing:

    format.js { redirect_to(:action => 'success') }
    format.js if request.xhr?  (with the appropriate update.js.rjs

file in place)
format.js

If anyone could help me figure this one out it would be great! Sorry
about the long post, I wanted to be clear what was going on.

Groove


#2

This may be the browser-dependency issue with recognition of accept
headers. I adapted a snippet that you can put in your
ApplicationController:

protected
def correct_safari_and_ie_accept_headers
ajax_request_types = [‘text/javascript’, ‘application/json’,
‘text/xml’]
request.accepts.sort!{ |x, y| ajax_request_types.include?
(y.to_s) ? 1 : -1 } if request.xhr?
end

What it does is sort the content types the browser claims to accept so
that the ajax’ey ones are first. That seems to fix a lot of this sort
of problem.

Attribution for original code: http://codetunes.com/

Hope this helps with your problem.


#3

You’re looking at the form. And it’s not surprising it looks the same
because you wrote it to be that way. Here’s my guess, and I can’t tell
without (essentially) being you, watching your http requests, etc.
Here’s the flow of what happens when you submit your form:

You:
Think you did a PUT via XMLHttpRequest
Your Browser:
Creates an xhr object and actually POSTs the form with a hidden
field that contains
the n/v pair _method=put
Rails (not necessarily in this order):
Gets the request and sees it is a POST
Parses the headers, especially the Accept headers
Looks for the hidden field, to see how it should be routed
Sees it and routes to your update method
Your update method
does a respond_to |format|
respond_to
Looks through the Accept headers to see if it can figure out what
the browser
request is looking for.

In actual practice, you have to get a number of things exactly right
to make this happen. These are far easier to get right if you are
using Prototype but no matter. If you are using jQuery’s Ajax function
(jQuery is a great choice too), I’ve seen inconsistencies in how the
Accept header is set as compared to Prototype. The things that need to
go right are:

  1. Be sure before each Ajax call, the Accept header is set. E.g.:

jQuery.ajaxSetup({
‘beforeSend’: function(xhr) {xhr.setRequestHeader(“Accept”, “text/
javascript”)}
});

  1. In Rails, make sure your headers are sorted so that the
    embarrassing ones are
    parsed out early. I’m not sure why you have a frozen array – you
    didn’t mention
    a Rails version, but I have 2.3 running with that sorting snipped
    just fine.

If you are not sure which code is being executed, work backwards, and
put RAILS_DEFAULT_LOGGER.debug “rendering script” in your script
section and RAILS_DEFAULT_LOGGER.debug “rendering html” in your html
section. See if you are really running the code you think you are.

Finally, if you want to make this not happen again, write tests or
specs to ship requests with these headers to your controller and make
certain it renders the right content.

Hope this helps.


#4

This is a long one, but it should be easy to parse through.

Thank you for the reply. A couple of things:

  1. The problem is with Firefox, that’s what I’m using for development.
  2. The above code (and the code from the codetunes.com site) give the
    error “can’t modify frozen array”

I set it as a before filter in my blog_entries controller.

This does bring up a few things. Does this mean that the reason for
my problem is that Rails is not detecting that the browser is sending
and xhr request, and thus assuming that it is html? This is strange
to me because it’s literally the same form. I ran a test where I left
the form alone, and didn’t try to change to form so that it would PUT/
UPDATE, I left it as POST/CREATE, and Rails returned the js file, not
the html file.

In my javascript returned from the “create” method, I am modifying the
form that that it looks just the same as the form that is generated
when I am editing an entry. It may be something that I’m doing, I
don’t know. I’ll post the HTML and javascript (according to firebug)
for fun:

HTML of the create form before I submit it for the first time:
/* ---------------------------------- BEGIN */

Title

Post
Save & Unpublish Publish

/* ---------------------------------- END */

Here is the javascript that is returned that changes the form:
/* ---------------------------------- BEGIN /
$("#status").show();
$("#status").html(“Blog entry was successfully created.”);
$(".blockMe").unblock();
$("#status").fadeOut(3000);
if($("#submit_blog_entry").find("input[name
=‘method’]").length == 0)
$("#submit_blog_entry").find(“input
[name*=‘authenticity_token’]”).parent().prepend("<input type=“hidden
" name=”_method" value=“put” />");
else
$("#submit_blog_entry").find(“input[name=’_method’]”).val(“put”);
$("#submit_blog_entry").attr(“action”, “/blog_entries/50”);
var onsub = $("#submit_blog_entry").attr(“onsubmit”);
$(“form#submit_blog_entry”).removeAttr(“onsubmit”);
$(“form#submit_blog_entry”).removeAttr(“onSubmit”);
onsub = onsub.replace(/url:’/blog_entries/g, “url:’/blog_entries/
50”);
$(“form#submit_blog_entry”).submit(function(){ eval(onsub); } );
$(“form#submit_blog_entry”).attr(“onsubmit”, onsub);
alert(onsub);
/* ---------------------------------- END */

And here is the html of the form after that return:
/* ---------------------------------- BEGIN */

<form action="/blog_entries/50" class="new_blog_entry"

id=“submit_blog_entry” method=“post”>

Title

Post
Save & Unpublish Publish

/* ---------------------------------- END */

You may notice that the onsubmit attribute doesn’t contain anything,
however, a quick call using:

$(“form#submit_blog_entry”).attr(“onsubmit”);

yields:

$.ajax({data:$.param($(this).serializeArray()) +
‘&authenticity_token=’ + encodeURIComponent
(‘3ec895eb98a99ed6f134a6112d93005e50f2834b’), dataType:‘script’,
type:‘post’, url:’/blog_entries/50’}); return false;

Which is exactly what it’s supposed to be (or so it seems), when I
look at the onsubmit for the form generated from the partial for an
edit, it looks like

$.ajax({data:$.param($(this).serializeArray()) +
‘&authenticity_token=’ + encodeURIComponent
(‘3ec895eb98a99ed6f134a6112d93005e50f2834b’), dataType:‘script’,
type:‘post’, url:’/blog_entries/46’}); return false;

exactly the same, but this one actually returns the js format, not the
html

Anyone have any ideas? Thanks again for the help thus far.

Groove


#5

Awesome, thanks for the continued help. I tried the first thing you
suggested, putting in the default AJAX settings. Being an
inexperienced Rails programmer, I really don’t know what you mean by
number 2. How do I sort my rails headers? I’m fairly sure I’m
running Rails 2.2.2

A few more things that I tried: setting the ‘accepts’ hash to be
{ script: “text/javascript” }, and the ‘dataType’ string to be
“script”. Neither of these seem to work. I also tried doing the
RAILS_DEFAULT_LOGGER.debug “rendering html”, and I also added to it so
that I can see what some of the request headers:
RAILS_DEFAULT_LOGGER.debug “rendering script; accepts:#
{request.accepts}, method:#{request.method}”
and lo and behold: it’s rendering HTML, and simply passing right over
the js area. Here’s what the logger outputted:

The first submit, where the entry is initially saving:

Processing BlogEntriesController#create (for 127.0.0.1 at 2009-02-22
23:46:30) [POST]
Session ID: fun!
Parameters: {“authenticity_token”=>“fun!”, “blog_entry”=>
{“title”=>“asdf”, “content”=>“asdf”}}
[4;35;1mUser Columns (3.6ms) SHOW FIELDS FROM users
[4;36;1mUser Load (0.3ms) SELECT * FROM users WHERE (users.id
= 1) LIMIT 1
[4;35;1mBlog Load (0.9ms) SELECT * FROM blogs WHERE
(blogs.user_id = 1) LIMIT 1
[4;36;1mBlog Columns (3.5ms) SHOW FIELDS FROM blogs
[4;35;1mBlogEntry Columns (1.6ms) SHOW FIELDS FROM blog_entries
[4;36;1mSQL (1.6ms) BEGIN
[4;35;1mBlogEntry Create (0.4ms) INSERT INTO blog_entries
(last_edited_at, updated_at, title, published, blog_id,
summary, content, first_published_at, flag_count,
created_at) VALUES(NULL, ‘2009-02-23 04:46:30’, ‘asdf’, 0, 1, NULL,
‘asdf’, NULL, NULL, ‘2009-02-23 04:46:30’)
[4;36;1mSQL (0.5ms) COMMIT
rendering script; accepts:text/javascripttext/htmlapplication/xml*/*,
method:post
Rendering blog_entries/create
Completed in 50ms (View: 2, DB: 13) | 200 OK [http://localhost/
blog_entries]

Now the second submit, where it’s supposed to be putting (and seems to
be):

Processing BlogEntriesController#update (for 127.0.0.1 at 2009-02-22
23:48:59) [PUT]
Session ID: dogs
Parameters: {“commit”=>“Save”, “authenticity_token”=>“yay”,
“id”=>“64”, “blog_entry”=>{“title”=>“asdf”, “content”=>“asdf”}}
[4;35;1mUser Columns (16.9ms) SHOW FIELDS FROM users
[4;36;1mUser Load (2.2ms) SELECT * FROM users WHERE (users.id
= 1) LIMIT 1
[4;35;1mBlogEntry Columns (1.8ms) SHOW FIELDS FROM blog_entries
[4;36;1mBlogEntry Load (0.4ms) SELECT blog_entries.* FROM
blog_entries INNER JOIN blogs ON blog_entries.blog_id = blogs.id
WHERE (blog_entries.id = 64 AND ((blogs.user_id = 1)))
[4;35;1mSQL (0.1ms) BEGIN
[4;36;1mSQL (0.1ms) COMMIT
rendering html; accepts:text/htmlapplication/xml*/*, method:put <—
**** THERE’S THE PROBLEM ****
Redirected to #BlogEntry:0x246321c
Completed in 143ms (DB: 22) | 302 Found [http://localhost/blog_entries/
64]

And, since it redirects as stated, there’s also the rendering of the
[GET] after that. This is really stumping me. I’m beginning to
wonder if anyone else has actually tried this sort of thing and
succeeded. The thing is that I’m trying to be RESTful, so I’m trying
to use the model/controller links that are already there, because this
is the first app I’m building and I want to do it right.

I also thought that maybe it was because I was using the
remote_form_for helper, so I changed the form to use the
form_remote_tag helper. The same as before ensued. So for some
reason, when the form is being submitted the second time, jQuery
forgets to tell Rails that it accepts javascript? I really don’t
understand why this is happening :frowning:

So the question is, how do I get the correct accept header sent the
second time? And WHY THE HECK IS IT CHANGING!?! It’s the same freakin
form for goodness sake!!

Thank you again for bearing with me, as I’m new, and I hope we can get
this figured out.

GrooveAwesome, thanks for the continued help. I tried the first thing
you suggested, putting in the default AJAX settings. Being an
inexperienced Rails programmer, I really don’t know what you mean by
number 2. How do I sort my rails headers? I’m fairly sure I’m
running Rails 2.2.2

A few more things that I tried: setting the ‘accepts’ hash to be
{ script: “text/javascript” }, and the ‘dataType’ string to be
“script”. Neither of these seem to work. I also tried doing the
RAILS_DEFAULT_LOGGER.debug “rendering html”, and I also added to it so
that I can see what some of the request headers:
RAILS_DEFAULT_LOGGER.debug “rendering script; accepts:#
{request.accepts}, method:#{request.method}”
and lo and behold: it’s rendering HTML, and simply passing right over
the js area. Here’s what the logger outputted:

The first submit, where the entry is initially saving:

Processing BlogEntriesController#create (for 127.0.0.1 at 2009-02-22
23:46:30) [POST]
Session ID: fun!
Parameters: {“authenticity_token”=>“fun!”, “blog_entry”=>
{“title”=>“asdf”, “content”=>“asdf”}}
[4;35;1mUser Columns (3.6ms) SHOW FIELDS FROM users
[4;36;1mUser Load (0.3ms) SELECT * FROM users WHERE (users.id
= 1) LIMIT 1
[4;35;1mBlog Load (0.9ms) SELECT * FROM blogs WHERE
(blogs.user_id = 1) LIMIT 1
[4;36;1mBlog Columns (3.5ms) SHOW FIELDS FROM blogs
[4;35;1mBlogEntry Columns (1.6ms) SHOW FIELDS FROM blog_entries
[4;36;1mSQL (1.6ms) BEGIN
[4;35;1mBlogEntry Create (0.4ms) INSERT INTO blog_entries
(last_edited_at, updated_at, title, published, blog_id,
summary, content, first_published_at, flag_count,
created_at) VALUES(NULL, ‘2009-02-23 04:46:30’, ‘asdf’, 0, 1, NULL,
‘asdf’, NULL, NULL, ‘2009-02-23 04:46:30’)
[4;36;1mSQL (0.5ms) COMMIT
rendering script; accepts:text/javascripttext/htmlapplication/xml*/*,
method:post
Rendering blog_entries/create
Completed in 50ms (View: 2, DB: 13) | 200 OK [http://localhost/
blog_entries]

Now the second submit, where it’s supposed to be putting (and seems to
be):

Processing BlogEntriesController#update (for 127.0.0.1 at 2009-02-22
23:48:59) [PUT]
Session ID: dogs
Parameters: {“commit”=>“Save”, “authenticity_token”=>“yay”,
“id”=>“64”, “blog_entry”=>{“title”=>“asdf”, “content”=>“asdf”}}
[4;35;1mUser Columns (16.9ms) SHOW FIELDS FROM users
[4;36;1mUser Load (2.2ms) SELECT * FROM users WHERE (users.id
= 1) LIMIT 1
[4;35;1mBlogEntry Columns (1.8ms) SHOW FIELDS FROM blog_entries
[4;36;1mBlogEntry Load (0.4ms) SELECT blog_entries.* FROM
blog_entries INNER JOIN blogs ON blog_entries.blog_id = blogs.id
WHERE (blog_entries.id = 64 AND ((blogs.user_id = 1)))
[4;35;1mSQL (0.1ms) BEGIN
[4;36;1mSQL (0.1ms) COMMIT
rendering html; accepts:text/htmlapplication/xml*/*, method:put <—
**** THERE’S THE PROBLEM ****
Redirected to #BlogEntry:0x246321c
Completed in 143ms (DB: 22) | 302 Found [http://localhost/blog_entries/
64]

And, since it redirects as stated, there’s also the rendering of the
[GET] after that. This is really stumping me. I’m beginning to
wonder if anyone else has actually tried this sort of thing and
succeeded. The thing is that I’m trying to be RESTful, so I’m trying
to use the model/controller links that are already there, because this
is the first app I’m building and I want to do it right.

I also thought that maybe it was because I was using the
remote_form_for helper, so I changed the form to use the
form_remote_tag helper. The same as before ensued. So for some
reason, when the form is being submitted the second time, jQuery
forgets to tell Rails that it accepts javascript? I really don’t
understand why this is happening :frowning:

So the question is, how do I get the correct accept header sent the
second time? And WHY THE HECK IS IT CHANGING!?! It’s the same freakin
form for goodness sake!!

Thank you again for bearing with me, as I’m new, and I hope we can get
this figured out.

Groove


#6

Here’s the code for the partial that renders the form:

http://pastie.org/397999

Here’s the rjs that’s returned when the above form is submitted and
the create first happens, that’s supposed to be changing the form from
a create to an update (which is IS doing):

http://pastie.org/398003

Here’s the relavant javascript/jQuery in the main js file:

http://pastie.org/398008

Hope this helps. If you need more code, let me know.

Groove


#7

Awesome, thanks for the continued help. I tried the first thing you
suggested, putting in the default AJAX settings. Being an
inexperienced Rails programmer, I really don’t know what you mean by
number 2. How do I sort my rails headers? I’m fairly sure I’m
running Rails 2.2.2

A few more things that I tried: setting the ‘accepts’ hash to be
{ script: “text/javascript” }, and the ‘dataType’ string to be
“script”. Neither of these seem to work. I also tried doing the
RAILS_DEFAULT_LOGGER.debug “rendering html”, and I also added to it so
that I can see what some of the request headers:
RAILS_DEFAULT_LOGGER.debug “rendering script; accepts:#
{request.accepts}, method:#{request.method}”
and lo and behold: it’s rendering HTML, and simply passing right over
the js area. Here’s what the logger outputted:

The first submit, where the entry is initially saving:

Processing BlogEntriesController#create (for 127.0.0.1 at 2009-02-22
23:46:30) [POST]
Session ID: fun!
Parameters: {“authenticity_token”=>“fun!”, “blog_entry”=>
{“title”=>“asdf”, “content”=>“asdf”}}
[4;35;1mUser Columns (3.6ms) SHOW FIELDS FROM users
[4;36;1mUser Load (0.3ms) SELECT * FROM users WHERE (users.id
= 1) LIMIT 1
[4;35;1mBlog Load (0.9ms) SELECT * FROM blogs WHERE
(blogs.user_id = 1) LIMIT 1
[4;36;1mBlog Columns (3.5ms) SHOW FIELDS FROM blogs
[4;35;1mBlogEntry Columns (1.6ms) SHOW FIELDS FROM blog_entries
[4;36;1mSQL (1.6ms) BEGIN
[4;35;1mBlogEntry Create (0.4ms) INSERT INTO blog_entries
(last_edited_at, updated_at, title, published, blog_id,
summary, content, first_published_at, flag_count,
created_at) VALUES(NULL, ‘2009-02-23 04:46:30’, ‘asdf’, 0, 1, NULL,
‘asdf’, NULL, NULL, ‘2009-02-23 04:46:30’)
[4;36;1mSQL (0.5ms) COMMIT
rendering script; accepts:text/javascripttext/htmlapplication/xml*/*,
method:post
Rendering blog_entries/create
Completed in 50ms (View: 2, DB: 13) | 200 OK [http://localhost/
blog_entries]

Now the second submit, where it’s supposed to be putting (and seems to
be):

Processing BlogEntriesController#update (for 127.0.0.1 at 2009-02-22
23:48:59) [PUT]
Session ID: dogs
Parameters: {“commit”=>“Save”, “authenticity_token”=>“yay”,
“id”=>“64”, “blog_entry”=>{“title”=>“asdf”, “content”=>“asdf”}}
[4;35;1mUser Columns (16.9ms) SHOW FIELDS FROM users
[4;36;1mUser Load (2.2ms) SELECT * FROM users WHERE (users.id
= 1) LIMIT 1
[4;35;1mBlogEntry Columns (1.8ms) SHOW FIELDS FROM blog_entries
[4;36;1mBlogEntry Load (0.4ms) SELECT blog_entries.* FROM
blog_entries INNER JOIN blogs ON blog_entries.blog_id = blogs.id
WHERE (blog_entries.id = 64 AND ((blogs.user_id = 1)))
[4;35;1mSQL (0.1ms) BEGIN
[4;36;1mSQL (0.1ms) COMMIT
rendering html; accepts:text/htmlapplication/xml*/*, method:put <—
**** THERE’S THE PROBLEM ****
Redirected to #BlogEntry:0x246321c
Completed in 143ms (DB: 22) | 302 Found [http://localhost/blog_entries/
64]

And, since it redirects as stated, there’s also the rendering of the
[GET] after that. This is really stumping me. I’m beginning to
wonder if anyone else has actually tried this sort of thing and
succeeded. The thing is that I’m trying to be RESTful, so I’m trying
to use the model/controller links that are already there, because this
is the first app I’m building and I want to do it right.

I also thought that maybe it was because I was using the
remote_form_for helper, so I changed the form to use the
form_remote_tag helper. The same as before ensued. So for some
reason, when the form is being submitted the second time, jQuery
forgets to tell Rails that it accepts javascript? I really don’t
understand why this is happening :frowning:

So the question is, how do I get the correct accept header sent the
second time? And WHY THE HECK IS IT CHANGING!?! It’s the same freakin
form for goodness sake!!

Thank you again for bearing with me, as I’m new, and I hope we can get
this figured out.

Groove


#8

I’m not sure why you are using form_remote_tag, but the Javascript
helpers really only work with Prototype, not jQuery. You should be
using the AjaxForm jQuery plugin and form_for or form_tag. If you use
AjaxForm, you will have accomplished exactly one thing: Getting the
submit() event to use xhr. That’s step 1. Step 2 is customizing the
behavior of the submit event depending on whether it’s new (create) or
existing (update). For that, you can ship back script from Rails but
don’t use the Rails js helpers. You just can’t mix and match.

Read this: http://errtheblog.com/posts/73-the-jskinny-on-jquery

Not the newest, but still good reading for the Rails-jQuery issue.

I believe if you look at the DOM constructed from your existing code
in Firebug, you’ll discover that things aren’t quite lining up right
after a successful submit event.

Are you doing any other jQuery stuff to respond to submit, click, or
other events that could influence these behaviors?

–s


#9

Hm. Well I was trying to do this using as many rails helpers as
possible. The site I’m building should only use one javascript
framework, and jQuery is it. In the past, I’ve user the ajaxForm
jQuery plugin in the past with great success. I need to stop being so
idealistic. The reason I felt free to use rails js helpers was
because I’m using the jRails plugin (http://ennerchi.com/projects/
jrails) and it seems to be working. Is it still not ok to mix’n’match
do you think?

I’ll do my homework and get back to you.

Groove