Code below successfully processes and submits data to database. Is there anything else that needs to be included / considered?
PHP (note-process.php):
$data = array();
if ( (empty($_POST['name'])) || (empty($_POST['note'])) ) {
$data['success'] = FALSE;
$data['message'] = 'Name and note is required.';
} else {
// Process inputs and send to database using prepared statements
if ($stmt->execute())
{
$data['success'] = TRUE;
$data['message'] = 'Success! Name and note saved!';
} else
{
$data['success'] = FALSE;
$data['message'] = 'Note not saved. Try again later';
}
$stmt->close();
}
echo json_encode($data);
JS:
// Refresh note section every 2 seconds
function loadlink(){
$('#notes-box').load('note-refresh.php',function () {
$(this).unwrap();
});
}
loadlink(); // This will run on page load
setInterval(function(){
loadlink() // This will run after every 2 seconds
}, 2000);
// Submits form without refreshing page
$(document).ready(function () {
$("form").submit(function (event) {
$(".help-block").remove();
var formData = {
name: $("#name").val(),
note: $("#note").val()
};
$.ajax({
type: "POST",
url: "note-process.php",
data: formData,
dataType: "json",
encode: true,
})
.done(function (data) {
console.log(data);
if (!data.success) {
$("#error-box").append(
'<div class="help-block"><b>' + data.message + "</b></div>"
);
} else {
$("#error-box").append(
'<div class="help-block">' + data.message + "</div>"
);
}
})
<!-- How does the below get called? -->
.fail(function (data) {
$("#error-box").append(
'<div class="help-block">Could not reach server, please try again later.</div>'
);
});
event.preventDefault(); // Prevents the default action of an element from happening
});
});
HTML:
<div id="notes-box"></div>
<div id="error-box"></div>
<form action="note-process.php" method="POST">
<label for="name">Name</label>
<input type="text" id="name" name="name" placeholder="Full Name" />
<label for="note">Note</label>
<input type="text" id="note" name="note" placeholder="Note" />
<button type="submit" class="btn btn-success">Submit</button>
</form>