So, I've been practicing with PDO, see my earlier asked question and now I am stuck at the following point:
I want to update the database variables without pushing on a button, and in my opinion is it best doable via AJAX.
A few codes: General.JS
var timeoutId;
$('form input').on('input propertychange change', function() {
console.log('Invoer bewerking');
clearTimeout(timeoutId);
timeoutId = setTimeout(function() {
// Runs 1 second (1000 ms) after the last change
saveToDB();
}, 1000);
});
function saveToDB()
{
console.log('Opslaan naar Database');
form = $('.formulier24');
$.ajax({
url: "ajax2.php",
type: "POST",
data: form.serialize(), // serializes the form's elements.
beforeSend: function(xhr) {
// Let them know we are saving
$('.HowAbout').html('Opslaan...');
},
success: function(data) { console.error(data) ;
var jqObj = jQuery(data); // You can get data returned from your ajax call here. ex. jqObj.find('.returned-data').html()
// Now show them we saved and when we did
var d = new Date();
$('.HowAbout').html('Opgeslagen om: ' + d.toLocaleTimeString());
},
});
}
// This is just so we don't go anywhere
// and still save if you submit the form
$('.formulier24').submit(function(e) {
saveToDB();
e.preventDefault();
});
ajax.php FILE:
<?php
include('verbinding.php');
if(isset($_POST['formulier24'])) {
$sql = "UPDATE INTO evenement SET username = :username, hours = :hours";
$parameters = array($_POST["username"], $_POST["hours"]);
try {
$stmt = $conn->prepare($sql);
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':hours', $_POST['hours']);
$result = $stmt->execute($parameters);
$return = "Updated data successfully!";
} catch (PDOException $e) {
$return = "Could not update data! Error: " . $e->getMessage();
}
header("Content-Type: application/json");
echo json_encode($return);
}
?>
The connection file (verbinding.php) is 100% working. I think I made a fault in the ajax.php file but I dont know where. Please let me know what I did wrong, because I do not get the Saved at time date-mention and it does not save in the database. Thanks in advance!