How do I efficiently write a "toggle database value" function in AJAX?

Posted by AmbroseChapel on Stack Overflow See other posts from Stack Overflow or by AmbroseChapel
Published on 2010-05-01T03:46:33Z Indexed on 2010/05/01 3:57 UTC
Read the original article Hit count: 320

Filed under:
|
|
|
|

Say I have a website which shows the user ten images and asks them to categorise each image by clicking on buttons. A button for "funny", a button for "scary", a button for "pretty" and so on. These buttons aren't exclusive. A picture can be both funny and scary.

The user clicks the "funny" button. An AJAX request is sent off to the database to mark that image as funny. The "funny" button lights up, by assigning a class in the DOM to mark it as "on".

But the user made a mistake. They meant to hit the next button over. They should click "funny" again to turn it off, right?

At this point I'm not sure whats the most efficient way to proceed.

The database knows that the "funny" flag is set, but it's inefficient to query the database every time a button is clicked to say, is this flag set or not, then go on with a second database call to toggle it.

Should I infer the state of the database flag from the DOM, i.e. if that button has the class "on" then the flag must be set, and branch at that point?

Or would it be better to have a data structure in Javascript in the page which duplicates the state of each image in the database, so that every time I set the database flag to true, I also set the value in the Javascript data to true and so on?

© Stack Overflow or respective owner

Related posts about AJAX

Related posts about JavaScript