Last active
May 31, 2017 07:29
-
-
Save adriandmitroca/c98623b8a69747a1d1a0ed513addfc90 to your computer and use it in GitHub Desktop.
Snippet for quick contact form handling with vanilla PHP/JS + $.ajax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$subject = 'Temat wiadomości'; | |
$recipient = 'recipient@example.com'; | |
$output = [ | |
'success' => 'Dziękujemy za wiadomość.', | |
'error' => 'Coś poszło nie tak. Spróbuj ponownie.', | |
]; | |
$data = [ | |
'name' => $_POST['name'], | |
'company' => $_POST['company'], | |
'email' => $_POST['email'], | |
'message' => $_POST['message'], | |
'honeypot' => $_POST['honeypot'], | |
]; | |
if ($data['honeypot'] === 'true') { | |
echo json_encode([ | |
'success' => 'true', | |
'message' => $output['error'], | |
]); | |
return; | |
} | |
$messageBody = " | |
<strong>Imię i nazwisko:</strong> ${data['name']}<br/> | |
<strong>Firma:</strong> ${data['company']}<br/> | |
<strong>E-mail:</strong> ${data['email']}<br/> | |
<strong>Wiadomość:</strong> ${data['message']}<br/> | |
"; | |
$headers = 'From: sender@example.com' . "\r\n" . | |
'Reply-To: ' . $data['email'] . "\r\n" . | |
'X-Mailer: PHP/' . phpversion() . "\r\n" . | |
'Content-Type: text/html; charset=utf-8'; | |
$mail = mail($recipient, $subject, $messageBody, $headers); | |
echo json_encode([ | |
'success' => 'true', | |
'message' => $mail ? $output['success'] : $output['error'], | |
]); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
$('.js-contact-form').on('submit', (e) => { | |
e.preventDefault(); | |
const form = e.target; | |
const button = form.querySelector('button'); | |
const notification = form.querySelector('.form-output'); | |
const data = { | |
name: form.fullname.value, | |
company: form.company.value, | |
email: form.email.value, | |
message: form.message.value, | |
honeypot: form.rules.checked, | |
}; | |
$.ajax({ | |
url: `/form-handler.php`, | |
method: 'POST', | |
dataType: 'json', | |
data, | |
beforeSend() { | |
button.textContent = 'Wysyłanie...'; | |
notification.textContent = ''; | |
}, | |
success(response) { | |
button.textContent = 'Wyślij'; | |
notification.textContent = response.message; | |
form.reset(); | |
}, | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment