Adding Ajax to an existing HTML form
Choose one interaction that benefits from updating part of the page, such as a catalogue lookup. Keep the ordinary form and server response working. The additional JavaScript should improve that route without becoming the only way to complete the task.
Preserve the ordinary request
Give the form a real action and submit control. Validate and authorise requests on the server whether they came from a page load or a script. Only cancel the normal submission once the script has successfully set up its alternative. A failed lookup should leave the original fields available, with an ordinary submit route the visitor can still use.
Detect the available request object
Test for XMLHttpRequest rather than guessing from the user-agent string. Internet Explorer 6 commonly requires the Microsoft.XMLHTTP ActiveX object; creation can fail where ActiveX is disabled. Catch that failure and retain normal submission. Keep requests on the same origin, and use asynchronous operation so waiting for the server does not freeze the browser interface.
Define the response before writing the display code
Decide whether the endpoint returns plain text, XML or a controlled HTML fragment, and send a matching content type and encoding. Check completion and HTTP status before using a response. Insert untrusted text with DOM text nodes. Do not treat arbitrary returned text as JavaScript or insert user-submitted markup into the document without appropriate escaping.
Handle slow and out-of-order replies
Show that a request is pending and provide a timeout using a timer and abort. If the visitor changes a search term twice, attach a sequence number to each request and ignore a reply for an older term. Aborting a request does not guarantee the server stopped processing it. For submissions that change data, use server-side duplicate protection before offering an automatic retry.
Test the complete browser interaction
Try Internet Explorer 6, Firefox and the other browsers the site supports, both with and without scripting. Delay a response, return a server error and navigate away during a request. Check keyboard focus and whether the result is apparent to assistive software. Preserve ordinary result-page links so visitors can bookmark or send a useful address even when the enhanced interaction stays on one page.
Test the non-scripted route after every change to the endpoint. It is part of the application, and it is the route available when request-object creation or script loading fails.