I'm a beginner attempting to create a HTML webpage. I'm using a free online template and trying to create a Contact Page. The contact calls a php script to send an email of the captured fields. I can get this to work when I send the email as pure php with no javascript or ajax. However when I try to use the javascript with the ajax code, the contents of the web form are not being passed. Two near identical issues have been raised here but I am finding the javascript to complicated for myself to understand as a beginner. The slight differences in the js has resulted in hours of trying to resolve without success.
js deleting submitted form data
PHP form post data not being received due to jQuery
The HTML code is
<div class="col-md-4 col-sm-12">
<div class="contact-form bottom">
<h2>Send a message</h2>
<form id="main-contact-form" name="contact-form" method="post" action="sendemail.php">
<div class="form-group">
<input type="text" name="name" class="form-control" required="required" placeholder="Name">
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" required="required" placeholder="Email Id">
</div>
<div class="form-group">
<textarea name="message" id="message" required class="form-control" rows="8" placeholder="Your text here"></textarea>
</div>
<div class="form-group">
<input type="submit" name="submit" class="btn btn-submit" value="Submit">
</div>
</form>
</div>
The PHP script is called sendemail.php
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'Thank you for contact us. As early as possible we will contact you '
);
$name = @trim(stripslashes($_POST['name']));
$email = @trim(stripslashes($_POST['email']));
$subject = @trim(stripslashes($_POST['subject']));
$message = @trim(stripslashes($_POST['message']));
$email_from = $email;
$email_to = 'email@email.com';
$body = 'Name: ' . $name . "
" . 'Email: ' . $email . "
" . 'Subject: ' . $subject . "
" . 'Message: ' . $message;
$success = @mail($email_to, $subject, $body, 'From: <'.$email_from.'>');
echo json_encode($status);
die;
The javascript is as follows
// Contact form
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
$.ajax({
url: $.post(this).attr('action'),
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
}).done(function(data){
form_status.html('<p class="text-success">Thank you for contacting us. We will reply as soon as possible.</p>').delay(3000).fadeOut();
});
});
There are two issues, the first being that the form data doesnt pass when using the javascript code. The second is that it displays the message twice and sends two emails. I think the second issue is related to the php script calling the function again.
Help & guidance will be really appreciated, I am a beginner only attempting a small challenge.