Sharing my full code at this point for full context (not including the form which essentially just calls to the page url on the ‘action’ attribute):
/controllers/contact.json.php:
<?php
return function($kirby, $pages, $page) {
if($kirby->request()->is('POST') && get('submit')) {
// check the honeypot
if(empty(get('website')) === false) {
go($page->url());
exit;
}
$data = [
'email' => get('email'),
'text' => get('text'),
];
$rules = [
'email' => ['required', 'email'],
'text' => ['required', 'minLength' => 3, 'maxLength' => 3000],
];
$messages = [
'email' => 'Please enter a valid email address',
'text' => 'Please enter a text between 3 and 3000 characters'
];
// authenticate as almighty
$kirby->impersonate('kirby');
// some of the data is invalid
if($invalid = invalid($data, $rules, $messages)) {
// the data is fine, let's send the email
} else {
try {
$kirby->email([
'template' => 'contact',
'from' => 'myemail@gmail.com',
'replyTo' => $data['email'],
'to' => 'myemail@gmail.com',
'subject' => 'Testing',
'data' => [
'text' => esc($data['text']),
]
]);
}
catch (Exception $error) {}
}
}
return [
'data' => $data ?? false,
'success' => $success ?? false
];
};
/templates/contact.json.php:
<?php
echo json_encode([
'data' => $data ?? false,
'success' => $success ?? false
]);
?>
js function:
$(form').on('submit', function(e) {
e.preventDefault();
// define some variables
var form = $(this);
// var url = form.attr('action');
var url = form.attr('action') + '.json';
var data = form.serialize();
$.ajax({
type: 'POST',
dataType: 'json',
url: url,
data: data,
// if the ajax call is successful ...
success: function(response) {
console.log(response);
// if registration was successful
if(response.success) {
console.log(response.success);
}
// if registration failed
if(response.error) {
console.log(response.error);
}
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
});