This is the code I'm using to send a form to a php page and then sending an email. Somehow it's not working and I don't get why. The page just reloads (why?) and I cannot see any request being sent. (I'm using MAMP on macOS if this is a useful information). What's wrong here? Thank you for helping me out. PS: also, the page reloads when I click submit. Why and how can I prevent that?
HTML
<div id="form_container">
<form id="contact_form" enctype="multipart/form-data">
<div class="form-group">
<div class="row">
<div class="col">
<input name="name" type="text" class="form-control" placeholder="Name" id="inputName">
</div>
<div class="col">
<input name="surname" type="text" class="form-control" placeholder="Surname" id="inputSurname">
</div>
</div>
</div>
<div class="form-group">
<input name="email" type="email" class="form-control" id="inputEmail" placeholder="Email">
</div>
<br/>
<div class="form-group">
<input name="subject" type="text" class="form-control" id="inputSubject" placeholder="Subject">
</div>
<div class="form-group">
<textarea name="message" class="form-control" id="textArea" rows="4" placeholder="Write your message here"></textarea>
</div>
<div id="btn_container">
<button id="btn_send" name="submit" type="submit" class="btn btn-dark">SEND</button>
<div id="success_send" class="alert alert-success" role="alert">
SUCCESS
</div>
<div id="error_send" class="alert alert-danger" role="alert">
ERROR
</div>
</div>
</form>
</div>
JS
$( document ).ready(function() {
$('#contact_form').submit(function(event) {
$.ajax({
type: 'POST',
url: '../php/email.php',
data: $('#contact_form').serialize(),
success: function() {
$('#success_send').show();
},
error: function(){
$('#error_send').show();
}
});
});
});
PHP
<?php
if($_POST){
$name = $_POST['name'];
$surname = $_POST['surname'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$to = "xxxxxx@xxxx.xxx";
$subject = "Portfolio Mail - ".$subject;
$body = "Name: ".$name."\t".$surname."\nEmail: ".$email."\nMessage: ".$message;
$headers = "From: " . $email;
//send email
mail($to, $subject, $body, $headers);
?>