Where can I save my PHP-Files for AJAX?

Okay, I’ll try to explain :smile:

Here’s the javascript that triggers my AJAX script.
I’m handing over the serialized form data and call a custom Kirby route.

$('#form').on('submit', function(e) {
  e.preventDefault();
  var data = $(this).serialize();
  $.ajax({
    type: "POST",
    dataType: "json",
    url: 'api/form/validate',
    data: data,
    success: function(data) {
      // your logic here
    },
  });
});

My custom Kirby route inside site/config.php looks like this:

c::set('routes', array(
  array(
    'pattern' => 'api/form/validate',
    'method' => 'POST',
    'action' => function() {
      $data = validateForm(kirby()->request()->data());
      return response::json($data);
    }
  )
));

The router now passes the form data to the validateForm function which will handle it.

For the validateForm function I created a plugin which lives inside the site/plugins directory.
Here’s the code (stripped down to the essentials)

function validateForm($data) {

  $errors = array();

  if(empty(get('name'))) {
    $errors[] = 'name';
  }
  ...

  if(empty($errors)) {
    $email = email($params);  // send email
  }

  if($email->send()) {
    $send = true;
  } else {
    $emailError = $email->error()->message();
  }

  $successMessage = 'E-Mail successfully sent';

  $data = array(
    'errors' => $errors,
    'successMessage' => $successMessage
  );

  return $data;
}

So the function gets the data, checks if the fields are valid/filled out and then either sends an email or returns an array of errors back to the javascript which then can be displayed in the form. Roundtrip done!

I hope this might come in handy! If anything is unclear, ask away.

9 Likes