I have been trying to send an Email from a contact form using Ajax.
When the mail is sent, It should return a confirmation message :
"thank you for contacting us".
Instead of displaying this message i have an error:
{"type":"success","message":"thank you for contacting us"} parsererror SyntaxError: Unexpected number in JSON at position 8
at JSON.parse (<anonymous>)
at parseJSON (jquery.js:4)
at On (jquery.js:6)
at k (jquery.js:6)
at XMLHttpRequest.r (jquery.js:6)`
Here is my PHP File sending the mail:
<?php
require_once 'phpmailer/PHPMailerAutoload.php';
$okMessage = 'thank you for contacting us';
$name = #trim(stripslashes($_POST['name']));
$email = #trim(stripslashes($_POST['email']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$societe = #trim(stripslashes($_POST['societe']));
$num = #trim(stripslashes($_POST['num']));
$body = 'Name: ' . $name . "\n\n" . 'Entreprise: ' . $societe . "\n\n" . 'contact Tel: ' . $num . "\n\n" . 'Email: ' . $email . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = 'xxxxx';
$mail->Port = xx; //
$mail->CharSet = 'UTF-8';
$mail->SMTPAuth = true;
$mail->SMTPDebug = 2;
$mail->Username = "xxxx";
$mail->Password = "xxxx";
$mail->setFrom('xxxx','xxxx');
$mail->addAddress('xxxx');
$mail->Subject = $subject;
$mail->Body = $body;
$mail->send();
header('Content-type: application/json');
$status = array(
'type' => 'success',
'message' => $okMessage
);
echo json_encode($status);
die;
Here is my JS function
var form = $('#main-contact-form');
form.submit(function(event){
event.preventDefault();
var form_status = $('<div class="form_status"></div>');
var req = $.ajax({
url: $(this).attr('action'),
type: "POST",
data: form.serialize(),
dataType : 'json',
beforeSend: function(){
form.prepend( form_status.html('<p><i class="fa fa-spinner fa-spin"></i> Email is sending...</p>').fadeIn() );
}
});
req.done( function( data, textStatus, jqXHR ){
console.log( data, textStatus, jqXHR );
console.warn( jqXHR.responseText);
form_status.html('<p class="text-success">' + data.message + '</p>').delay(3000).fadeOut();
});
req.fail( function( jqXHR, textStatus, errorThrown ){
console.log( jqXHR.responseText, textStatus, errorThrown );
console.warn( jqXHR.responseText);
form_status.html('<p class="text-error">' + textStatus + '</p>').delay(3000).fadeOut();
});
});
Can you help me please?
I have resolved the problem.
In the network tab of my browser, i saw that the response was not only Json.
I realised that it was caused by the parameter
$mail->SMTPDebug = 2;
In fact, it returned me the whole conversation between Server and Client, before printing the response in JSON.
So I replace it by
$mail->SMTPDebug = 0;
and every thing is ok now.
Thanks for the help
Related
I have some issue with showing the response alert of the form.
$(function () {
// when the form is submitted
$('#contact-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "contact.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data.type;
var messageText = data.message;
// let's compose Bootstrap alert box HTML
var alertBox = '<div class="alert ' + messageAlert + ' alert-dismissable"><button type="button" class="close" data-dismiss="alert" aria-hidden="true">×</button>' + messageText + '</div>';
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// inject the alert to .messages div in our form
$('#contact-form').find('.messages').html(alertBox);
// empty the form
$('#contact-form')[0].reset();
// }
}
});
return false;
}
})
});
php file looks like that
try
{
if(count($_POST) == 0) throw new \Exception('Form is empty');
$emailText = "You have a new message from your contact form\n=============================\n";
foreach ($_POST as $key => $value) {
// If the field exists in the $fields array, include it in the email
if (isset($fields[$key])) {
$emailText .= "$fields[$key]: $value\n";
}
}
// All the neccessary headers for the email.
$headers = array('Content-Type: text/plain; charset="UTF-8";',
'From: ' . $from,
'Reply-To: ' . $from,
'Return-Path: ' . $from,
);
// Send email
mail($sendTo, $subject, $emailText, implode("\n", $headers));
$responseArray = array('type' => 'success', 'message' => $okMessage);
}
catch (\Exception $e)
{
$responseArray = array('type' => 'danger', 'message' => $errorMessage);
}
The thing is that if (messageAlert && messageText) is never TRUE since the variables are that time undefined. Though emails are sent successfully and console.log(data) in js file prints wanted data.
Could you please help me to solve the problem?
You send the email, you create the response Array but you don't pass it to the ajax call.
Where is the echo of the responseArray?
The best way I suggest you is to pass it as a json data:
echo json_encode($responseArray);
And then read in the javascript function
var json = $.parseJSON(data);
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
I have problems :
My code for emailing is working, but I don't think its the right way to do so. Is it possible to use the $http service inside an AngularJS foreach loop? Will it overheat the process, if each loop is destined to PhpMailer to send one mail each time? Should I use the $q service? The code works to send a low amount of emails but will it overheat the php script if more emails are sent?
AngularJS code
$scope.submit = function(contactform) {
$scope.submitted = true;
$scope.submitButtonDisabled = true;
angular.forEach($scope.intervenants,function(data){
var x = angular.copy($scope.formData);
x.destinataire = data.email;
$http({
method : 'POST',
url : 'contact-form.php',
data : $.param(x), //param method from jQuery
headers : { 'Content-Type': 'application/x-www-form-urlencoded' } //set the headers so angular passing info as form data (not request payload)
}).success(function(data){
console.log(data);
if (data.success) { //success comes from the return json object
$scope.submitButtonDisabled = true;
$scope.resultMessage = data.message;
$scope.result='bg-success';
} else {
$scope.submitButtonDisabled = false;
$scope.resultMessage = data.message;
$scope.result='bg-danger';
}
});
});
}
PhpMail code
//check if any of the inputs are empty
if (empty($_POST['inputName']) || empty($_POST['inputEmail']) || empty($_POST['inputSubject']) || empty($_POST['inputMessage'])) {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
exit;
}
//create an instance of PHPMailer
$mail = new PHPMailer();
$mail->IsSMTP();
$mail->Host = "smtp.orange.fr";
$mail->From = $_POST['inputEmail'];
$mail->FromName = $_POST['inputName'];
$mail->AddAddress($_POST['destinataire']); //recipient
$mail->Subject = $_POST['inputSubject'];
$mail->Body = "Name: " . $_POST['inputName'] . "\r\n\r\nMessage: " . stripslashes($_POST['inputMessage']);
if (isset($_POST['ref'])) {
$mail->Body .= "\r\n\r\nRef: " . $_POST['ref'];
}
if(!$mail->send()) {
$data = array('success' => false, 'message' => 'Message could not be sent. Mailer Error: ' . $mail->ErrorInfo);
echo json_encode($data);
exit;
}
$data = array('success' => true, 'message' => 'Thanks! We have received your message.');
echo json_encode($data);
} else {
$data = array('success' => false, 'message' => 'Please fill out the form completely.');
echo json_encode($data);
}
I have a php function handling the results of a form delivered from a jQuery script, as the form content is also delivered to a Workbooks CRM url to be added to records there.
All works fine, except the email is sent 3 times. The button clicked is not inside the form, and the 'send' value for isset($_POST) is delivered from a hidden form field in the form.
I've tried:
Adding flags, both in PHP and in the jQuery.
Adding alerts in the jQuery.
Adding exit("sent"); after the mail() function.
The alert() experiment appeared to indicate the jQuery wasn't the issue, but flags seemed to indicate the same in the PHP!
Here's the jQuery:
$(document).ready(function () {
$("#test-vf-button1").click(function (event) {
event.preventDefault();
// Field values as array
var name = $("#name").val();
var email = $("#email").val();
var message = $("#message").val();
var formData = $("#wb_form").serialize();
var url = $(location).attr('hostname');
var pathname = $(location).attr('pathname');
var pageUrl = url + pathname;
console.log(pageUrl);
$("#validate-message").empty();
$("#confirm-message").empty();
if (name == '' || email == '' || message == '') {
$("#validate-message").append(" Fill in required fields");
} else {
// Returns successful data submission message when the entered information is stored in database.
$.ajax({
type: 'POST',
url: "http://visual-factory.co.uk/",
data: formData,
success: function () {
$.ajax({
type: 'POST',
url: "https://secure.workbooks.com/crm/web_leads",
crossDomain: true,
data: formData,
dataType: 'text',
success: function () {
PHP handling function:
function vf_deliver_mail() {
// if the submit button is clicked, send the email
if ( isset( $_POST['send'] ) ) {
// sanitize form values
$title = sanitize_text_field( $_POST['person_lead_party']['person_personal_title'] );
$name = sanitize_text_field( $_POST['person_lead_party']['name'] );
$jobrole = sanitize_text_field( $_POST['person_lead_party']['person_job_role'] );
$email = sanitize_text_field( $_POST['org_lead_party']['main_location']['email']);
$phone = sanitize_text_field( $_POST['org_lead_party']['main_location']['telephone'] );
$company = sanitize_text_field( $_POST['org_lead_party']['name'] );
$country = sanitize_text_field( $_POST['org_lead_party']['main_location']['country'] );
$messagecontent = esc_textarea( $_POST['vf-message'] );
$message = "<p>Title: ".$title."</p>";
$message .= "<p>Name of lead is: ".$name."</p>";
$message .= "<p>Job Role: ".$jobrole."</p>";
$message .= "<p>Email is: ".$email."</p>";
$message .= "<p>Phone is: ".$phone."</p>";
$message .= "<p>Company is: ".$company."</p>";
$message .= "<p>Country is: ".$country."</p>";
$message .= "<p>Message: ".$messagecontent.".</p>";
// get the blog administrator's email address
$to = get_option( 'admin_email' );
$subject = "Form response";
$headers = "From: $name <$email>" . "\r\n";
mail( $to, $subject, $message, $headers ) ;
}
}
I am trying to use this code to pass via POST a variable containing HTML
var data = {
message: $('#mydiv').html()
};
jQuery.ajax({
type: 'POST',
data: data,
url: '/myurl?action=send_email',
success: function( response ) { }
});
In PHP, I retrieve the data and I send an Email using the data content
$message = "Hello<br>" . $_POST['message'] . "<br>Bye Bye";
$mail = mail($email, $subject, nl2br($message), $headers);
The HTML within the email that I receive is badly formatted:
<img width="\"70\"" height="\"87\"" alt="\"D_6928_antiqueoak_vapor\"">
Can someone tell me why and if there is a solution? Thank you a lot
Try this method using encodeURIComponent()
var data = 'message='+$('#mydiv').html();
jQuery.ajax({
type: 'POST',
data: encodeVars(data),
url: '/myurl?action=send_email',
success: function( response ) { }
});
function encodeVars(vars){
return vars.map(function (cell) {
var res = cell.split('=');
return res[0] + '=' + encodeURIComponent(res[1]);
}) ;
}
Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
I solved in that way. Javascript
var data = {
message: $('#mydiv').html()
};
jQuery.ajax({
type: 'POST',
data: data.replace(/&/g, "&")
.replace(/"/g, """)
.replace(/'/g, "'"),
url: '/myurl?action=send_email',
success: function( response ) { }
});
PHP
$message = preg_replace('/&/', '&', $_POST['message']);
$message = preg_replace('/"/', '"', $message);
$message = preg_replace('/'/', "'", $message);
$message = "Hello<br>" . $message . "<br>Bye Bye";
$mail = mail($email, $subject, nl2br($message), $headers);