How should I use the "onreadystatechange" in an Ajax call when I'm using Ajax to write data in the database rather than retrieve data?
When I retrieve data, onreadystatechange
triggers a function that uses the data in some way. What kind of function should be triggered when I write to the DB?
Typically, when a user attempts to commit an action, it's useful to let them know if it succeeded or failed.
In the syncronous, page-level case, you already know this, you just output the result in the HTML response.
In the asynchronous, ajax case, you should get your server to return a message about the success or failure of the attempted write. This can either be a simple statement that it failed, or it can contain a detailed error message, or instructions on what they should do next.
The onreadystatechange function should receive this response and present it to the user.
The method for doing that depends on the format of your message.
In the simplest case, if it's a text/html string you can simply insert the XHR.responseText into the appropriate element on the page.
Another option which I find particularly convenient when using jquery is to return JSON notation which jquery will automatically make into a Javascript object which you can then reference to control some logic on the page (e.g. displaying the message, formatting it red if it's an error, pooling multiple messages into a log, etc.)