When the submit button is clicked on the form that I have set up, it goes though the PHP script I have set up fine and delivers the appropriate email. The JS script I have to validate input and AJAX works fine, but only with input validation. The AJAX request isn't returning anything.
Here is my HTML - the contact form. This all works well by itself and everything is inputted.
<form id="contact-form" method="post" action="./scripts/php/contactform.php" role="form">
<h3 class="h1 text-center">Any questions or feedback? Please let us know here!</h3>
<div class="row justify-content-center">
<div class="messages"></div></div>
<div class="row justify-content-center">
<div class="form-group col-md-4">
<label for="inputName">Name</label>
<input type="text" class="form-control" id="inputName" name="name" placeholder="Name" required="required" data-error="Your name is required.">
<div class="help-block with-errors"></div>
</div>
<div class="form-group col-md-4">
<label for="inputEmail">Email</label>
<input type="email" class="form-control" id="inputEmail" name="email" placeholder="Email" required="required" data-error="A valid email address is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row justify-content-center">
<div class="form-group col-md-8">
<label for="inputSubject">Subject</label>
<input type="text" class="form-control" id="inputSubject" name="subject" placeholder="Subject" required="required" data-error="A subject is required.">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="row justify-content-center">
<div class="form-group col-md-8">
<label for="inputMessage">Message</label>
<textarea class="form-control" id="inputMessage" name="message" placeholder="Message" required="required" data-error="Please enter a message to send to us."rows="5"></textarea>
<div class="help-block with-errors"></div>
</div>
<div class="row justify-content-center">
<div class="form-group col-md-8 text-center">
<button class="btn btn-primary btn-block" type="submit" id="submit" name="submit">Submit</button>
</div>
</div>
</form>
Here is the PHP script. This also works fine, with a possibility of the AJAX response section at the bottom, although it should work. The data I need to go to the JS script is the $responseArray
data in the try/catch blocks.
<?php
if(isset($_POST["submit"])) {
// Email variables
$from = $_POST["email"];
$to = "mailtoaddress";
// Other form data
$name = $_POST["name"];
$subject = $_POST["subject"];
$message = $_POST["message"];
// Fields translated to human-readable English
$fields = array("name" => "Name", "email" => "Email", "subject" => "Subject", "message" => "Message");
// Status messages
$success = "Contact form has been successfully submitted and we will get back to you as soon as possible!";
$error = "There was an error submitting the form. Please try again later.";
// To debug turn to "E_ALL & ~E_NOTICE", else 0.
error_reporting(0);
try {
if(count($_POST) == 0) throw new \Exception("Form is empty"); // Throw error if form is empty
// Email header
$header = "From: ".$name."<".$from.">\r\n";
$txt = "You have recieved an email from ".$name." (".$from.") via the website contact form.\n\nMessage: \n".$message; // Compile the message text
mail($to, $subject, $txt, $header); // Send mail
$responseArray = array("type" => "success", "message" => $success); // Create the success response
} catch (\Exception $e) {
$responseArray = array("type" => "danger", "message" => $error); // Create the response if something failed
}
// If requested by AJAX request return JSON response
if (!empty($_SERVER["HTTP_X_REQUESTED_WITH"]) && strtolower($_SERVER["HTTP_X_REQUESTED_WITH"]) == "xmlhttprequest") {
$encoded = json_encode($responseArray);
header("Content-Type: application/json");
echo $encoded;
}
// Otherwise just display the message
else {
echo $responseArray["message"];
header("Location: {$_SERVER["HTTP_REFERER"]}");
}
}
?>
And finally, the JS script. Everything just stops working once inside the AJAX request function. It may be a consequence of the PHP response, but I'm not sure.
$(function () {
// Initialize the validator
$('#contact-form').validator();
// On submission
$('#contact-form').submit(function (e) {
// If the validator will allow submission
if (!e.isDefaultPrevented()) {
var url = "../php/contactform.php";
$.ajax({
type: "POST",
url: url,
data: $(this),
dataType: 'json',
success: function (data) {
alert('working');
// Apply the message type
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// Compose alert HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
if (messageAlert && messageText) {
// Inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// Reset form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
});
What should happen is that the form data should be sent in an email, which already happens, and then a Bootstrap alert box should pop up replacing the .messages
div, which doesn't work. I have tested the alert box and it works fine on its own.
I am also open to different solutions - it doesn't have to be structured specifically this way.
Thank you very much for the help!
Edit: The error is TypeError: $.ajax is not a function
. The jQuery input should be fine, but here it is:
<script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script>