Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
How to submit form data with Ajax?
I need to apply backend behavior (PHP directives in my case) to an HTML <form>
.
The backend behavior I wish to apply to the form is in this pattern (behavior.php):
<?php
$name = $_POST['name']; # Required;
$email = $_POST['email']; # Required;
$to = 'example@example.com';
$subject = 'A new message from: ' . $name;
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=utf-8';
mail($to, $subject, $message, implode("\r\n", $headers));
?>
The way I know to do this is with this HTML pattern:
<form action="/behavior.php" method="POST">
Now I have a form that the default behavior of which is prevented with preventDefault()
so clicking the submit button will not cause form submission.
Therefore the HTML action
and method
became ineffective and I need to send the form's data with Ajax but according to the backend behavior (under behavior.php) where the relevant email address is stored.
In MDN "Using Fetch" I didn't find any code example with such a file reference.
1 answer
See the first example in this section:
const form = new FormData(document.getElementById('login-form'));
fetch('/login', {
method: 'POST',
body: form
});
To adapt this example to your code, you'll need to change the URL being provided to fetch
from '/login'
to the URL of your PHP behavior page—looks like that might be just '/behavior.php'
from your example. And of course you'll need to get the correct form DOM object to use in the FormData
constructor. This example uses an id
attribute on the form and the document.getElementById
function to do this, which is a nice way to do it but not the only way.
3 comment threads