I've been learning how to update databases using jQuery and AJAX so you don't need to refresh the page when you submit something, but I'm a little bit stuck.
This example is quite simple - you click the "accept" button, and in the database, the column "accepted" is updated to be '1' instead of '0'. The jQuery function appears to be working correctly, but the value isn't updating. I've tried switching from data: 'id='+id
to the JSON data: { id: data }
approach, as well as just using .val()
instead of .serializeArray()
, but nothing seems to work. Any advice?
form.php
<form id='acceptGoal' method='post'>
<input type='hidden' name='id' value='$gid'>
<input type='button' id='submit'>Accept?</button>
</form>
/* $gid is the unique identifier of each individual item to be accepted */
script.js
$('#submit').click( function() {
var data = $("#id").val();
$.ajax({
type: "POST",
url: "accept.php",
datatype: "json",
data: { id: data }
});
});
accept.php
require 'core/initialize.php';
$query=$db->prepare("UPDATE goals SET accepted=:a WHERE id=:i");
$query->bindParam(":a", $a=1);
$query->bindParam(":i", $_POST['id']);
if ($query->execute()) {
echo "Done";
}
else {
echo "Something went wrong.";
}