views:

155

answers:

2

I'll try to make this as simple a posible.

I just started working with jquery and don't know what's the best aproach to do what i want to do or if i'm completely wrong. I'm trying to make a simple "recommend" button to recomend articles but i want that once the user has recommended one article he can't recomend it again.

So far i got the button working and posting the data with the function $.post, and then, when the user has voted i disable the button so he can't post data again. The problem is, that if he reloads the page the button is enabled again (i'm controlling this serverside, but i want to disable the button client side also).

What would be the best aproach to detect from jquery if the user has recommended one article within the .ready function in order to do not bind the button event?

I can think of two viable solutions but none seems clean enough to me, the first would be to give a direfent ID to the button in the view if the recommendation is loaded with the model so that the event never binds. Or the other solution would be to make another ajax call in the document.ready to check if the article was already recomended.

A lot of sites have this kind of behavior (youtube for ex.) so there must be a better way to do this.

Some code:

this is my "button" in the view:

<% // Display the button %>
<%= Html.Image("/ECA/Content/Images/notchecked.png", new { id = "recommend"  })%>

And my jquery event bind:

    //Add click event to recommend the article
    $("img[id^='recommend']").click
    (
            function() {

                UpdateVote( 2);
            }
    );

My callback function:

var UpdateVoteCallBack=function(data) {
     $("#recommend")
 .attr('src','/ECA/Content/Images/checked.png');
     $("#recommend").unbind('click');

}
+1  A: 

I would check server side to see if the article has been recommended and send the appropriate class/id to the view and have a jquery function to disable any buttons with a cancelled class/id.

Rigobert Song
+2  A: 

When you draw the original server page, don't draw clickable buttons for articles that are already recommended - instead, draw a label saying "You like this!" or some such thing.

Have your client-side jQuery replace the button with this label in the callback, instead of just removing the click handler - this will give your user some feedback that their recommendation has been accepted.

Finally - make sure that for clients without Javascript, the actual button click or form submission is handled server-side, their recommendation is acknowledged, and when they get the resulting page it's got "I like this" instead of a button.

Remember that you should always try to use jQuery et al to enhance your website's underlying behaviour; make it work without any AJAX going on first, then add the bells & whistles afterwards.

Dylan Beattie