Keep JavaScript responsible for enhancement and user feedback, not security. Validation and permission checks still belong on the PHP endpoint.
async function submitFeedback(form) {
const response = await fetch(form.action, {
method: 'POST',
body: new FormData(form),
headers: { 'Accept': 'application/json' }
});
const data = await response.json();
if (!response.ok) {
throw new Error(data.message || 'Unable to send feedback.');
}
return data;
}
The complete example below uses the same Fetch + FormData pattern so the copyable code matches the recommended approach.
FormData and sends them by POST. This avoids manually assembling and encoding every field.
async function ajaxFunction(myForm) {
const messageBox = document.getElementById('display-msg');
messageBox.textContent = 'Data processing...';
messageBox.style.display = 'inline';
try {
const response = await fetch('contactusck-ajax.php', {
method: 'POST',
body: new FormData(myForm),
headers: { 'Accept': 'application/json' }
});
const data = await response.json();
messageBox.textContent = data.message || 'Request completed.';
if (response.ok && data.status === 'OK') {
myForm.reset();
}
} catch (error) {
messageBox.textContent = 'Unable to send feedback right now.';
}
}
function hidemsg() {
document.getElementById('display-msg').style.display = 'none';
}
Basic of Feedback from
Part 2 HTML part of Feedback from
Part 3 JavaScript code of Ajax Feedback from
part 4 PHP script of Feedback from
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.