tags:

views:

33

answers:

2

Im using Ajax to send values to a PHP script which writes some value to a database:

$.ajax({
    type: "POST",
    data: "action=vote_down&id="+$(this).attr("id"),
    url: "vote.php",
    success: function(msg) {
        $("span#votes_count"+the_id).fadeOut();
        $("span#votes_count"+the_id).html(msg);
        $("span#votes_count"+the_id).fadeIn();                      
    }
});

As you can probably tell from the action=vote_down the script is for a voting script.

Im already preventing the user from voting more than once by logging there vote against there username and ID in vote.php and if there username and ID is already in the DB against the same post then I dont add the vote to the DB.

I personally think that querying the database on each page load to check if the user has already voted could be quite intensive, there are many places to vote on a single page.

So instead i'll show the user the voting option, but when they vote I want to some how return a value from vote.php to say they have already voted.

Any ideas for the best approach to this?

+1  A: 

This should put you in the right direction...

http://forum.jquery.com/topic/jquery-ajax-and-php-variables

I would parse back a boolean false if they have posted already, or the id of the vote if they were successful (for styling / adding the html message).

Gareth
+1  A: 

Use JSON

If this is your file to show the voting form:

<div id='voteform-div'>
 <form id='voteform'>
   Your form elements and a submit button here.
 </form>
</div>

Your JS code look like this:

jQuery('#voteform').live('submit',function(event) {
    $.ajax({
        url: 'vote.php',
        type: 'POST',
        data: "action=vote_down&id="+$(this).attr("id"),
        dataType: 'json',
        success: function( messages) {
            for(var id in messages) {
                jQuery('#' + id).html(messages[id]);
            }
        }
    });
    return false;
});

your vote.php should be something like this:

// Get data from $_POST array.

if( Already voted ) {

  // It will replace the id='voteform-div' DIV with error message
  $arr = array ( "voteform-div" => "you have already voted." ); 

} else {

 // Store vote in database

  // It will replace the id='voteform-div' DIV with confirmation message
  $arr = array ( "voteform-div" => "Yor vote is submitted. Thanks" );

}

echo json_encode( $arr ); // encode array to json format



For more detail on this look at this question.

NAVEED