Question

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?

Was it helpful?

Solution

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.)

OTHER TIPS

It's possible that I don't quite understand your question, but I don't think there's any particular reason to use onreadystatechange much differently. Whether you're posting data or retrieving data, onreadystatechange tells you what stage the server is at in responding to the request - when the ready state becomes 4, the full response is ready. In the case of posting data, what you do with that response is a little different (presumably there is something in the response that you would want to check to make sure that the write was successful), but that shouldn't change how onreadystatechange itself works.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top