A form is a really interesting element in javascript or jquery (in this case).
Here’s my problem:
JS:
const themeFolder = object_name.templateUrl;
const urlAjax = themeFolder + '/FormHandler.php';
const form = $('#contact-form');
const outputmessage = $('.output-message');
form.submit(function(e) {
e.preventDefault();
$.ajax({
type: 'post',
url: urlAjax,
method: form.attr('method'),
data: form.serialize() + '&submit=true',
success: function (result) {
console.log(result);
outputmessage.append('<p>A message was sent successfully!</p>');
}
});
});
PHP:
if ($ok == true && isset($_POST['submit']) && empty( $honeypot )) {
$json_tidy = json_encode($_POST);
echo $json_tidy;
} else {
echo 'something wrong';
}
Now, what I’m not getting is the fact that I can send the same form multiple times with the same values but I’m not finding a solution to send my form only once and disable the form right after having done that.
Probably I’m overthinking but for example, the json_tidy will post this result:
{"fname":"ma","lname":"ma","email":"[email protected]","message":"ciao","honeypot":"","submit":"true"}</body>
Which doesn’t make a lot of sense for me.
Plus in this case, I’m struggling in finding a value to identify as a counter for how many times I will send a form.
I can use return true and false, right after the form.submit(function(e) {} and at the and of the javascript, but it will only avoid to my js script to run and fire the php script, which is in my form:
<form id="contact-form" name="contact-form" action="{{ theme.link }}/FormHandler.php" method="POST">
I’m wondering if anyone else had the same problem in the past
2
Answers
How about a boolean variable?
or:
You can remove the
submit
event handler just after sending the form, so the form won’t be sent again.Depending on the jQuery version you are using, you can do that with
Or:
Another option is to disable the submit button and, optionally, the input fields: