views:

29

answers:

1

I have a web application which among other things contains a table of items created using an Ajax callback. A bunch of form fields at the top of the table allow me to filter the items that will be displayed in the table according to various criteria and show it.

Some parts of the table have lists of items with an [X] marked next to them that I can delete by clicking on those items.

Now, if I were doing this the non-ajax/javascript way, the page would receive a bunch of POSTed data fields and then would render the table accordingly. I can do this but I would also like to Ajaxify the entire setup. My questions are regarding this.

  1. How would I create the [X] button. A simple <a> would "work" but it's a GET modifying state so I don't want to do that. The way I'm doing it now is a tiny form with a hidden parameter than holds the item to be deleted and a styled submit button that's the [x]. If I ajaxify this, I can get the response and do the needful.

  2. How do I keep my backend DRY? I don't want to have two completely different bits of code for the Ajaxified version and the regular ones. What I'm doing right now is having the non-ajax version submit to a URL that changes the state and then redirects to the main page again (similar to a PRG type system). With the Ajax enabled, I simply call the URL and ignore the redirect but use the returned data to adjust the table. Is this the "right way"?

  3. Any other advice on graceful degradation on how to keep my backend DRY?

+3  A: 

I would put each row into it's own form (with method='POST'), and include a hidden field to say which item is to be deleted. The [X] would submit the form, and in the form's submit event, if no XmlHttpRequest is present simply submit the form to the server which would delete the item and redirect to the same page again (this is good practise to avoid a reload from resubmitting the delete POST).
If an XmlHttpRequest is present, set it up to POST with the id of the thing to delete and then remove the row if the request succeeded. You could set a flag in the AJAX request so that redirect doesn't happen, just a success (200 OK).

andrewmu
That's quite similar to what I'm doing now (as my question) indicates. Any gotchas that I should be wary about? Any comments on how the backend code should be organised?
Noufal Ibrahim
Well, this way doesn't require the backend do anything different for either form POSTs or AJAX POSTs, apart from returning OK or redirecting at the end. In fact I'd include a parameter in another hidden field in the form such as `<input type="hidden" name="redirect" value="<%= INSERT PAGE URL ON SERVERSIDE %>">` and only have the delete handler send a redirection if the redirect parameter is present. This will keep the action a bit cleaner and more RESTful.
andrewmu
Why more RESTful? That's an interesting point.
Noufal Ibrahim