I'm trying to validate a contact form with jquery and php but I always get false from php even though it's working fine. I'm going to explain with my code:
This is my html:
<form method='post'>
<label>Name<input id="name" type="text" name="name" /></label>
<label>Email Address<input id="email" type="text" name="email" /></label>
<label>Subject<input id="subject" type="text" name="subject" /></label>
<label>Message<textarea id="message" name="message"></textarea></label>
<label><input type="button" value="Submit Form" id="button_form" /></label>
</form>
This is my js code:
function validaForm(){
// Campos de texto
if($('#email').val() == ""){
alert("You must fill in at least the email field.");
$('#email').focus();
return false;
}
return true;
}
$('#button_form').click( function() {
if(validaForm()){
$.post("php/form.php",$('form').serialize(),function(res){
if(res == 1){
alert("Your e-mail has been sent, Thank you for contacting us. We will answer you as soon as possible.");
} else if(res == 0){
alert("Sorry, your e-mail couldn't been sent, please try again later.");
} else {
alert("Others.");
}
});
}
});
This is my .php file:
<?php
require 'class.phpmailer.php';
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = 'smtp.domain.com';
$mail->SMTPAuth = true;
$mail->Username = 'myacc#mydomain.com';
$mail->Password = 'pass';
$mail->SMTPSecure = 'tls';
$mail->From = 'myacc#mydomain.com';
$mail->FromName = 'Contact Form';
$mail->AddAddress('myacc#mydomain.com');
$mail->AddAttachment('/var/tmp/file.tar.gz');
$mail->AddAttachment('/tmp/image.jpg', 'new.jpg');
$mail->IsHTML(true);
$mail->Subject = $_POST['subject'];
$mensajeFinal = "Message";
$mail->Body = $mensajeFinal;
if(!$mail->Send()) {
return false;
} else {
return true;
};
?>
Ok, Everything is working fine, I mean, it sends the e-mail but the problem is that I always get false from php file no matter if it sends or not the e-mail.
Am I doing something wrong?? Is there something I am missing??
I would appreciate any help. Thanxs a lot.
You have to use echo here, this is not function. return is used for returning result from functions. Also remove the ; after
else {...};
^
if(!$mail->Send()) {
echo false;
} else {
echo true;
}
In your click function
$('#button_form').click( function() { .... } );
Be sure to return false if validaForm returns false
Hi put your code between
$(document).ready(function() {
});
Looks like
$(document).ready(function() {
$('#button_form').click( function() {
if(validaForm()){
$.post("php/form.php",$('form').serialize(),function(res){
if(res == 1){
alert("Your e-mail has been sent, Thank you for contacting us. We will answer you as soon as possible.");
} else if(res == 0){
alert("Sorry, your e-mail couldn't been sent, please try again later.");
} else {
alert("Others.");
}
});
}
});
});
Related
i've search here but i didnt find anything that solve the problem... hope someone could help me please....
i'm using PHPMailer to send mails and i want to add option to attach PDF Files that's my code:
HTML (simplfied):
<form method="post" action="contact/submit.php">
<input type="email" name="email" value="<?php echo $supmail; ?>" size="80">
<input type="text" name="ccmail" value="<?php echo implode(', ', $final);?>" size="80">
<input type="text" style="font-size:11" name="subject" id="subject" value="ORDER" size="80">
<input type="hidden" name="MAX_FILE_SIZE" value="100000">
<input type="file" name="userfile" size="55" style="font-size:10;" accept="application/pdf">
<textarea rows="7" name="message" id="message" cols="85" style="font-size: 11"><?php echo $newstr; ?></textarea>
<div class="g-recaptcha" style="text-align:center;" data-sitekey="<?= CONTACTFORM_RECAPTCHA_SITE_KEY ?>">
<button class="button">Send</button>
</form>
submit.php:
<?php
require('db.php');
$target_dir = __DIR__."/uploads/";
$target_file = $target_dir . basename($_FILES["fileToUpload"]["name"]);
$uploadOk = 1;
$imageFileType = strtolower(pathinfo($target_file,PATHINFO_EXTENSION));
if (file_exists($target_file)) {
echo "קובץ קיים.";
$uploadOk = 0;
}
if($imageFileType != "pdf") {
echo "ניתן להעלות רק קבצי PDF";
$uploadOk = 0;
}
if ($uploadOk == 0) {
echo "הקובץ לא עלה.";
} else {
if (move_uploaded_file($_FILES["fileToUpload"]["tmp_name"], $target_file)) {
echo $target_file;
} else {
echo "שגיאה בהעלאת הקובץ";
}
}
require_once __DIR__.'/vendor/autoload.php';
require_once __DIR__.'/functions.php';
require_once __DIR__.'/config.php';
session_start();
if ($_SERVER['REQUEST_METHOD'] != 'POST') {
redirectWithError("The form must be submitted with POST data.");
}
// Do some validation, check to make sure the name, email and message are valid.
if (empty($_POST['g-recaptcha-response'])) {
redirectWithError("נא להשלים בדיקת רובוט");
}
$recaptcha = new \ReCaptcha\ReCaptcha(CONTACTFORM_RECAPTCHA_SECRET_KEY);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_REQUEST['REMOTE_ADDR']);
if (!$resp->isSuccess()) {
$errors = $resp->getErrorCodes();
$error = $errors[0];
$recaptchaErrorMapping = [
'missing-input-secret' => 'לא נשלח קוד.',
'invalid-input-secret' => 'הקוד לא נכון.',
'missing-input-response' => 'לא נשלח אימות.',
'invalid-input-response' => 'שגיאה בקבלת תשובת אימות.',
'bad-request' => 'שגיאה לא ידועה.',
'timeout-or-duplicate' => 'פג תוקף, נסה שוב',
];
$errorMessage = $recaptchaErrorMapping[$error];
redirectWithError("יש לנסות שוב אימות: ".$errorMessage);
}
if (empty($_POST['email'])) {
redirectWithError("אנא הזן כתובת דואר אלקטורני עבור הספק");
}
if (empty($_POST['subject'])) {
redirectWithError("אנא הזן נושא להזמנה");
}
if (empty($_POST['message'])) {
redirectWithError("אנא הזן הודעה לספק");
}
if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
redirectWithError("נא להזין כתובת דואר אלקטרונית חוקית");
}
if (strlen($_POST['message']) < 5) {
redirectWithError("חובה להזין לפחות 5 תויים בהודעה");
}
// Everything seems OK, time to send the email.
$mail = new \PHPMailer\PHPMailer\PHPMailer(true);
try {
//Server settings
$tomail = $_POST['email'];
$toname = $_POST['suppl'];
$ccmail = $_POST['ccmail'];
$nametoconf = $_POST['confby'];
$orderid = $_POST['orderid'];
$toname2 = "מכללת השף";
$mail->SMTPDebug = 2;
$mail->isSMTP();
$mail->Host = CONTACTFORM_SMTP_HOSTNAME;
$mail->SMTPAuth = true;
$mail->CharSet = 'UTF-8';
$mail->Username = CONTACTFORM_SMTP_USERNAME;
$mail->Password = CONTACTFORM_SMTP_PASSWORD;
$mail->SMTPSecure = CONTACTFORM_SMTP_ENCRYPTION;
$mail->Port = CONTACTFORM_SMTP_PORT;
$mail->setFrom(CONTACTFORM_FROM_ADDRESS, $toname2);
$mail->addAddress($tomail, $toname);
$ccmailto = explode(',', $ccmail);
foreach($ccmailto as $ccmailtof)
{
$mail->AddCC($ccmailtof);
}
// Content
$mail->Subject = "".$_POST['subject'];
$mail->Body = <<<EOT
{$_POST['message']}
EOT;
$mail->AddAttachment($target_file);
$mail->send();
redirectSuccess();
} catch (Exception $e) {
redirectWithError("שגיאה בעת ניסיון שליחת ההזמנה: ".$mail->ErrorInfo);
}
?>
when i'm tring to send mail witout the attachment works great.
when i add the attachment i get "Could not access file:"
thank you
This code is unsafe:
$mail->AddAttachment($_FILES['uploaded_file']['tmp_name'], $_FILES['userfile']['name']);
As per the file upload example provided with PHPMailer and the PHP docs, you need to validate what's in $_FILES before trusting it.
Further to that, the addAttachment method returns a tru/false status value if it can find and read the file, so check that – don't assume that it's worked.
This is index.php
Right now all i can do is give values to the $mail->Subject and $mail->body but i want it to be dynamic for example
Here i want to give 2 inputs for subject and message and pass it on $mail->Subject and $mail->Body
since the post method is on ajax im unable to pass two values from input fields to the send_mail.php any help would be appreciated
<?php
//index.php
$connect = new PDO("mysql:host=localhost;dbname=testing", "root", "");
$query = "SELECT * FROM customer ORDER BY customer_id";
$statement = $connect->prepare($query);
$statement->execute();
$result = $statement->fetchAll();
?>
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container">
<br />
<div class="table-responsive">
<table class="table table-bordered table-striped">
<tr>
<th>Customer Name</th>
<th>Email</th>
<th>Select</th>
<th>Action</th>
</tr>
<?php
$count = 0;
foreach($result as $row)
{
$count = $count + 1;
echo '
<tr>
<td>'.$row["customer_name"].'</td>
<td>'.$row["customer_email"].'</td>
<td>
<input type="checkbox" name="single_select" class="single_select" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" />
</td>
<td>
<button type="button" name="email_button" class="btn btn-info btn-xs email_button" id="'.$count.'" data-email="'.$row["customer_email"].'" data-name="'.$row["customer_name"].'" data-action="single">Send Single</button>
</td>
</tr>
';
}
?>
<tr>
<td colspan="3"></td>
<td><button type="button" name="bulk_email" class="btn btn-info email_button" id="bulk_email" data-action="bulk">Send Bulk</button></td></td>
</tr>
</table>
</div>
</div>
</body>
</html>
<script>
$(document).ready(function(){
$('.email_button').click(function(){
$(this).attr('disabled', 'disabled');
var id = $(this).attr("id");
var action = $(this).data("action");
var email_data = [];
if(action == 'single')
{
email_data.push({
email: $(this).data("email"),
name: $(this).data("name")
});
}
else
{
$('.single_select').each(function(){
if($(this).prop("checked") == true)
{
email_data.push({
email: $(this).data("email"),
name: $(this).data('name')
});
}
});
}
$.ajax({
url:"send_mail.php",
method:"POST",
data:{email_data:email_data},
beforeSend:function(){
$('#'+id).html('Sending...');
$('#'+id).addClass('btn-danger');
},
success:function(data){
if(data == 'ok')
{
$('#'+id).text('Success');
$('#'+id).removeClass('btn-danger');
$('#'+id).removeClass('btn-info');
$('#'+id).addClass('btn-success');
}
else
{
$('#'+id).text(data);
}
$('#'+id).attr('disabled', false);
}
})
});
});
</script>
And this is send_mail.php
<?php
//send_mail.php
if(isset($_POST['email_data']))
{
require 'class/class.phpmailer.php';
$output = '';
foreach($_POST['email_data'] as $row)
{
$mail = new PHPMailer;
$mail->IsSMTP();
$mail->Host = 'smtp.gmail.com';
$mail->Port = '587';
$mail->SMTPAuth = true;
$mail->Username = 'xx';
$mail->Password = 'xx';
$mail->SMTPSecure = 'tls';
$mail->From = 'xx';
$mail->FromName = 'xx';
$mail->AddAddress($row["email"], $row["name"]);
$mail->WordWrap = 50;
$mail->IsHTML(true);
$mail->Subject = 'i want input to be passed here';
//An HTML or plain text message body
$mail->Body = 'and the body message to be passed here';
$mail->AltBody = '';
$result = $mail->Send(); //Send an Email. Return true on success or false on error
// if($result["code"] == '400')
// {
// $output .= html_entity_decode($result['full_error']);
// }
}
if($output == '')
{
echo 'ok';
}
else
{
echo $output;
}
}
?>
I am assuming You want to add two inputs for subject and message for each email data.
You can add 2 fields and in ajax set it along with email data and pass it to send_mail.php.
JS Code
<script>
$(document).ready(function(){
$('.email_button').click(function(){
$(this).attr('disabled', 'disabled');
var id = $(this).attr("id");
var action = $(this).data("action");
var email_data = [];
if(action == 'single')
{
email_data.push({
email: $(this).data("email"),
name: $(this).data("name"),
subject: $(this).data("subject"), //or can be grab from input
message: $(this).data("message")
});
}
else
{
$('.single_select').each(function(){
if($(this).prop("checked") == true)
{
email_data.push({
email: $(this).data("email"),
name: $(this).data('name'),
subject: $(this).data("subject"), //or can be grab from input
message: $(this).data("message")
});
}
});
}
$.ajax({
url:"send_mail.php",
method:"POST",
data:{email_data:email_data},
beforeSend:function(){
$('#'+id).html('Sending...');
$('#'+id).addClass('btn-danger');
},
success:function(data){
if(data == 'ok')
{
$('#'+id).text('Success');
$('#'+id).removeClass('btn-danger');
$('#'+id).removeClass('btn-info');
$('#'+id).addClass('btn-success');
}
else
{
$('#'+id).text(data);
}
$('#'+id).attr('disabled', false);
}
})
});
});
</script>
In send_mail.php replace following lines
$mail->Subject = 'i want input to be passed here';
//An HTML or plain text message body
$mail->Body = 'and the body message to be passed here';
With This
$mail->Subject = $row["subject"];
$mail->Body = $row["message"];
Hope it will answer your question.
Firt of all:
Send only user id with ajax (better use fetch() for requests in js)
and then get user data in file (send_mail.php) from database (user validation)!!!
User validation is needed if not by session then by checking against the database.
See composer class for sending emails with phpmailer here:
https://github.com/MoovFun/Xo-Mail
firstly I am not overly knowledgeable in PHP. I will try to explain with the understanding that the PHP on my site was written by a friend for me in college so I only understand small bits of it. Anyhow, everything is working great, I was just wondering right now when the auto-reply is received it is from nf.theamitybladecom#boscustweb2204.eigbox.net which kind of bugs me. theamitybladecom is, of course, a reference to my site name. I was hoping I could tweak it to say from noreply#theamityblade.com or something. Anyways, this is the code I have so far, and forgive me for removing a few sensitive entries. Hopefully, you understand what I strive to do and that it is an easy alteration to my code. I can't handle complex PHP basically at all so please explain it in newbie terms. Any help you can offer would be greatly appreciated. Thanks,
Black_Lightning
<?php
/* Verify captcha from google */
function verify_captcha($response) {
$url = 'https://www.google.com/recaptcha/api/siteverify';
$curl = curl_init();
$captcha_verify_url = "https://www.google.com/recaptcha/api/siteverify";
curl_setopt($curl, CURLOPT_URL,$captcha_verify_url);
curl_setopt($curl, CURLOPT_POST, true);
curl_setopt($curl, CURLOPT_POSTFIELDS, "secret=captchaSecretKey&response=".$response);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
$verify = curl_exec ($curl);
curl_close ($curl);
$captcha_success=json_decode($verify);
if ($captcha_success->success==true) {
return true;
} else{
return false;
}
}
$action=$_REQUEST['action'];
$show_form = true;
if ($action!="") /* display the contact form */
{
$name=$_POST['name'];
$email=$_POST['email'];
$message=$_POST['message'];
$response = $_POST["g-recaptcha-response"];
//check if the captcha is valid or not
if (verify_captcha($response)) {
$subject="New Message for me!";
mail("example#mysite.com",$subject,$message,"From: $email \n");
echo "Email sent!!";
$show_form = false;
} else if ($captcha_success->success==false) {
$show_form = true;
}
}
?>
<?php if($show_form) { ?>
<form id="form" class="contact-form" action="" onSubmit="return checkValid()"method="POST" enctype="multipart/form-data">
<input type="hidden" name="action" value="submit" />
<span id="blue-text">Your name:<br>
<input id="name" name="name" type="text" value="" size="50"/>
<br>
Your email:<br>
<input id="email" name="email" type="text" value="" size="50"/><br>
Your message:<br>
</span>
<textarea id="message" name="message" wrap="hard" rows="10" cols="49" ></textarea>
<br>
<div class="g-recaptcha" data-sitekey="captchaSiteKey"></div>
<input type="submit" value="Send"/>
</form>
<?php
}
/* Prepare autoresponder subject */
$respond_subject = "Thank you for contacting me!";
/* Prepare autoresponder message */
$respond_message = "Hello!
Thank you for contacting me! I will get back to you
as soon as possible!
Yours sincerely,
My Name
www.mysite.com
";
/* Send the message using mail() function */
mail($email, $respond_subject, $respond_message);
?>
<script>
function checkValid()
{
var name = document.getElementById("name");
var email = document.getElementById("email");
var message = document.getElementById("message");
var firstError = null;
var errorMessage = "";
if (name.value == "")
{
errorMessage += "Please enter your name! \n";
if (firstError == null)
{
firstError = name;
}
}
if (email.value == "")
{
errorMessage += "Please enter your email! \n";
if (firstError == null)
{
firstError = email;
}
}
if (message.value == "")
{
errorMessage += "Please enter your message! \n";
if (firstError == null)
{
firstError = message;
}
}
if (errorMessage != "")
{
alert(errorMessage);
firstError.focus();
return false;
}
else
{
return true;
}
}
</script>
It is currently trying to use the submitter's email address as the from address:
mail("example#mysite.com",$subject,$message,"From: $email \n");
Don't do that; it's forgery and will either be prevented from working altogether, or result in your messages being spam-filtered or bounced. Set it as a reply-to header instead:
mail("example#mysite.com", $subject, $message, "Reply-to: $email \n");
This code is vulnerable to header injection attacks as no filtering is applied to $_POST['email'] before it is used as a message header. Overall, avoid using the mail function altogether; it's inherently unsafe. Use a library like PHPMailer (that you tagged this question with) and send using SMTP to localhost, which is both faster and safer. See PHPMailer's contact form example.
I'm working with the form using phpmailer. here phpmailer is working fine but before sending a mail I want to validate my form using js.validation is not working how should I validate the form before sending a mail using js. where I have to write a condition for this can anyone help me out I tried in many ways but didn't achieve it.
Below is my code
HTML
<form method="post" action="script.php" id="test" novalidate>
<div class="detail">
<label>name:</label>
<input type="text" name="user_name" data-validation="name" />
</div><!--detail-->
<div class="detail">
<label>Email:</label>
<input type="email" name="user_email" data-validation="email"/>
</div><!--detail-->
<div class="detail">
<label>phone</label>
<input type="number" name="user_phone" data-validation="phone" />
</div><!--detail-->
<div class="detail">
<label></label>
<input type="text" name="user_enquiry" data-validation="message" />
</div><!--detail-->
<div class="detail message">
<label>Message:</label>
<textarea name="user_message" cols="30" rows="15" data-validation="message"></textarea>
</div><!--detail-->
<p><input type="submit" name="send" id="send" value="Send" onclick="formSubmit();" /></p>
<div class="success_msg">
<p>Form submitted Successfully</p>
</div>
</form>
JS:
function formSubmit(){
var Validator = function(formObject) {
this.form = $(formObject);
var Elements = {
name: {
reg: /^[a-zA-Z]{2,20}$/,
require : true,
error: "Not a valid name.",
},
email: {
reg: /^[a-z-0-9_+.-]+\#([a-z0-9-]+\.)+[a-z0-9]{2,7}$/i,
error: "Not a valid e-mail address.",
},
phone: {
reg: /^\(?([0-9]{3})\)?[-. ]?([0-9]{3})[-. ]?([0-9]{4})$/,
error: "Not a valid number.",
},
message: {
reg: /^(?!\s*$).+/,
error: "Message field cannot be empty.",
},
gender: {
error: "gender is required",
},
selectOption: {
error: "this field is required",
required: true
}
};
var handleError = function(element, message) {
element.addClass('input-error');
var $err_msg = element.parent('div');
$err_msg.find('.error').remove();
var error = $('<div class="error"></div>').text(message);
error.appendTo($err_msg);
console.log(element);
element.on('keypress change', function() {
$(error).fadeOut(1000, function() {
console.log(element);
element.removeClass('input-error');
});
});
};
/* Select Option */
this.validate = function() {
var errorCount = 0;
this.form.find("select").each(function(index, field){
var type = $(field).data("validation");
var validation = Elements[type];
if($(field).val() == "") {
errorCount++;
handleError($(field), validation.error);
}
});
this.form.find("input, textarea").each(function(index, field){
var type = $(field).data("validation");
var validation = Elements[type];
if(validation !== undefined) {
var re = new RegExp(validation.reg);
if (validation){
if (!re.test($(field).val())){
errorCount++;
handleError($(field), validation.error);
}
}
}
})
/* Radio button */
var radioList = $('input:radio');
var radioNameList = new Array();
var radioUniqueNameList = new Array();
var notCompleted = 0;
for(var i=0; i< radioList.length; i++){
radioNameList.push(radioList[i].name);
}
radioUniqueNameList = jQuery.unique( radioNameList );
console.log(radioUniqueNameList);
for(var i=0; i< radioUniqueNameList.length; i++){
var field = $('#' + radioUniqueNameList[i]);
var type = field.data("validation");
var validation = Elements[type];
if($('input[name='+type+']:checked', '#test').val() == undefined) {
errorCount++;
handleError($(field), validation.error);
}
}
return errorCount == 0;
};
};
/* Submit form*/
$(function(){
$('form#test').on('submit', function (e) {
var NoErrors = new Validator(this).validate();
if(NoErrors == true) {
$.ajax({
url: this.action,
type: this.method,
data: $(this).serialize(),
success: function() {
// AJAX request finished, handle the results and error msg
$('.success_msg').fadeIn().delay(3000).fadeOut();
//$('input[type=text], input[type=number], input[type=email], textarea').val('').removeClass('error');
$('input[type!="submit"], textarea').val('').removeClass('error');
//this.reset();
}
});
}
return false;
})
})
}//formSubmit
PHP:
<?php
include "classes/class.phpmailer.php";
$mail = new PHPMailer; // Passing `true` enables exceptions
$mail->IsSMTP(); // Set mailer to use SMTP
$mail->SMTPDebug = 1; // Enable verbose debug output
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->SMTPSecure = 'tls'; // Enable TLS encryption, `ssl` also accepted
$mail->Host = 'smtp.gmail.com'; // Specify main and backup SMTP servers
$mail->Port = 587; // TCP port to connect to
$mail->IsHTML(true); // Set email format to HTML
$mail->Username = '***********'; // SMTP username
$mail->Password = '**********'; // SMTP password
$mail->SetFrom('**************');
$msg = 'Name : ' . $_POST["user_name"] . '<br> Email : ' . $_POST["user_email"] . '<br> Phone : ' . $_POST["user_phone"] . '<br> Enquiry : ' . $_POST["user_enquiry"] . '<br> Message : ' . $_POST["user_message"];
$mail->Subject = "subject here";
$mail->Body = $msg;
$mail->AddAddress($_POST["user_email"]);
if(!$mail->Send()){
echo 'Mailer Error: ' . $mail->ErrorInfo;
}else{
echo 'Message has been sent with using SMTP.';
}
?>
email.comusing this html code:
<form id="emailform" name="emailform" method="post" action="" >
<label>Name</label>
<input type="text" name="name" />
<label >Email</label>
<input type="text" name="email" />
<label >Message</label>
<textarea name="message"></textarea>
<div id="errormessage"></div>
<input type="submit" value="send" class="button" />
<input id="hiddenID" type="reset" name="hidden" />
</form>
with this script:
$("#emailform").submit(function(){
$.ajax({
type: "POST",
url: "email.ajax.php",
data: $("#emailform").serialize(),
dataType: "json",
success: function(msg){
$("#errormessage").removeClass('error');
$("#errormessage").addClass(msg.status);
$("#errormessage").html(msg.message);
$("#hiddenID").click();
},
error: function(){
$("#errormessage").removeClass('success');
$("#errormessage").addClass('error');
$("#errormessage").html("There was an error submitting the form. Please try again.");
}
});
return false;
});
and this php:
<?php
function checkEmail($email){
if(eregi("^[a-zA-Z0-9_]+#[a-zA-Z0-9\-]+\.[a-zA-Z0-9\-\.]+$]", $email)){
return FALSE;
}
list($Username, $Domain) = split("#",$email);
if(#getmxrr($Domain, $MXHost)){
return TRUE;
} else {
if(#fsockopen($Domain, 25, $errno, $errstr, 30)){
return TRUE;
} else {
return FALSE;
}
}
}
$response_array = array();
if(empty($_POST['name'])){
$response_array['status'] = 'error';
$response_array['message'] = 'Name is blank';
} elseif(!checkEmail($_POST['email'])) {
$response_array['status'] = 'error';
$response_array['message'] = 'Email is blank or invalid';
} elseif(empty($_POST['message'])) {
$response_array['status'] = 'error';
$response_array['message'] = 'Message is blank';
} else {
$body = $_POST['name'] . " sent you a message\n";
$body .= "Details:\n\n" . $_POST['message'];
mail("email#email.com", "Portfolio", $body);
$response_array['status'] = 'success';
$response_array['message'] = 'Email sent!';
}
echo json_encode($response_array);
?>
I'm getting a "Uncaught TypeError: Cannot read property 'status' of null" error at success msg and cant seem to figure why. It catches the name error but then doesnt like the email validation. Any help?
Here is the line creating the error: $("#errormessage").addClass(msg.status);
You are trying to access the status property of the msg object and the error is telling you that msg is either not an object or it has no property named status.
Do a console.log(msg); on the first line of your callback function to see what is actually being returned to the JavaScript.
Try adding this before your echo:
header('Content-type: application/json');
echo json_encode($response_array);