Return value Ajax post

Im using Ajax to send values ​​to a PHP script that writes some value to the 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 action=vote_down, a script to vote script.

I already forbid the user to vote more than once, registering a vote there against this username and identifier in vote.php, and if there the username and identifier are already in the database against the same record, I do not add the vote to the database.

I personally believe that a database request for each page load to check whether a user has already been voted can be quite intense, there are many places to vote on one page.

, , , , - vote.php, , .

?

+5
2

JSON

, :

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

JS- :

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;
});

vote.php :

// 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



.

+2

All Articles