I have created an application in AngularJS and it has an email contact form and it sends emails using PHP file in server.
Here's my Controller.js part in AngularJS:
$scope.feedbacksubmit= function (){
var name1 = document.getElementById("name").value;
var email1 = document.getElementById("email").value;
var message1 = document.getElementById("message").value;
$http({
url: "http://boost.meximas.com/mobile/email.php",
method: "POST",
data: { name: name1, email: email1, message:message1 }
}).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
if(status == 200) {
var return_data = data;
if(return_data != 0){
$scope.hide();
//$scope.closeFeedback();
}else{
$scope.showEmailError();
}
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(status);
$scope.showAlertNetwork();
$scope.hide();
});
};
Here's my PHP Code:
<?php
$array = json_decode(file_get_contents('php://input'), true);
$name = $array['name'];
$email = $array['email'];
$message = $array['message'];
if (($name=="")||($email=="")||($message==""))
{
printf("0");
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("mygmail#gmail.com", $subject, $message, $from);
}
?>
The problem arises when I fill in the contact form and hit the Send button. I'm getting $scope.showEmailError();. But I get the email without problem.
And if I try to hit the button without filling the form still getting same $scope.showEmailError(); message.
Why don't you use model values from input? It looks like you try to use AngularJS but you still think with other frameworks in mind
In the following example I'm sending model to php script, if NAME is not filled then PHP returns 404 error and it's handled in AngularJS $http via .error handler. You don't have to add so much extra logic to success to deal with it
http://plnkr.co/edit/sw9RRXb3kdEWXszJdwX3?p=preview
html
<input type="text" ng-model="formData.name" placeholder="name">
<input type="text" ng-model="formData.email" placeholder="email">
<input type="text" ng-model="formData.message" placeholder="message">
javascript
$scope.formData = {
'name': '',
'email': '',
'message': ''
};
$scope.postData = function () {
$http.post('http://edeen.pl/form.php', $scope.formData)
.success(
function(data){
$scope.response = data.replace(/\ /g, ' ').replace(/\n/g, '<br/>') //format response
})
.error(
function(data){
$scope.response = data
})
}
php
$input = json_decode(file_get_contents('php://input'));
if($input->name === ''){
header("HTTP/1.0 404 Not Found");
echo "Something went terribly wrong, missing name maybe?";
return;
}
header('Content-Type: application/json');
var_dump($input);
<?php
$data = json_decode(file_get_contents("php://input"),true);
$name = $data->name;
$email = $data->email;
$sujet = $data->sujet;
$contenu = $data->contenu;
if($name && $email && $sujet && $contenu){
$destinataire = 'bercybilingualschool#gmail.com';
// Pour les champs $expediteur / $copie / $destinataire, séparer par une virgule s'il y a plusieurs adresses
$expediteur = $email;
$copie = 'sss17#gmail.com';
$copie_cachee = 'xxx#xxx.xxx';
$objet = $sujet; // Objet du message
$headers = 'MIME-Version: 1.0' . "\n"; // Version MIME
$headers .= 'Content-type: text/html; charset=ISO-8859-1'."\n"; // l'en-tete Content-type pour le format HTML
$headers .= 'Reply-To: '.$expediteur."\n"; // Mail de reponse
$headers .= 'From: '.$name.'<'.$name.'>'."\n"; // Expediteur
$headers .= 'Delivered-to: '.$destinataire."\n"; // Destinataire
$headers .= 'Cc: '.$copie."\n"; // Copie Cc
$headers .= 'Bcc: '.$copie_cachee."\n\n"; // Copie cachée Bcc
$message = '<div style="width: 100%; text-align: justify; font-weight: bold">hello</div>';
mail($destinataire, $objet, $message, $headers);
}else{
}
?>
Related
I am trying to create ajax and php files so when a user enters data on the form it either displays an error message if its invalid or sends and email and displays a thank you message if it is valid. I am stuck and not sure why my code is not working, right now when I hit submit the page is just reloaded with no messages at all.
AJAX code:
$('document').ready(function () {
var request;
$('contact').submit(function(event) {
event.preventDefault();
if (request) {
request.abort();
}
var $form = $(this);
var $inputs = $form.find("inputs, select, buttons, textarea");
var serializedData = $form.serialize();
$inputs.prop("disabled", true);
request = $.ajax({
url: "../send_email.php",
type: "post",
data: serializedData
});
request.done(function (msg) {
alert(msg);
});
request.fail(function (jqXHR, textStatus, errorThrown) {
console.error(
"The following error occurred: "+
textStatus, errorThrown
);
});
request.always(function () {
$inputs.prop("disabled", false);
});
});//contact event
});//document ready
PHP code:
<?php
if(isset($_POST['email'])) {
$email_to = "email#address.ca";
$email_subject = "Personal Website Contact Form";
$error_message = "";
if(!isset($_POST['first_name']) ||
!isset($_POST['last_name']) ||
!isset($_POST['email']) ||
!isset($_POST['comments']))
{
$error_message .= 'Please fill in all fields.\n'
}
else{
$first_name = $_POST['first_name']; // required
$last_name = $_POST['last_name']; // required
$email_from = $_POST['email']; // required
$comments = $_POST['comments']; // required
$email_exp = '/^[A-Za-z0-9._%-]+#[A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/';
if(!preg_match($email_exp,$email_from)) {
$error_message .= 'The Email Address you entered does not appear to be valid.\n';
}
$string_exp = "/^[A-Za-z .'-]+$/";
if(!preg_match($string_exp,$first_name)) {
$error_message .= 'The First Name you entered does not appear to be valid.\n';
}
if(!preg_match($string_exp,$last_name)) {
$error_message .= 'The Last Name you entered does not appear to be valid.\n';
}
if(strlen($comments) < 2) {
$error_message .= 'The Comments you entered do not appear to be valid.\n';
}
if(strlen($error_message) == 0) {
$email_message = "Form details below.\n\n";
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "First Name: ".clean_string($first_name)."\n";
$email_message .= "Last Name: ".clean_string($last_name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Comments: ".clean_string($comments)."\n";
// create email headers
$headers = 'From: '.$email_from."\r\n".
'Reply-To: '.$email_from."\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
echo "Email Sent. Thank you, I will get back to you asap";
}
else{
echo $error_message;
}
}
}
?>
$('document')
should be:
$(document)
And I suspect
$('contact')
should be:
$('#contact')
Though we'd have to see your HTML to know for certain. What you have is looking for <contact> elements, of which there are none. Instead, I imagine you want to look for something like <form id="contact">.
These are also wrong:
$form.find("inputs, select, buttons, textarea")
HTML elements aren't pluralized:
$form.find("input, select, button, textarea")
You have to be specific about your selectors. jQuery isn't going to be able to guess what you mean if it's close enough. It has to be exact. There are many options to use in the selectors, it's good to familiarize yourself with the basics.
Sorry for the title gore I am a little over my head on this one and have tried everything I can find online. I'm trying to pass data via post to my sendjs.php file and I have an issue.
The ajax success function does not apply the if statement.
Live site here: www.diysoakwells.com.au (you can add an item and checkout to test).
I'm not even sure where to start to be honest so any information would be appreciated and I will update the post with any info as requested.
app.js
$(function() {
// Get the form.
var form = $("#ajax-contact");
// Get the messages div.
var formMessages = $("#form-messages");
var spinner = $("#spinner");
var submit = $("#submit");
// Set up an event listener for the contact form.
$(form).submit(function(e) {
// Stop the browser from submitting the form.
e.preventDefault();
//display the cog animation
$(spinner).removeClass("hidden");
//hide the submit button
$(submit).addClass("hidden");
jsonObj=[];
for(i=1;i<$(".item-price").length;i++)
{
var items={};
var itemname = $(".item-name").get(i);
var itemprice = $(".item-price").get(i);
var itemquantity = $(".item-quantity").get(i);
var itemtotal = $(".item-total").get(i);
items["name"] = itemname.innerHTML;
items["price"] = itemprice.innerHTML;
items["quantity"] = itemquantity.innerHTML;
items["total"] = itemtotal.innerHTML;
jsonObj.push(items);
}
console.log(items);
var formdata = {};
formdata["textbox"] = $("#textbox").val();
formdata["name"] = $("#name").val();
formdata["phone"] = $("#phone").val();
formdata["email"] = $("#email").val();
formdata["address"] = $("#address").val();
formdata["grandtotal"] = simpleCart.grandTotal();
var x =
{
"cart" : jsonObj,
"formdata" : formdata,
"captchaResponse" : $("#g-recaptcha-response").val()
};
//jsonString = jsonObj+formdata;
var y = JSON.stringify(x);
console.log(y);
var result = jQuery.parseJSON(y);
console.log(result);
// Serialize the form data.
//var formData = $(form).serialize();
// Submit the form using AJAX.
$.ajax({
type: "post",
url: "sendjs.php" ,
//url: $(form).attr("action"),
data: y,
contentType: "application/json; charset=utf-8",
traditional: true,
success: function (response) {
if(response=="Thank You! Your message has been sent.")
{
//remove the button animation
$(spinner).addClass("hidden");
$(formMessages).removeClass("error");
$(formMessages).addClass("success");
$("#textbox").val("");
$("#name").val("");
$("#email").val("");
$("#message").val("");
$("#phone").val("");
$("#address").val("");
}
else
{
$(formMessages).removeClass("success");
$(formMessages).addClass("error");
$(spinner).addClass("hidden");
$(submit).removeClass("hidden");
}
$(formMessages).text(response);
}
});
});
});
sendjs.php
<?php
//Debugging
//ini_set( 'display_errors', 1 );
//error_reporting( E_ALL );
//replaces file_get_contents due to restrictions on server
function get_data($url)
{
$ch = curl_init();
$timeout = 5;
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT,$timeout);
$data = curl_exec($ch);
curl_close($ch);
return $data;
}
//turn url_fopen on due to restrictions on server
//ini_set('allow_url_fopen', true);
date_default_timezone_set('Australia/Perth');
$time = date ("h:i A");
$date = date ("l, F jS, Y");
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$captcha = $obj["captchaResponse"];
$captcha;
$secretKey = "scrubbed";
$ip = $_SERVER['REMOTE_ADDR'];
$response = get_data("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
//not used due to server restictions
//$response=file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=".$secretKey."&response=".$captcha."&remoteip=".$ip);
$responseKeys = json_decode($response,true);
if(intval($responseKeys["success"]) !== 1) {
echo "Please Click on the Captcha";
return false;
}
else
{
//echo $items;
$name = $obj["formdata"]["name"];
$phone = $obj["formdata"]["phone"];
$email = $obj["formdata"]["email"];
$textbox = $obj["formdata"]["textbox"];
$address = $obj["formdata"]["address"];
$grandtotal = $obj["formdata"]["grandtotal"];
$text = "<html style='font-family:arial'>
<body>
<h1 style='color:crimson;'>DIY Soakwells</h1>
<p>This order was submitted from www.diysoakwells.com.au on $date at $time</p>
<p>$name thank you for your order inquiry. Deliveries are normally every Friday, we will be in contact shortly to discuss your order and confirm a time.</p>
<p>An invoice will be issued after delivery for payment via bank transfer.</p>
<p>In the meantime if you haven't already seen it, you can take a look at www.soakwellcalculator.com.au to confirm the number of soakwells you ordered will be adequate.</p>
<br>
<h2 style='color:crimson;'>CUSTOMER DETAILS</h2>
<p><b>Email:</b>\n$email</p>
<p><b>Name:</b>\n$name</p>
<p><b>Phone:</b>\n$phone</p>
<p><b>Delivery Address:</b>\n$address</p>
<p><b>Message:</b>\n$textbox</p>
<br>
<h2 style='color:crimson;'>ORDER DETAILS</h2>";
$items_in_cart = count($obj["cart"]);
for($i=0; $i < $items_in_cart; $i++) {
$iname = $obj["cart"][$i]["name"];
$price = $obj["cart"][$i]["price"];
$quantity = $obj["cart"][$i]["quantity"];
$total = $obj["cart"][$i]["total"];
//display looped cart data
$items .= "<p>$iname x $quantity - $price <small>ea.</small> <b>Sub Total: </b> $total .</p>";
}
$final_total ="<br>
<p><b>Total: </b>$$grandtotal <small>inc. GST</small></p>
</body>
</html>";
//Email Content
$body = $text.$items.$final_total;
// Set the email subject.
$subject = "New order from $name";
// Build the email content.
$email_content = $body;
// Build the email headers.
$email_headers = 'MIME-Version: 1.0' . PHP_EOL;
$email_headers .= 'Content-Type: text/html; charset=ISO-8859-1' . PHP_EOL;
//$email_headers .= 'To:' . $name . '<' . $email . '>' . PHP_EOL;
$email_headers .= 'From: DIY Soakwells <orders#diysoakwells.com>' . PHP_EOL;
$email_headers .= 'CC: orders#diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'Reply-To: DIY Soakwells <orders#diysoakwells.com.au>' . PHP_EOL;
$email_headers .= 'Return-Path: DIY Soakwells <orders#diysoakwells.com>' . PHP_EOL;
$email_headers .= 'X-Sender: DIY Soakwells <orders#diysoakwells.com.au' . PHP_EOL;
$email_headers .= 'X-Mailer: PHP/' . phpversion() . PHP_EOL;
//$email_headers .= 'X-Priority: 1' . PHP_EOL;
//validate Email
$email_check = filter_input(INPUT_POST, $email, FILTER_VALIDATE_EMAIL);
//Recipients
$to = $email;
if (mail($to, $subject, $email_content, $email_headers, '-forders#diysoakwells.com.au')) {
// Set a 200 (okay) response code.
//http_response_code(200);
echo "Thank You. Your order has been sent and a copy mailed to your inbox.";
} else {
// Set a 500 (internal server error) response code.
//http_response_code(500);
echo "There appears to be an issue with our server, please ring 0420 903 950 or email contact#diysoakwells.com.au.";
}
}
?>
Hope someone can give me some tips.
because your condition is response == "Thank You! Your message has been sent."
and your results are
"Please Click on the Captcha", "Thank You. Your order has been sent and a copy mailed to your inbox.", "There appears to be an issue with our server, please ring 0420 903 950 or email contact#diysoakwells.com.au.".
so all of your result will do else part
My php runs but for some reason my variables are not being communicated. What am I doing incorrectly? I am trying to relay the message through ajax and i can't seem to get any type of error or success message to pop up, no matter where I put it in my php..which leads me to believe that the problem lies inside my ajax/javascript functions. The ajax should place the message straight in the defined . I also realize this has been asked before on here but I have truly looked at a lot of them and still can not figure out what's wrong. Thanks guys, sorry for the wall.
AJAX
<!-- Email -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script>
// magic.js
$(document).ready(function() {
// process the form
$('form').submit(function(event) {
$('#sub_result').html("");
// get the form data
// there are many ways to get this data using jQuery (you can use the class or id also)
var formData = {
'email' : $('input[name=email]').val(),
};
// process the form
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'phEmail.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true
})
// using the done promise callback
.done(function(data) {
// log data to the console so we can see
console.log(data);
// here we will handle errors and validation messages
if ( ! data.success) {
// handle errors for email ---------------
if (data.errors.email) {
$('#sub_result').addClass('class="error"'); // add the error class to show red input
$('#sub_result').append('<div class="error">' + data.errors.email + '</div>'); // add the actual error message under our input
}
} else {
// ALL GOOD! just show the success message!
$('#sub_result').append('<div class="success" >' + data.message + '</div>');
// usually after form submission, you'll want to redirect
// window.location = '/thank-you'; // redirect a user to another page
}
})
// using the fail promise callback
.fail(function(data) {
// show any errors
// best to remove for production
console.log(data);
});
// stop the form from submitting the normal way and refreshing the page
event.preventDefault();
});
});
</script>
PHP
<?php
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
// validate the variables ======================================================
// if any of these variables don't exist, add an error to our $errors array
if(filter_var($_POST['email'],FILTER_VALIDATE_EMAIL) === false)
{
$errors['email'] = 'Email is not valid';
}
if (empty($_POST['email'])){
$errors['email'] = 'Email is required.';
}
// if there are items in our errors array, return those errors============================
if ( ! empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
//variables===============================================================================
$servername = "localhost";
$username = "ghostx19";
$password = "nick1218";
$dbname = "ghostx19_samplepacks";
$user = $_POST['email'];
// Create connection======================================================================
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
echo "Connection failed";
}
//add user================================================================================
$sql = "INSERT INTO users (email)
VALUES ('$user')";
if ($conn->query($sql) === TRUE) {
$data['success'] = true;
$data['message'] = 'Subscribed!';
} else {
$errors['email'] = 'Error';
}
$conn->close();
// message to me==========================================================================
$to = 'garvernr#mail.uc.edu';
$subject = 'New subscription';
$message = $_POST['email'];
$headers = 'From: newsubscription#samplepackgenerator.com' . "\r\n" .
'Reply-To: newsubscription#samplepackgenerator.com';
mail($to, $subject, $message, $headers);
//message to user=========================================================================
$to = $_POST['email'];
$subject = 'Subscribed!';
$message = 'Hello new member,
Thank you for becoming a part of samplepackgenerator.com. You are now a community member and will recieve light email updates with the lastest information. If you have recieved this email by mistake or wish to no longer be apart of this community please contact nickgarver5#gmail.com
Cheers!,
-Nick Garver ';
$headers = 'From: newsubscription#samplepackgenerator.com' . "\r\n" .
'Reply-To: newsubscription#samplepackgenerator.com';
mail($to, $subject, $message, $headers);
// show a message of success and provide a true success variable==========================
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
?>
HTML
<!-- Subscription -->
<div class="container shorter">
<div class="no-result vertical-align-outer">
<div class="vertical-align">
<form action="phEmail.php" method="POST">
<!-- EMAIL -->
<div id="email-group" class="form-group">
<label for="email"></label>
<input type="text" class="email" name="email" placeholder="Enter your email">
<button type="submit" class="emailbtn">Subscribe</button>
<span></span>
<!-- errors -->
</div>
</div>
</div>
</div>
<br>
<br>
<div id="sub_result">
</div>
You just need to use json_encode in your PHP becuase your data type is json and you are expecting the response in json format like that
if (!empty($error)){
// your stuff
$data['success'] = false;
$data['errors'] = $errors;
echo json_encode($data);
}
else {
// your stuff
$data['success'] = "SUCCESS MESSAGE";
$data['errors'] = false;
echo json_encode($data);
}
That's because you forgot to encode your $data array. Do echo json_encode($data); just before your ending PHP tag(?>), like this:
// your code
mail($to, $subject, $message, $headers);
// show a message of success and provide a true success variable==========================
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
echo json_encode($data);
?>
Your php don't return any value, add a simple "echo" line at the end:
...
$data['success'] = true;
$data['message'] = 'Subscribed!';
}
echo $data['message'];
?>
And in js (if all the other code is correct) you receive the message.
Your php file doesn't send anything to the output.
Add a line
exit(json_encode($data));
to your php file on the line where you want to return your reply.
I am trying to send an email from a form using php ,here is my PHP code(along with the validation ,didn't want to leave anything out :_)
<?php
/*
* Contact Form Class
*/
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$admin_email = 'sgg3590#rit.edu'; // Your Email
$message_min_length = 5; // Min Message Length
class Contact_Form{
function __construct($details, $email_admin, $message_min_length){
$this->name = stripslashes($details['name']);
$this->email = trim($details['email']);
$this->subject = 'Contact from Your Website'; // Subject
$this->message = stripslashes($details['message']);
$this->email_admin = $email_admin;
$this->message_min_length = $message_min_length;
$this->response_status = 1;
$this->response_html = '';
}
private function validateEmail(){
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($this->email == '') {
return false;
} else {
$string = preg_replace($regex, '', $this->email);
}
return empty($string) ? true : false;
}
private function validateFields(){
if(!$this->name)
{
$this->response_html .= '<p>Please enter your name</p>';
$this->response_status = 0;
}
// Check email
if(!$this->email)
{
$this->response_html .= '<p>Please enter an e-mail address</p>';
$this->response_status = 0;
}
// Check valid email
if($this->email && !$this->validateEmail())
{
$this->response_html .= '<p>Please enter a valid e-mail address</p>';
$this->response_status = 0;
}
// Check message length
if(!$this->message || strlen($this->message) < $this->message_min_length)
{
$this->response_html .= '<p>Please enter your message. It should have at least '.$this->message_min_length.' characters</p>';
$this->response_status = 0;
}
}
private function sendEmail(){
$mail = mail($this->email_admin, $this->subject, $this->message,
"From: ".$this->name." <".$this->email.">\r\n"
."Reply-To: ".$this->email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
$this->response_status = 1;
$this->response_html = '<p>Thank You!</p>';
}
else
{
$this->response_status = 0;
$this->response_html = '<p>Sending failed</p>';
}
}
function sendRequest(){
$this->validateFields();
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo json_encode($response);
}
}
$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();
?>
here is how I am calling it
BRUSHED.contactForm = function(){
$("#contact-submit").on('click',function() {
$contact_form = $('#contact-form');
var fields = $contact_form.serialize();
$.ajax({
type: "POST",
url: "_include/php/contact.php",
data: fields,
dataType: 'json',
success: function(response) {
if(response.status){
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$('#response').empty().html(response.html);
}
});
return false;
});
}
And here is my form
<form id="contact-form" class="contact-form" action="#">
<p class="contact-name">
<input id="contact_name" type="text" placeholder="Full Name" value="" name="name" />
</p>
<p class="contact-email">
<input id="contact_email" type="text" placeholder="Email Address" value="" name="email" />
</p>
<p class="contact-message">
<textarea id="contact_message" placeholder="Your Message" name="message" rows="5" cols="40"></textarea>
</p>
<p class="contact-submit">
<a id="contact-submit" class="submit" href="#">Send Your Email</a>
</p>
<div id="response">
</div>
</form>
The validations work proper so its going to the php file, but I can't send the email and the response div is not fill after I push the send button(neither with thank you or sending fail)
I followed this code from a website and I Don't really understand whats wrong here.. :(
First make sure you have set your machine host same as domain name, as sometimes mail-servers will deny mail-headers that doesn't have matching domain, like Sender: test#test.org but From: localhost.
Then, install postfix so it will correct any improper / incorrect stuff in the email and lastly, you're missing email headers there. Here are my example that works for me:
<?php
try {
$to = 'user#test.org';
$subject = 'Mail Test';
$message = <<<TEXT
Mail request received
TEXT;
$message = str_replace("\n.", "\n..", $message);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Test Org. <webmaster#test.org>' . "\r\n" .
'Reply-To: webmaster#test.org' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
printf("Mail sent to " + $to);
} catch (Exception $e) {
printf("Error occured: " + $e);
}
?>
If it still fails, you can try sending a test message from console echo "this is the body" | mail -s "test" "receipent#test.org" and see if it works. If both failed, best to ask server vendor as maybe they have set outgoing mail disabled or something.
Well I was using local host with WAMP and realized wamp server doesn't provide the functionality . THe code is good and working though.
Thanks
I'm using the Jquery Ajax to post a form data and display the success message. Everything works fine, but I'm not able to display the success message. Below is the code :
Javascript
<script>
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#stage').empty();
var postForm = { //Fetch form data
"name": $("#name").val(),
"element_4_1": $("#element_4_1").val(),
"element_4_2": $("#element_4_2").val(),
"element_4_3": $("#element_4_3").val(),
"email": $("#email").val(),
"input4": $("#input4").val(),
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'contact.php', //Your form processing file url
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
console.log("inside success3") ;
alert(data);
$("#stage").html(data);
if (!data.success) { //If fails
if (data.errors) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors); //Throw relevant error
console.log("inside failure") ;
}
} else {
console.log("inside success") ;
$('#stage').fadeIn(1000).append('<p>' + data.posted + '</p>');
console.log("inside success2") ;
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
</script>
PHP :
<?php
ini_set('display_errors','On');
error_reporting(E_ALL);
$errors = array();
$form_data = array();
header('Content-type: application/json');
echo json_encode($form_data);
$name=$_POST['name'];
$phone=chop($_POST['element_4_1']);
$phone.=chop($_POST['element_4_2']);
$phone.=chop($_POST['element_4_3']);
$email=chop($_POST['email']);
$message1=chop($_POST['input4']);
if ($name && $phone && $email) {
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: sales#test.com \n";
$recipient= "test#test.in";
$subject="Online Enquiry ";
$message="\nName : $name\n";
$message.="\nPhone : $phone\n";
$message.="\nEmail ID : $email\n";
$message.="\nMessage : $message1\n";
//send auto-reply
$subject_reply="Thank you for contacting us";
$message_reply="Thank you for contacting us. We will get back to you shortly.";
//mail($email, $subject_reply, $message_reply, $headers);
//Send Mail
//===========
if(isset($recipient, $subject, $message, $headers)) {
error_log($message);
$form_data['status'] = 'success';
error_log($form_data['status']);
} else {
$form_data['status'] = 'error';
error_log($form_data['status']);
} ?>
HTML
<div id="stage">
</div>
How can I print the success message
You have this at the start of your php script:
echo json_encode($form_data);
where $form_data is an empty array at that time.
You should remove that and put it at the end.