Using Jeditable for inline editing
Using the Jeditable plugin for jQuery enables inline editing of a block of text. This makes it easy to take a static view and simply drop in editability. Say we start with the following HTML:
<label>Name:</label> <span class="employeeName">Ben Scott</span><br/> <label>Rating:</label> <span class="employeeRating">Highly awesome</span>
We want to be able to edit the employeeName and employeeRating spans. We need two actions (asssuming an MVC framework) to update the name and rating. The URLs might be something like /employee/set_name/{id} and /employee/set_rating/{id}. Each action should accept HTTP POST, take the new value in $_REQUEST['new_value'] or similar, and return a HTTP status of 200 on success and 500 on failure, with the error message in the response. For example, using Slab (my PHP5 MVC framework, in development) the set_name action might be like this:
class EmployeeController extends AppController {
function set_name($id) {
$this->Employee->save(array(
'id' => $id',
'name' => $this->data['new_value']);
));
return $this->ajaxSuccess($this->data['new_value']);
}
}
Slab catches uncaught exceptions and returns an AJAX failure with the exception message as the body of the response.
To hook up the fields to the actions, modify the HTML to include the URLs to the actions. While this means the markup has behavioural elements and isn’t purely presentational (and has a non-standard attribute), it makes the script a bit simpler and easy to move into a static .js file, and is a quick way to get a page working.
<label>Name:</label> <span class="employeeName" editUrl="/employee/set_name/7">Ben Scott</span><br/> <label>Rating:</label> <span class="employeeRating" editUrl="/employee/set_rating/7">Highly awesome</span>
Now for the script itself:
$(function(){
$('.employeeName, .employeeRating').editable(
function(value, settings) {
return $.ajax({
url: $(this).attr('editUrl'),
data: { 'new_value': value },
async: false,
type: 'post'
}).responseText;
}, {
indicator: 'Saving...',
tooltip: 'Click to edit',
onblur: 'submit'
}
);
});
The first argument is a function that returns the new value of the field. This is important when doing things like replacing line breaks with <br/> which we’re not worrying about, but it also gives us the ability to write our own AJAX code. By default Jeditable makes assumptions about how the update is done. The async option in the call to $.ajax() blocks until the call returns, and lets the function return the response of the AJAX call. The second argument are options to set some text to show while calling the update function, the tooltip to display when hovering over the span, and to submit changes on blurring the input which makes it seem a bit more usable when there are multiple fields.