AJAX - The Complete Reference

(avery) #1

PART II


Chapter 8: User Interface Design for Ajax 363


Finally, in the save() function, the value of the input field used to collect the edit data
is saved back to the original field and transmitted to the server. You might desire to wait
until a satisfactory server response is received before updating the user page, but it appears
that many Ajax developers desire to add more speed and address commit errors later on if
they do so at all. We omit the transmission of the saved data in the code fragment here as it
uses a standard pattern similar to numerous examples in preceding chapters. However, do
note the comment and line of code addressing the possibility that the user may have entered
markup or script code for some cross-site scripting attack. Our goal here is for readers not to
quickly forget the security lessons of the previous chapter.

function save(elm, input)
{
/* escape the content to avoid XSS problems */
var message = input.value.replace(/<([^>]*)>/g, "<$1>");
/* set content to edited value */
elm.innerHTML = message;
/* save content via Ajax call to sendRequest()
see online version to get the details
or use your own approach
*/
}

A full running version of the click-to-edit pattern can be found at http://ajaxref.com/
ch8/clicktoedit.html and is previewed in Figure 8-8. This version allows you to try various
different editing appearances and invocations to see which you may prefer.
Internet Explorer supports a very direct way to implement the click-to-edit interface
idiom, the contenteditable attribute. If this attribute is set to true on a tag you wish to
edit, a similar process as discussed in the previous example can be performed with very
little code. The following code snippet should give you the idea of how easy it is to use this
browser-specific feature.

function contentEditableEdit(elm)
{
/* make sure we are not already editing */
if (elm.isContentEditable)
return;
/* turn on IE specific content editing */
elm.contentEditable = true;
/* register save callback onblur */
elm.onblur = function(){contentEditableSave(elm);};
}
window.onload = function ()
{
document.getElementById("doubleclickcontenteditable").ondblclick =
function(){contentEditableEdit(this);};
};

A full example using this approach can be found at http://ajaxref.com/ch8/clicktoedit-ie
.html.
Free download pdf