It seems this should be a simple thing to do but something is still going wrong. I am using the code of the top answer on this page: jQuery Ajax POST example with PHP
When I submit the form, instead of passing that data to the upvote.php and having it edit the database accordingly, it redirects me to /upvote.php?bar=hfAb1he49kk. It is taking the data that I need & redirecting to the php page and adding the data the url. Why is it doing that?
PHP
<?php
// Create connection
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$result = mysqli_query($con,"SELECT * FROM videos ORDER BY votes DESC");
while($row = mysqli_fetch_array($result)) {
echo "<div class='entry'>";
$id = $row['id'];
echo "<form action='upvote.php'>
<input type='hidden' name='bar' id='bar' value='" . $id . "' />
<input type='submit' value='upvote'/>
</form>";
echo '<iframe width="560" height="315" src="https://www.youtube.com/embed/' . stripslashes($row['id']) . '" frameborder="0" allowfullscreen></iframe>';
echo $row['votes'];
echo "</div>";
}
?>
JQuery
<script>
var request;
// bind to the submit event of our form
$(form).submit(function(event){
if (request) {
request.abort();
}
// setup some local variables
var $form = $(this);
// let's select and cache all the fields
var $inputs = $form.find("input, select, button, textarea");
// serialize the data in the form
var serializedData = $form.serialize();
// let's disable the inputs for the duration of the ajax request
// Note: we disable elements AFTER the form data has been serialized.
// Disabled form elements will not be serialized.
$inputs.prop("disabled", true);
// fire off the request to /form.php
request = $.ajax({
url: "/upvote.php",
type: "post",
data: serializedData
});
// callback handler that will be called on success
request.done(function (response, textStatus, jqXHR){
// log a message to the console
console.log("Hooray, it worked!");
});
// callback handler that will be called on failure
request.fail(function (jqXHR, textStatus, errorThrown){
// log the error to the console
console.error(
"The following error occured: "+
textStatus, errorThrown
);
});
// callback handler that will be called regardless
// if the request failed or succeeded
request.always(function () {
// reenable the inputs
$inputs.prop("disabled", false);
});
// prevent default posting of form
event.preventDefault();
});
</script>
upvote.php
<?php
$con=mysqli_connect("localhost","root","root","test");
// Check connection
if (mysqli_connect_errno()) {
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
$bar = $_POST['bar'];
mysqli_query($con,"UPDATE videos SET votes = votes + 1 WHERE id = '" . $bar . "'");
mysqli_close($con);
?>