PHP file upload with Ajax - php

I am working on a form where we need to upload the file. The form is processing with Ajax and the data is being posted on the email with no problem except file upload.
Now we want to allow user to upload multiple image files that will be stored on our server and we will get the link to the images in the email.
Please have a look at the codes below:
Form HTML code:
<div class="col-sm-12">
<div class="well">
<form id="ajax-contact" action="http://websitename.com/mailer.php" method="post" enctype="multipart/form-data">
<h2>Personal Details</h2>
<div class="login-wrap">
<div class="form-group">
<label class="control-label" for="name">Name</label>
<input name="name" placeholder="enter your name" id="name" class="form-control" type="text">
</div>
<div class="form-group">
<label class="control-label" for="tel">Telephone</label>
<input name="tel" placeholder="enter your telephone" id="tel" class="form-control" type="text">
</div>
<div class="form-group">
<label class="control-label" for="email">Email</label>
<input name="email" placeholder="enter your email" id="input-email" class="form-control" type="text">
</div>
<div class="form-group">
<label class="control-label" for="comments">Comments</label>
<textarea name="comments" placeholder="your comments" id="comments" class="form-control" type="text"></textarea>
</div>
</div>
<h2 style="margin-top:20px;">Product Details</h2>
<div class="login-wrap">
<div class="form-group">
<label class="control-label" for="make">Make/Brand</label>
<input name="make" placeholder="enter your make" id="make" class="form-control" required="" type="text">
</div>
<div class="form-group">
<label class="control-label" for="model">Model</label>
<input name="model" placeholder="enter your model" id="model" class="form-control" required="" type="text">
</div>
<div class="form-group">
<label class="control-label" for="reference">Reference Number</label>
<input name="reference" placeholder="enter your reference" id="reference" class="form-control" type="text">
</div>
<div class="form-group">
<label class="control-label" for="condition">Condition</label>
<select id="condition" name="condition" required="">
<option>Mint</option>
<option>Used</option>
</select>
</div>
<div class="form-group">
<label for="images">Upload Images</label>
<input id="images" name="images" multiple="" required="" type="file">
<p class="help-block">upload maximum 4 images</p>
</div>
<div class="form-group">
<label class="control-label" for="price">Expected Price</label>
<input name="price" placeholder="enter your price" id="price" class="form-control" required="" type="text">
</div>
<div class="checkbox">
<label>
<input value="" type="checkbox">
With Box
</label>
</div>
<div class="checkbox disabled">
<label>
<input value="" type="checkbox">
With Papers
</label>
</div>
</div>
<input value="Submit" class="btn btn-primary button" type="submit">
</form>
</div>
</div>
</div>
AJAX:
$(function() {
// Get the form.
var form = $('#ajax-contact');
// Get the messages div.
var formMessages = $('#form-messages');
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
// Serialize the form data.
var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: 'POST',
url: $(form).attr('action'),
data: formData
})
.done(function(response) {
// Make sure that the formMessages div has the 'success' class.
$(formMessages).removeClass('error');
$(formMessages).addClass('success');
// Set the message text.
$(formMessages).text(response);
// Clear the form.
$('#name').val('');
$('#email').val('');
$('#message').val('');
$('#tel').val('');
$('#make').val('');
$('#model').val('');
$('#reference').val('');
$('#condition').val('');
})
.fail(function(data) {
// Make sure that the formMessages div has the 'error' class.
$(formMessages).removeClass('success');
$(formMessages).addClass('error');
// Set the message text.
if (data.responseText !== '') {
$(formMessages).text(data.responseText);
} else {
$(formMessages).text('Oops! An error occured and your message could not be sent.');
}
});
});
});
PHP Form Processor:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$name = strip_tags(trim($_POST["name"]));
$name = str_replace(array("\r","\n"),array(" "," "),$name);
$email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$tel = filter_var(trim($_POST["tel"]));
$message = trim($_POST["message"]);
$make = trim($_POST["make"]);
$model = trim($_POST["model"]);
$reference = trim($_POST["reference"]);
$condition = trim($_POST["condition"]);
// Check that data was sent to the mailer.
if ( empty($name) OR !filter_var($email, FILTER_VALIDATE_EMAIL)) {
// Set a 400 (bad request) response code and exit.
http_response_code(400);
echo "Oops! There was a problem with your submission. Please complete the form and try again.";
exit;
}
// Set the recipient email address.
// FIXME: Update this to your desired email address.
$recipient = "myemail#mycompany.com";
// Set the email subject.
$subject = "New Contact form Submitted";
// Build the email content.
$email_content = "Name: $name\n";
$email_content .= "Tel: $tel\n";
$email_content .= "Email: $email\n";
$email_content .= "Message: $message\n";
$email_content .= "Make/Brand: $make\n";
$email_content .= "Model: $model\n";
$email_content .= "Reference: $reference\n";
$email_content .= "Condition: $condition\n";
// Build the email headers.
$email_headers = "From: $name <$email>";
// Send the email.
if (mail($recipient, $subject, $email_content, $email_headers)) {
// Set a 200 (okay) response code.
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
// Set a 500 (internal server error) response code.
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
// Not a POST request, set a 403 (forbidden) response code.
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

Related

Ajax form validation in php

Im trying to create ajax from with php validation, let explain with screenshot. while validating form im getting all error in same place…
what im trying to get is individual validation for field like below
And after form is submitted i want display success message at the top of form but im getting success message on all field
html form data (index.php)
<form id="first_form" method="POST" action="form.php">
<p class="form-message"></p>
<div class="mb-3">
<input type="text" class="form-control" id="name" name="name" placeholder="Name:">
<p class="form-message"></p>
</div>
<div class="mb-3">
<input type="tex" class="form-control" id="email" name="email" placeholder="Email:">
<p class="form-message"></p>
</div>
<div class="mb-3">
<input type="text" class="form-control" id="phone" name="phone" placeholder="Phone:">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="address" name="address" placeholder="Address:">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="subject" name="subject" placeholder="Subject:">
</div>
<div class="mb-3">
<input type="text" class="form-control" id="services" name="services" placeholder="Services:">
</div>
<div class="mb-3">
<textarea class="form-control" rows="5" id="message" name="message" placeholder="Leave Your Message..."></textarea>
</div>
<button type="submit" name="submit" id="submit" class="btn btn-primary">Submit</button>
js code:
$(document).ready(function() {
$("#first_form").submit(function(event) {
event.preventDefault();
name = $("#name").val();
email = $("#email").val();
phone = $("#phone").val();
address = $("#address").val();
subject = $("#subject").val();
services = $("#services").val();
message = $("#message").val();
submit = $("#submit").val();
$(".form-message").load("form.php", {
name: name,
email: email,
phone: phone,
address: address,
subject: subject,
services: services,
message: message,
submit: 'submitted'
});
});
});
form.php data
if (isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$subject = "Contact Form";
$mailTo = "hello#develoweb.com";
$headers = "From: ".$email;
$txt = "You have received a message from ".$name.
".\n\n".$message;
$errorEmptyname = false;
$errorEmptyemail = false;
$errorEmptymessage = false;
$errorEmail = false;
if (empty($name)) {
echo "<span class='form-error'>Name Field cannot be empty</span> ";
//$errorEmptyName = true;
}
if (empty($email)) {
echo "<span class='form-error'>Email Field cannot be empty</span>";
//$errorEmptyemail = true;
}
if (empty($message)) {
//$errorEmptymessage = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>
Write a valid e-mail addres </span>";
$errorEmail = true;
}
else {
echo "<span class='form-success'>
Thank you for your message!<br>
I'll get back to you as soon as I can.</span>";
mail($mailTo, $subject, $body, $headers);
}
}
else{
echo "There was an error!";
}
what i have understand, im not getting individual validation error in individual field bcz class is same, how can i append error to related fields
i havent used js validation bcz i want to some validation for spammer to prevent spam mail and as we know while viewing source code we can easily view code for validation too, so pefer validation in php

I am receiving empty emails on my website

I am building a html5 based contact form with php mail script.
I do not know why i am getting empty emails on submission as well as If i want to print any message like "Thank you for contacting us", How would I do that.
<?php
$name = (isset($_POST['name']) ? $_POST['name'] : null);
$phone = (isset($_POST['phone']) ? $_POST['phone'] : null);
$address = (isset($_POST['address']) ? $_POST['address'] : null);
$appointment_datepicker =(isset($_POST['appointment-datepicker']) ? $_POST['appointment-datepicker'] : null);
$message = (isset($_POST['textarea']) ? $_POST['textarea'] : null);
$email_address = (isset($_POST['email']) ? $_POST['email'] : null);
// Create the email and send the message
$to = 'dipen2512#gmail.com'; // Add your email address inbetween the '' replacing yourname#yourdomain.com - This is where the form will send a message to.
$email_subject = "Website Contact Form: $name";
$email_body = "You have received a new message from your website contact form.\n\n"."Here are the details:\n\nName: $name\n\nPhone: $phone\n\nEmail: $email_address\n\nAppointment: $appointment_datepicker\n\nAddress: $address\n\nMessage:\n$message";
$headers = "From: noreply#dev-designers.com\n"; // This is the email address the generated message will be from. We recommend using something like noreply#yourdomain.com.
$headers .= "Reply-To: $email_address";
$mail_status = mail($to,$email_subject,$email_body,$headers);
/** Check for empty fields
if(!empty($_POST['name']) || !empty($_POST['phone']) || !empty($_POST['address']) || !empty($_POST['appointment-datepicker']) || !empty($_POST['textarea']) || filter_var($_POST['email'],FILTER_VALIDATE_EMAIL))
{**/
if ($mail_status) { ?>
<script language="javascript" type="text/javascript">
print( "Thank you for the message. We will contact you shortly.");
window.location = 'http://thankyou.html';
</script>
<?php
}
else { ?>
<script language="javascript" type="text/javascript">
print( 'Message failed. Please, send an email to gordon#template-help.com');
window.location = 'http://thankyou.html';
</script>
<?php
}
?>
<form id="appointment-form" action="contact_me.php" method="post" class="appointment-form">
<div class="col-md-6">
<div class="form-group form-md-line-input form-md-floating-label">
<input id="name" type="text" class="form-control" required="required">
<label for="name">Name</label>
</div>
<div class="form-group form-md-line-input form-md-floating-label">
<input id="phone" type="text" class="form-control" required="required" pattern="/[1-9][01][0-9]-?[0-9]{3}-=[0-9]{4}">
<label for="phone">Phone Number</label>
</div>
<div class="form-group form-md-line-input form-md-floating-label">
<input id="address" type="text" class="form-control" required="required">
<label for="address">Address </label>
</div>
<div class="form-group form-md-line-input form-md-floating-label">
<input id="appointment-datepicker" type="text" class="form-control form-line-input" required="required">
<label for="appointment-datepicker">Book a date</label>
</div>
</div>
<div class="col-md-6">
<div class="form-group form-md-line-input form-md-floating-label">
<input id="email" type="text" class="form-control" required="required" pattern="[a-zA-Z0-9!#$%&'*+\/=?^_`{|}~.-]+#[a-zA-Z0-9-]+(\.[a-zA-Z0-9-]+)*">
<label for="email">Email Address</label>
</div>
<div class="form-group form-md-line-input form-md-floating-label">
<textarea id="textarea" rows="4" class="form-control form-textarea"></textarea>
<label for="textarea">Message</label>
</div>
<div class="btn-wrapper">
<button type="submit" class="btn btn-make-app">Send to us</button>
</div>
</div>
<div class="clearfix"> </div>
</form>
Your form inputs are missing "name" attributes. IDs don't get passed along in a form request; only the name-value pairings.
v---------v
<input id="name" name="name" type="text" class="form-control" required="required">

FILTER_VALIDATE_EMAIL saying a valid email is invalid

I have a problem with checking if a email is valid. but the weird is that i have the same form on to different pages/urls, and on one of the forms it keeps saying that the email is invalid and on the form its valid.
The form on this page works - http://night.sendme.to/about
the form on this page doesnt - http://night.sendme.to/book/jokeren
The HTML on the forms is the same
<form action="" method="post" id="myform">
<div class="form-group">
<label for="name">Navn *</label>
<input type="text" class="form-control" id="name" name="name" placeholder="Navn" required="required">
</div>
<div class="form-group">
<label for="corp">Virksomhed</label>
<input type="text" class="form-control" id="corp" name="corp" placeholder="Virksomhed">
</div>
<div class="form-group">
<label for="email">Email adresse *</label>
<input type="email" class="form-control" id="email" name="email" placeholder="Email adresse" required="required">
</div>
<div class="form-group">
<label for="tel">Telefon *</label>
<input type="tel" class="form-control" id="tel" name="tel" placeholder="Telefon" required="required">
</div>
<div class="form-group">
<label for="message">Kommentar</label>
<textarea class="form-control" id="message" name="message" rows="10" required="required"></textarea>
</div>
<button type="submit" class="btn btn-default" id="submit">Send</button>
</form>
<div id="success" style="color:red;"></div>
The PHP is this
<?php // Here we get all the information from the fields sent over by the form.
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$to = 'YOURMAIL';
$subject = 'the subject';
$message = 'FROM: '.$name.' Email: '.$email.'Message: '.$message;
$header = "MIME-Version: 1.0" . "\r\n";
$header .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$header .= "from:".$_POST['email'];
if (filter_var($email, FILTER_VALIDATE_EMAIL)) { // this line checks that we have a valid email address
mail($to, $subject, $message, $header); //This method sends the mail.
echo "Your email was sent!";
echo var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
} else {
echo "Invalid Email, please provide an correct email.";
echo var_dump(filter_var($email, FILTER_VALIDATE_EMAIL));
}
?>
The javascript is this
$(document).ready(function(){
$('#submit').click(function(){
$.post("email.php", $("#myform").serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;
});
});
Hope some one can help, why the form only works on the http://night.sendme.to/about and the others
So, to not leave this question answer-less:
In your HTML code, you actually had <form action="" method="post" id="myform"> in both pages – but in your second page, you had another <form> tag right before it … and because of this invalid HTML, the browser ignored the second form tag, and that made $("#myform").serialize() not return any data at all, because it could not find the form element with that id.
You should always validate your HTML code. This helps avoiding such errors.

Succeeding submission of contact form

Hi I have a contact form using PHP AJAX but filling the form, it is successful but when I try to fillup again the form it is not submitting unless I refresh the page, it will go back to normal again. What will be the problem of this?
Thanks
HTML Code
<form role="form" id="feedbackForm" method="POST">
<div class="col-lg-6">
<div class="form-group">
<label class="control-label" for="textinput">First Name<span class="required">*</span></label>
<input type="text" class="form-control required" id="first_name" name="first_name" placeholder="Enter your First Name"/>
<span class="help-block" style="display: none;">Please enter your first name.</span>
</div>
<div class="form-group">
<label class="control-label" for="textinput">Last Name<span class="required">*</span></label>
<input type="text" class="form-control" id="last_name" name="last_name" placeholder="Enter your Last Name"/>
<span class="help-block" style="display: none;">Please enter your last name.</span>
</div>
<div class="form-group">
<label class="control-label" for="textinput">Email Address<span class="required">*</span></label>
<input type="email" class="form-control" id="email" name="email" placeholder="Enter your email address"/>
<span class="help-block" style="display: none;">Please enter a valid e-mail address.</span>
</div>
<div id="companyname_con" class="form-group">
<label class="control-label" for="textinput">Company Name</label>
<input type="text" class="form-control" id="company_name" name="company_name" placeholder="Enter your company name">
</div>
<div class="form-group">
<label class="control-label" for="textinput">Message<span class="required">*</span></label>
<textarea rows="10" cols="100" class="form-control" id="contact_message" name="contact_message" placeholder="Enter your message"></textarea>
<span class="help-block" style="display: none;">Please enter a message.</span>
</div>
</div>
<div class="col-lg-6">
<div class="form-group">
<label for="selectbasic">How did you hear about us?</label>
<select id="selectbasic" name="selectbasic" class="form-control">
<option value="None">Select</option>
<option value="Search Engine">Search engine</option>
<option value="Microsoft DPE">Microsoft DPE</option>
<option value="Microsoft Event">Microsoft event</option>
<option value="Social Media">Social media</option>
<option value="Word of Mouth">Word of mouth</option>
<option value="Other">Other</option>
</select>
</div>
<div class="checkbox">
<label>
<input type="checkbox" id="emailUpdates" name="emailUpdates" value="Yes"> Please keep me informed of kinectAPI product updates and news
</label>
</div>
<img id="captcha" src="library/vender/securimage/securimage_show.php" alt="CAPTCHA Image" />
Show a Different Image<br/>
<div class="form-group" style="margin-top: 10px;">
<input type="text" class="form-control" name="captcha_code" id="captcha_code" placeholder="For security, please enter the code displayed in the box." />
<span class="help-block" style="display: none;">Please enter the code displayed within the image.</span>
</div>
<span class="help-block" style="display: none;">Please enter a the security code.</span>
<button type="submit" id="feedbackSubmit" class="btn btn-purple btn-md message-btn">Submit Message</button>
</div>
</form>
PHP Code
<?php
//start a session -- needed for Securimage Captcha check
session_start();
//add you e-mail address here
define("MY_EMAIL", "dummy#email.com");
/**
* Sets error header and json error message response.
*
* #param String $messsage error message of response
* #return void
*/
function errorResponse ($contact_message) {
header('HTTP/1.1 500 Internal Server Error');
die(json_encode(array('message' => $contact_message)));
}
/**
* Return a formatted message body of the form:
* Name: <name of submitter>
* Comment: <message/comment submitted by user>
*
* #param String $name name of submitter
* #param String $messsage message/comment submitted
*/
function setMessageBody ($first_name, $last_name, $email, $company_name,
$contact_message, $selectbasic) {
$message_body .= "First Name: " . $first_name."\n\n";
$message_body .= "Last Name: " . $last_name."\n\n";
$message_body .= "Email: " . $email."\n\n";
$message_body .= "Company Name:" . $company_name."\n\n";
$message_body .= "Message:" . $contact_message. "\n\n";
$message_body .= "How did you hear about us?" . $selectbasic."\n\n";
return $message_body;
}
$first_name = $_POST['first_name'];
$last_name = $_POST['last_name'];
$email = $_POST['email'];
$company_name = $_POST['company_name'];
$contact_message = $_POST['contact_message'];
$selectbasic = $_POST['selectbasic'];
header('Content-type: application/json');
//do some simple validation. this should have been validated on the client-side also
if (empty($email) || empty($contact_message)) {
errorResponse('Email or message is empty.');
}
//do Captcha check, make sure the submitter is not a robot:)...
include_once './vender/securimage/securimage.php';
$securimage = new Securimage();
if (!$securimage->check($_POST['captcha_code'])) {
errorResponse('Invalid Security Code');
}
//try to send the message
if(mail(MY_EMAIL, "Contact Form Results", setMessageBody($_POST["first_name"],
$_POST["last_name"], $_POST["email"], $_POST["company_name"], $_POST["contact_message"],
$_POST["selectbasic"]), "From: $email")) {
echo json_encode(array('message' => 'Your message was successfully sent'));
} else {
header('HTTP/1.1 500 Internal Server Error');
echo json_encode(array('message' => 'Unexpected error while attempting to send e-
mail.'));
}
?>
JS code
$(document).ready(function() {
$("#feedbackSubmit").click(function() {
//clear any errors
contactForm.clearErrors();
//do a little client-side validation -- check that each field has a value and e-mail field is in proper format
var hasErrors = false;
$('#feedbackForm input,textarea').each(function() {
if (!$(this).val()) {
hasErrors = true;
contactForm.addError($(this));
}
});
var $email = $('#email');
if (!contactForm.isValidEmail($email.val())) {
hasErrors = true;
contactForm.addError($email);
}
//if there are any errors return without sending e-mail
if (hasErrors) {
return false;
}
//mailchimp trigger
if($('#emailUpdates').prop('checked')) {
$.ajax({
type: "POST",
url: 'subscribe.php',
data: 'ajax=true&email=' + escape($('#email').val())
});
}
//send the feedback e-mail
$.ajax({
type: "POST",
url: "library/sendmail.php",
data: $("#feedbackForm").serialize(),
success: function(data)
{
contactForm.addAjaxMessage(data.message, false);
//get new Captcha on success
$('#captcha').attr('src', 'library/vender/securimage/securimage_show.php?' +
Math.random());
},
error: function(response)
{
contactForm.addAjaxMessage(response.responseJSON.message, true);
}
});
$('#feedbackForm input,textarea,select').val('');
return false;
});
});
//namespace as not to pollute global namespace
var contactForm = {
isValidEmail: function (email) {
var regex = /^([a-zA-Z0-9_.+-])+\#(([a-zA-Z0-9-])+\.)+([a-zA-Z0-9]{2,4})+$/;
return regex.test(email);
},
clearErrors: function () {
$('#emailAlert').remove();
$('#feedbackForm .help-block').hide();
$('#feedbackForm .form-group').removeClass('has-error');
},
addError: function ($input) {
$input.siblings('.help-block').show();
$input.parent('.form-group').addClass('has-error');
},
addAjaxMessage: function(msg, isError) {
$("#feedbackSubmit").after('<div id="emailAlert" class="alert alert-' + (isError ?
'danger' : 'success') + '" style="margin-top: 5px;">' + $('<div/>').text(msg).html() +
'</div>');
}
};

Contact Form same page success

I am trying to send an email with PHP and Ajax, the mailer is working but I know very little about Ajax, after reading a couple of pages of a book I have written a small piece of code and was hoping someone could point out where I am going wrong:
Here is my PHP:
<?php
$name = ($_POST['name']);
$email = ($_POST['email']);
$fsubject = ($_POST['subject']);
$message = ("Name: ". $name . "\nEmail Address: " . $email . "\n\nMessage: " . $_POST['message']);
// Set Mail
$to = "emailaddress#fakeone.com";
$headers = 'emailaddress#fakeone.com' . "\r\n";
$subject = "{$fsubject}";
$body = "{$message}";
// Send Mail
if (mail($to, $subject, $body, $header))
{
echo("<p>Message successfully sent!</p>");
}
else
{
echo("<p>Message delivery failed...</p>");
}
?>
My HTML:
<div id="success" style="color:red;"></div>
<form action="" id="contactform" method="post">
<div class="row">
<div class="form-group">
<div class="col-md-6">
<label>Your name *</label>
<input type="text" value="" data-msg-required="Please enter your name." maxlength="100" class="form-control" name="name" id="name">
</div>
<div class="col-md-6">
<label>Your email address *</label>
<input type="email" value="" data-msg-required="Please enter your email address." data-msg-email="Please enter a valid email address." maxlength="100" class="form-control" name="email" id="email">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Subject</label>
<input type="text" value="" data-msg-required="Please enter the subject." maxlength="100" class="form-control" name="subject" id="subject">
</div>
</div>
</div>
<div class="row">
<div class="form-group">
<div class="col-md-12">
<label>Message *</label>
<textarea maxlength="5000" data-msg-required="Please enter your message." rows="10" class="form-control" name="message" id="message"></textarea>
</div>
</div>
</div>
<div class="row">
<div class="col-md-12">
<input type="submit" id="submit" value="Send Message" class="btn btn-info btn-lg" data-loading-text="Loading...">
</div>
</form>
My AJAX:
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("sendmail.php", $("#contactform").serialize(), function(response) {
$('#success').html(response);
//$('#success').hide('slow');
});
return false;
});
});
</script>
At the moment the same page just reloads, the desired outcome is just a subtle success or failure message appearing.
Any help would be welcome!
Thanks,
Dan
Your snippet code seems to run just fine.
It must be an error either in other JS (check browser console, F12 in Chrome for example) or in your PHP.
Try this to see if ajax post fails:
<script>
$(document).ready(function(){
$('#submit').click(function(){
$.post("contact.php", $("#contactform").serialize(), function(response) {
$('#success').html(response);
}).fail(function() {
alert( "error" );
});
return false;
});
});
</script>
Also, try to make sure PHP execution is fine, so remove all javascript and replace
<form action="sendmail.php" id="contactform" method="post">
Check the result of that page, it should be "Message successfully sent!".
Also, check a simple JS snippet of your code:
http://jsfiddle.net/CPtpk/
Please note that if you have another JavaScript code in your page that could be a cause for this problem. Even if your JS error is in another place it can cause JS execution to stop and so your onClick isn't executed and that's why you get your problem...
Try something like this on the JS:
<script>
$(document).ready(function() {
$('#contactform').submit(function(e) {
e.preventDefault();
$.post("sendmail.php", $(this).serialize(), function(response) {
$('#success').html(response);
});
});
});
</script>

Categories