I have created a form that is processed using an AJAX request. The code I have here works fine as I get the form result message to appear. I now need to send the input data to the processor API. How do I do this?
<div class="col-md-6 col-sm-12">
<form id="my-form" class="contact-form margin-top-50">
<!-- for displaying the results of the sending operation -->
<span class="form-result"></span>
<input type="text" name="name" id="my-form-name" placeholder="Name" required>
<input type="email" name="email" id="my-form-email" placeholder="Email" required>
<input type="tel" name="phone" id="my-form-phone" placeholder="Phone">
<!-- a 'honeypot' field, to help us detect spam bots (use css to hide it) -->
<input type="text" name="website" id="my-form-website" value="" class="hidden">
<textarea name="message" id="my-form-message" rows="9" placeholder="Message"></textarea>
<button class="button-1 fade-in" type="submit" name="submit">
Get Started!
</button>
</form>
</div>
<script>
// AJAX FORM PROCESSING
$('#my-form').on('submit', function(e){
e.preventDefault();
var form = $(this);
$.ajax({
type: 'POST',
// use the same url here as the 'pattern' in your route
url: 'api/form',
data: form.serialize(),
success: function(result){
// form data successfully reached form processor api
if(result.success){
// message successfully sent
form.find('.form-result').text('Your message was sent successfully - thank you!');
} else {
// an issue was encountered
if(result.errors == undefined || result.errors == null || result.errors.length == 0){
// no validation errors - an email sending error was encountered
form.find('.form-result').text(result.msg);
} else {
// a validation error was encountered
var msg = "Please note: <br>";
if(result.errors.indexOf('name') != -1){
msg += "Name field must not be empty. <br>";
}
if(result.errors.indexOf('email') != -1){
msg += "Email field must contain a valid email. <br>";
}
if(result.errors.indexOf('website') != -1){
msg += "You seem to be a robot. <br>";
}
form.find('.form-result').html(msg);
}
}
},
error: function(result){
// the form was unable to reach processor api
form.find('.form-result').text('Error '+ result.status + ' - unable to process form: ' + result.statusText);
},
dataType: 'json'
});
});
</script>