Leonard Farneth
Leonard Farneth

Reputation: 11

I need to create a "vote" button that does not refresh the page

Hi I am building a video voting website that allows voting on videos. I want the user to be able to vote without interrupting the play of the video.

here is the snip I am using.

if ($_POST['vote']) {
    $sql = mysql_query("UPDATE videos SET vid_votes=vid_votes+1 WHERE vid_id=$vid_id"); 
}
$votebutton ="<form action='index.php?id=$vid_id' method='post' enctype='multipart/form-data'><input name='vote' type='hidden' id='vote' value='$vid_id'><input type='submit' name='Submit' value='Vote for it!' /></form>";

I echo out the vote or not vote based on a query of whether or the logged in voter already voted today.

This script logs a vote and returns the user to the video he was watching. More scripting will change this to an unvote button if the user has already voted within a day. However my main concern is How can I get this button to run the script without restarting the video?

Upvotes: 1

Views: 1097

Answers (1)

Brad
Brad

Reputation: 163622

I would do this with jQuery. You definitely don't have to use jQuery, but it wraps up AJAX calls nicely, and makes them work in a standard way across several platforms.

First, you need to get jQuery loaded. You can load this from a CDN:

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>

Next, in your JavaScript, just make a .post() call to your existing PHP script:

$.post('yourscript.php', 
    {vid_or_whatever: 12345},
    function (data, textStatus, jqXHR) {
        /* Handle the response data here. */
    }
);

You can find more details on this method here: http://api.jquery.com/jQuery.post/

Finally, make sure you're using prepared queries with PDO, server-side. That way, you can avoid SQL injection vulnerabilities.

Upvotes: 1

Related Questions