Reputation: 397
So, I thought I had this figured out, but, nope. So I could use any help here.
I have a html page. On that page I have three links. Each link representing a different piece of data. When a user clicks those links it will then post to a PHP page and carry that data to the PHP page. The PHP page will then update a database. Then, the PHP page will return the updated results BACK to the HTML page.
I know this requires JQuery, PHP, and Ajax.
Here is what I NOW have with some help from the boards:
HTML PAGE
<script src="_js/jquery-1.7.2.min.js"></script> <!-- Linking jQuery -->
<script>
$(document).ready(function () {
$('.answer').click ( function (e) {
var color = $(this).attr("data-color");
$.ajax({
url: 'mm.php',
type: 'POST',
data: '{ color: "'+color+'" }',
success: function (res) {
...
},
error: function (jqXHR) {
...
}
})
})
}
</script>
<title>M&M Poll</title>
</head>
<body>
<h1>VOTE FOR YOUR FAVORITE COLOR M&M</h1>
<h2>Click the M&M to vote</h2>
<div id="wrapper">
<div id="red" data-color="red" class="answer">
<a href="#"><img src="images/red.jpg" width="100%" /></a>
</div>
<div id="blue" data-color="blue" class="answer">
<a href="#"><img src="images/blue.jpg" width="100%" /></a>
</div>
<div id="green" data-color="green" class="answer">
<a href="#"><img src="images/green.jpg" width="100%" /></a>
</div>
<div id=rvotes>
TEST
</div>
<div id=bvotes>
TEST
</div>
<div id=gvotes>
TEST
</div>
PHP Page
<?php
function showVotes()
{
$sql = "SELECT * FROM mms";
$result = mysql_query($sql) or die(mysql_error());
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($showresult))
{
echo ("<br> M&M = ". $row["color"] . " has " . $row["votes"] . "votes <br>");
}
}
function addVote()
{
$sql= "UPDATE mms SET votes = votes+1 WHERE color = 'red'";
$result= mysql_query($sql) or die(mysql_error());
return $result;
}
?>
I know my database works. I just need to connect the HTML/AJAX/PHP
Any help is super appreciated!!
Upvotes: 0
Views: 126
Reputation: 9146
EDIT: New code, tested and works
HTML:
<html>
<head>
<title>M&M Poll</title>
<script src="//ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
</head>
<body>
<h1>VOTE FOR YOUR FAVORITE COLOR M&M</h1>
<h2>Click the M&M to vote</h2>
<div id="wrapper">
<div id="red" data-color="red" class="answer">
<a href="#">Red</a>
</div>
<div id="blue" data-color="blue" class="answer">
<a href="#">blue</a>
</div>
<div id="green" data-color="green" class="answer">
<a href="#">green</a>
</div>
<div id="rvotes">
TEST
</div>
<div id="bvotes">
TEST
</div>
<div id="gvotes">
TEST
</div>
</div>
<script>
$(document).ready(function ($) {
$('.answer').click ( function (e) {
e.preventDefault();
var color = $(this).data("color");
$.post('mm.php', { color: color}, function(data) {
console.log(data);
var obj = $.parseJSON(data);
$('#rvotes').html(obj.red);
$('#bvotes').html(obj.blue);
$('#gvotes').html(obj.green);
});
});
});
</script>
</body>
</html>
PHP:
<?php
$con=mysql_connect("localhost","root","");
mysql_select_db('mm_db') or die('Could not select database');
// Check connection
if (mysqli_connect_errno($con))
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
function showVotes()
{
$sql = "SELECT * FROM mms";
$result = mysql_query($sql) or die(mysql_error());
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
while ($row = mysql_fetch_array($showresult))
{
echo ("<br> M&M = ". $row["color"] . " has " . $row["votes"] . "votes <br>");
}
}
function jsonVotes()
{
$sql = "SELECT * FROM mms";
$result = mysql_query($sql) or die(mysql_error());
$showresult = mysql_query("SELECT * from mms") or die("Invalid query: " . mysql_error());
$color_votes = array();
while ($row = mysql_fetch_array($showresult))
{
$color_votes[$row['color']] = $row['votes'];
}
return $color_votes;
}
function addVote($color)
{
//If the color is one of the 3 we expect...
if($color == "red" || $color == "blue" || $color == "green") {
//NEVER put the variable in the query string, especially in production. Always use prepared statements -> http://php.net/manual/en/pdo.prepared-statements.php
$sql= "UPDATE mms SET votes = votes+1 WHERE color = '$color'";
$result = mysql_query($sql) or die(mysql_error());
return $result;
} else {
die();
}
}
//If this is an AJAX request
if(!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
//Do some sanitization since we're dealing with mysql instead of mysqli or PDO -> http://php.net/manual/en/book.pdo.php
$color = htmlspecialchars(trim(strtolower($_POST['color'])));
//If the vote was added successfully
if(addVote($color)) {
echo json_encode(jsonVotes());
}
}
?>
A few notes: look into PDO. Using mysql_*
is both bad practice and depreciated, but I wanted to stick as close to your code as I could so you could more easily understand it. Also look into $.post
instead of $.ajax
. Most people prefer it because it's shorter to type, but that's just a personal preference there.
Upvotes: 0
Reputation: 4043
Well, you're almost there, just going through it piece by piece - not necessarily putting in the code for you so you can figure it out for yourself and you'll learn more.
In your jQuery, you put in a type: 'post' which means the php file that is being called will contain data in $_POST.
If you're not sure what is in the $_POST array - print it out.
e.g.
print_r($_POST);
You may see an array being outputted that contains 'color'
Next - you'll need to insert it into your function. Ideally, your function takes in parameters in addVote() - because that's what it needs to input. This will also teach you methodologies of cleaning up information that's coming into your function in the long run so you're not in risk of sql infjections.
So a quick and dirty is:
// you already have this function - add a parameter
addVote ( $color ) { // blah }
addVote ( $_POST['color'] );
Now in your addVote() function, you aren't really a particular color in because everything is red, so you'll need to fix that.
$sql= "UPDATE mms SET votes = votes+1 WHERE color = '$color'";
Side note: You're also using mysql_query() which is btw outdated, people here will flog you if you continue using that - look up MySql PDO or mysqli (depending on who you ask). But that's a different thread.
Through these steps, you should see that the table has been updated, the next thing is to output the results, which is where you call in your other function - showVotes();
Hope that helps
Upvotes: 1