views:

158

answers:

3

I'm implementing a voting system like the one used by stackoverflow. It's working with ajax sending POST request to an url. I'd like a way to fail gracefully when javascript/ajax isn't supported or enabled, a GET like /voteup/id isn't even considered because i'm altering the database. What's the best solution? I'm either considering a form or simply removing the feature if js isn't enabled.

There are at least three related entries on SO but i can't insert more than one hyperlink

http://stackoverflow.com/questions/2015739/post-with-links-without-javascript

+3  A: 

Make the basic voting actions mini-forms, then use javascript to disable their posting action.

<form method=post action="hit-url">
   <input type=hidden name=vote value="1" />
   <input type=submit value="Vote Up" onSubmit="doVote(1);return false;" />
</form>
<form method=post action="hit-url">
   <input type=hidden name=vote value="-1" />
   <input type=submit value="Vote Down" onSubmit="doVote(-1);return false;" />
</form>

To replace these with links for javascript-enabled users:

<div id="voteupbutton">
   <form method=post action="hit-url">
      <input type=hidden name=vote value="1" />
      <input type=submit value="Vote Up" onSubmit="doVote(1);return false;" />
   </form>
</div>
<script>
   document.getElementById("voteupbutton").innerHTML="<a href='script:return false' onClick='doVote(1);return false;'>Vote up</a>";
</script>

I haven't tested the above. If you're using jQuery or some other framework, there will be more elegant ways of doing all of this.

Phil H
Is there a way to submit a form with a link?(Without images or javascript)
Spear
@Spear: what's wrong with using a GET request? you can re-direct to the proper URL from the server-side with a 30x HTTP response
Christoph
@Spear: Not without javascript. However, you can use javascript to modify the page dynamically and replace the button with a link. I'll modify the answer to show that.
Phil H
@Phil H: Yes, i'm using jquery, that will do the job, thank you :)
Spear
Probably the noscript tag could be helpful.
Spear
+1  A: 

The straightforward option is just a regular form POST, even if it is to the URL /voteup/id, and I'm not sure why you can't do that (or even the GET you mentioned).

Put onsubmit="return false" into the tag to prevent POSTing by users who do have JS enabled.

Karl B
Altering the database with a GET request is a bad practice.
Spear
A: 

While you can't use links to submit forms, you can certainly use links to trigger database actions if you want to, via the querystring. In no particular scripting language:

<===
if (querystring("v")) then {
 v.value.writeToDatabase
}
===>

<a href="vote.xxx?v=a">Vote A</a>, <a href="vote.xxx?v=b">Vote B</a>
graphicdivine