I am working on the jquery to upload the attachments so I can post the files name via ajax. I have got a problem with storing the files name in the array and display each file name in the loop, because it will store 2 files name in the array in one index using this code:
$(".file-list_yhs").each(function() {
attachments[i++] = $(this).find('.vI').text();
});
Output:
Array
{
[0] => uploads/add email.txtemail.zip
}
Array
It should be:
Array
{
[0] => uploads/add email.txt
}
Array
{
[1] => uploads/email.zip
}
Here is the full code:
$(document).on('click','#domodal_send', function(e) {
if ($(".notify-outer").css('display') == 'none') {
var email = $("#domodal_email_receipt").val();
var subject = $("#domodal_subject").val();
var from_name = $("#avater_name").text();
var from_email = $('#avater_email').text();
var emailbody = $("#domodal_message").html();
var attachments = [];
var i = 0;
$(".file-list_yhs").each(function() {
attachments[i++] = $(this).find('.vI').text();
});
$.ajax({
url: 'sendMail.php',
type: 'POST',
data : {
send_to: email,
from: from_name,
from_email: from_email,
emailsubject: subject,
emailbody: emailbody,
emailattachment: attachments
},
success: function(result)
{
alert(result);
}
});
}
});
SendMail.php:
<?php
require_once "Mail.php";
require_once "Mail/mime.php";
require_once('Mail/IMAPv2.php');
//Connect to the database
include('config.php');
$inbox = '{imap.example.com:993/imap/ssl/novalidate-cert}INBOX';
$mailserver = '{imap.example.com:993/imap/ssl/novalidate-cert}INBOX.Sent';
if (isset($_POST['send_to']))
{
$from = "Robert <rob#example.com>";
$to_email = $_POST['send_to'];
$to = $firstname . " <$to_email>";
$subject = $_POST['emailsubject'];
$message = $_POST['emailbody'];
$message_without_image = $_POST['emailbody'];
$filenames = $_POST['emailattachment'];
$files = [];
foreach ($filenames as $filename) {
$files[] = 'uploads/' . $filename;
}
print_r($files);
$username = 'username';
$password = 'password';
$smtp_hostname = "smtp.example.com";
$port = "587";
echo $files;
/*$messageID = sprintf("<%s.%s#%s>",
base_convert(microtime(), 10, 36),
base_convert(bin2hex(openssl_random_pseudo_bytes(8)), 16, 36),
'example.com');
$date = date('Y-m-d H:i:s');
$emailID = '';
$sent_db = "SELECT email_id FROM sent WHERE email_id = '$messageID'";
$sent_result = mysqli_query($link, $sent_db) or die($link->error);
if(mysqli_num_rows($sent_result) == 0)
{
$sent_db1 = "INSERT INTO sent (id, email_id, email, sendDateTime, isRead, readDateTIme) VALUES ('', '$messageID', '$to', '$date', '0', '0000-00-00 00:00:00')";
if (mysqli_query($link, $sent_db1)) {
$emailID = mysqli_insert_id($link);
}
}
$message .= "<img src=\"http://test.example.com/project/track/Images/signature.gif?id=".$emailID."&etc=".time()." \" style=\"width: 0; max-height:0; overflow:hidden; \">";
$headers = array ('From' => $from,
'To' => $to, 'Subject' => $subject,
'Reply-To' => $from,
'Content-Type' => 'Content-Type: text/plain; charset=UTF-8',
'MIME-Version' => '1.0',
'Received' => 'from smtp.example.com',
'Date' => date("r"),
'Message-ID' => sprintf("<%s.%s#%s>",
base_convert(microtime(), 10, 36),
base_convert(bin2hex(openssl_random_pseudo_bytes(8)), 16, 36),
'example.com'));
$params = array ('host' => $smtp_hostname,
'port' => $port,
'auth' => 'PLAIN', // Note 1
'socket_options' => array('ssl' => array('verify_peer_name' => false, 'verify_peer' => false)), // Note 2
'username' => $username,
'password' => $password);
$mime_params = array(
'text_encoding' => '7bit',
'text_charset' => 'UTF-8',
'html_charset' => 'UTF-8',
'head_charset' => 'UTF-8'
);
$crlf = "\r\n";
$mime = new Mail_mime(array('eol' => $crlf));
$body = $message;
$mime->setTXTBody($body);
$mime->setHTMLBody($body);
if(!empty($files)) {
$mime->addAttachment($files);
}
$body = $mime->get($mime_params);
$headers = $mime->headers($headers);
$smtp = Mail::factory ('smtp', $params);
$mail = $smtp->send($to, $headers, $body);
if (PEAR::isError($mail))
{
echo("<p>" . $mail->getMessage() . "</p>");
}
else
{
echo("<p>Email has been sent!</p>");
}
}
?>
What I am trying to do is to store the files name in the array and post it via ajax after I have uploaded the files on my server. When the files is upload on the server, I can be able to output each files name to add the files location on the server and send the email with the attachments.
Can you please show me an example how I could store each file name in the loop where I could use it to post it with ajax to output each file name?
Thank you.
EDIT: Here is the html:
<div style="width: 70%; margin-left: 10px; position:relative;" class="file-list_yhs">
<div class="dL" tabindex="-1" id=":vw" aria-label="Attachment: edit_link1.png. Press enter to view the attachment and delete to remove it" style="position:relative;">
<input id=":vp" name="attach" type="hidden" value="#msg-a:r-6685135251679589431_#msg-a:r-6685135251679589431_null_-1" checked="">
<div style="display:flex">
<a class="dO" id=":vq" style="display:flex;">
<div id="domodal_attachment" class="vI">addd her email.txt</div>
<div class="vJ">(0K)</div>
</a>
<div id=":vn" role="button" aria-label="Remove attachment" class="vq" tabindex="-1" data-tooltip="Remove attachment" style="position:absolute; right:5px; top:5px;"></div>
</div>
</div>
<div class="dL" tabindex="-1" id=":vw" aria-label="Attachment: edit_link1.png. Press enter to view the attachment and delete to remove it" style="position:relative;">
<input id=":vp" name="attach" type="hidden" value="#msg-a:r-6685135251679589431_#msg-a:r-6685135251679589431_null_-1" checked="">
<div style="display:flex">
<a class="dO" id=":vq" style="display:flex;">
<div id="domodal_attachment" class="vI">email.zip</div>
<div class="vJ">(183K)</div>
</a>
<div id=":vn" role="button" aria-label="Remove attachment" class="vq" tabindex="-1" data-tooltip="Remove attachment" style="position:absolute; right:5px; top:5px;"></div>
</div>
</div>
</div>
You're creating an array element for each .file-list_yhs DIV, not for each .vI DIV. $(this).find('.vI').text() will concatenate the texts of all the .vI elements that it finds in each .file-list_yhs.
Change your loop to
$(".file-list_yhs .vI").each(function() {
attachments.push($(this).text());
}
You can also use .map:
attachments = $(".file-list_yhs .vI").map(function() {
return $(this).text();
}).get();
.get() is needed at the end to convert the jQuery object that .map() returns to an array.
Related
I am trying to create an email form with a cart that then sends the Summary of the Cart displayed to the user. How can i send the content of the cart div?
I am using a E-Mail form i found online that works with bootstrap 4. It has the function to grab all active form fields and send those. The thing is once i use a checkbox it displays these as on or off and not the value e.g yes or no. I found solutions but am not sure on how to implement those.
<div class="form-group font" id="cart" style="border: 5px solid white; width: 40%; padding: 5px 5px 5px 5px;">
<h5>Übersicht</h5>
<div id="descript10">Vorname: <b id="vorname"></b></div>
<div id="descript11">Nachname: <b id="nachname"></b></div>
<div id="descript12">Alter: <b id="alter"></b></div>
<div id="descript1">Buchen: <b id="booking">Nein</b></div>
<div id="descript2" style="display:none;">Preisklasse: <b id="type"></b></div>
<div id="descript3" style="display:none;">Alles: <b id="all">Ja</b></div>
<div id="descript4" style="display:none;">Mischpult: <b id="mixer">Ja</b></div>
<div id="descript5" style="display:none;">Anlage: <b id="sound">Ja</b></div>
<div id="descript6" style="display:none;">Lichteffekte: <b id="light">Ja</b></div>
<div id="descript7" style="display:none;">Nebelmaschine: <b id="fog">Ja</b></div>
<div id="descript8" style="display:none;">Nachricht: <b id="nachricht"></b></div>
</div>
<input type="submit" class="btn btn-success btn-send" value="Abschicken" data-disable="true">
<p class="text-muted font">
<strong>*</strong> Pflichtfelder
</p>
<?php
// require ReCaptcha class
require('recaptcha-master/src/autoload.php');
// configure
// an email address that will be in the From field of the email.
$from = 'example2#mail.com';
// an email address that will receive the email with the output of the form
$sendTo = 'example#mail.com';
// subject of the email
$subject = 'New message';
// form field names and their translations.
// array variable name => Text to appear in the email
$fields = array('name' => 'Vorname', 'surname' => 'Nachname', 'email' => 'Email', 'buchen' => 'Buchen?', 'options' => 'Optionen', 'mischpult' => 'Mischpult', 'anlage' => 'Anlage', 'licht' => 'Lichteffekte', 'nebel' => 'Nebelmaschine', 'message' => 'Nachricht');
// message that will be displayed when everything is OK :)
$okMessage = 'Deine Nachricht wurde erfolgreich gesendet. Ich melde mich so bald wie möglich!';
// If something goes wrong, we will display this message.
$errorMessage = 'Es gab einen Fehler beim senden deiner Nachricht. Versuche es Später nochmal.';
// ReCaptch Secret
$recaptchaSecret = 'secret';
// let's do the sending
// if you are not debugging and don't need error reporting, turn this off by error_reporting(0);
error_reporting(E_ALL & ~E_NOTICE);
try {
if (!empty($_POST)) {
// validate the ReCaptcha, if something is wrong, we throw an Exception,
// i.e. code stops executing and goes to catch() block
if (!isset($_POST['g-recaptcha-response'])) {
throw new \Exception('ReCaptcha is not set.');
}
// do not forget to enter your secret key from https://www.google.com/recaptcha/admin
$recaptcha = new \ReCaptcha\ReCaptcha($recaptchaSecret, new \ReCaptcha\RequestMethod\CurlPost());
// we validate the ReCaptcha field together with the user's IP address
$response = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if (!$response->isSuccess()) {
throw new \Exception('ReCaptcha wurde nicht Validiert.');
}
// everything went well, we can compose the message, as usually
$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' => $e->getMessage());
}
if (!empty($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) == 'xmlhttprequest') {
$encoded = json_encode($responseArray);
header('Content-Type: application/json');
echo $encoded;
} else {
echo $responseArray['message'];
}
So i want to get the content of the div in the mail instead of every single value that is active. I'm no expert, but i'm guessing the foreach function needs to be replaced by a get function to get the content. I just don't know how. The form works, just not the way i want it to. live version can be found here: https://nichola1.myhostpoint.ch/DJ101/contact.php
I am trying to send an email with both a calendar invite and HTML body content, but I can't seem to get the both added to the email object to be sent via SendGrid
I am able to send a calendar invite by itself and HTML body content by itself but not together.
function sendgridAPI(){
GLOBAL $mgClient,$domain,$toName, $toEmail, $fromName, $fromEmail, $subj, $body, $cc, $bcc, $attachments, $mimeMessage, $sendgrid_api_key;
$email = new \SendGrid\Mail\Mail();
$email->setFrom($fromEmail, $fromName);
$email->setSubject($subj);
$toEmails = [$toEmail => $toName,];
$email->addTos($toEmails);
if ($mimeMessage != ""){
echo "<br> 1 <br>";
$contents = [
"text/calendar" => $mimeMessage,
"text/html" => $body
];
$email->addContents($contents);
}
else{
$content = ["text/html" => $body];
$email->addContent($content);
}
if($cc != ""){
$ccEmails = [$cc => "CC",];
$email->addCcs($ccEmails);
}
if ($attachments != ""){
$filePath = $attachments;
$fileName = substr($attachments, strrpos($attachments, '/') + 1);
$fileData = base64_encode(file_get_contents($filePath));
$fileExtension = substr($attachments, strrpos($attachments, '.') + 1);
$fileType = 'application/'. $fileExtension;
$email->addAttachment(
$fileData,
$fileType,
$fileName,
"attachment"
);
$email->addAttachments($attachments);
}
$sendgrid = new \SendGrid($sendgrid_api_key);
try {
$response = $sendgrid->send($email);
$data = $response->headers();
print_r($data);
gettype($data['5']);
$responseSG = substr($data['5'], strpos($data['5'], ":") + 1);
return $responseSG;
//echo $responseSG;
} catch (Exception $e) {
echo 'Caught exception: '. $e->getMessage() ."\n";
return "";
}
}
?>
The variables are passed to this function then the email object is constructed to be sent using the SendGrid API
You need to create an attachment object for addAttachment(), not pass in a filename. And an array of Attachment objects for addAttachments()
https://github.com/sendgrid/sendgrid-php/blob/master/lib/mail/Mail.php#L1152-L1172
Here's the constructor for an Attachment:
https://github.com/sendgrid/sendgrid-php/blob/master/lib/mail/Attachment.php#L35-L52
I am sending an e-mail with different variables as an JSON encoded array from an online store. I get the mail just fine and all the data is in there except for one of the variables, which is a JSON encoded array by itself. this particular variable shows as "false" in the e-mail. I'm missing something?
I'm using PHP mail to do it.
<?php
require_once "Mail.php";
$link = mysqli_connect("localhost", "xxx", "xxx", "xxx");
if ($link === false) {
die("ERROR: Could not connect. " . mysqli_connect_error());
}
$sql = "SELECT * FROM users WHERE user = '" . $_SESSION['logged'] . "'";
$result = mysqli_query($link, $sql);
$row = mysqli_fetch_assoc($result);
$user = $_SESSION['logged'];
$rua = $_POST['rua'];
$numero = $_POST['numero'];
$apt = $_POST['apt'];
$cep = $_POST['cep'];
$total = $_POST['total'];
$comment = $_POST['observacion'];
$from = $row['mail'];
$mailTo = "xxxxx#hotmail.com";
$subject = "compra online - no cep";
$compra = $_SESSION["shopping_cart"];
$compra2 = json_encode($compra);
$bod = array(
'user' => $user,
'rua' => $rua,
'cep' => $cep,
'compra' => $compra2,
'comment' => $comment,
'total' => $total,
);
$body = json_encode($bod);
$headers = array(
'From' => $from,
'To' => $mailTo,
'Subject' => $subject,
);
$smtp = Mail::factory('smtp', array(
'host' => 'smtp-mail.outlook.com',
'port' => '587',
'auth' => true,
'username' => 'xxxxxxx#hotmail.com',
'password' => 'xxxxxxx',
));
$mail = $smtp->send($mailTo, $headers, $body);
if (PEAR::isError($mail)) {
echo ("<p>" . $mail->getMessage() . "</p>");
} else {
header("Location: lojacart.php?mailok");
}
mysqli_close($link);
I'm getting the e-mail with all the data except for the $compra2 variable which is showing as 'compra'=false. now if I echo the variable $compra2 it actually have a large string of data on it.
I think it might have to do with the variable being a JSON encoded session, but I'm not sure.
After a lot of trying and getting frustrated I came with a solution, for those looking for a something like this:
I added a hidden input to the form on the previous page and assigned it a value as "print_r($SESSION['whatever you session is called'], TRUE)" ...
on the next page I took the $_POST[] form that input and added the variable to the $body array for the mail().
It will print some array garbage in the middle BUT it works like a charm! and I cleaned all the "extra" text form the array using preg_replace(). It may not be an elegant way of doing it but as I said... it worked
Ever since I made a change to a send file, I am getting around 20 spam submissions a day on a form. Before the change there was never spam.
The subtle modifications to my send file are shown below. The change solely consisted of how I was getting the POST data. The commented code below was my original and non-commented is what it is now.
$to_requester = Communication::mail_api($_POST, null, $template, 1, "{$_SERVER['DOCUMENT_ROOT']}/PDFs/{$pdf_downloaded}.pdf");
//$to_requester = Communication::mail_api($_POST, null, $template, 1, "../PDFs/" . $file_mapping[$_POST['pdf_downloaded']] . ".pdf");
There are several parts to my form. The process goes in this order:
Submission to Salesforce
Information sent to my database (via ajax)
Notification emails are sent to the user and myself (via ajax)
The spam submissions that are occurring are only submitted to salesforce. They never touch my send file (this includes the db submission and email notifications). The change I noted above is in the send file, so I have no idea why this would have any effect.
I have jQuery validation setup on the form itself.
The salesforce id and other information is held in a config file and called in the form file.
The submissions are entering salesforce like this:
The name/company fields are being filled with some sort of id/code. Again, the send file or database are not being reached with these submissions. The send file is reached with AJAX communicating in-between.
What could be causing these spam submissions? Is there anything I can do validation wise to make sure this spam is not submitted?
Form
<form action="<?php echo $config['sf_url']; ?>" method="POST" id="pdfForm">
<input type=hidden name="oid" value="<?php echo $config['oid']; ?>">
<input type=hidden name="retURL" value="<?php echo $config['retUrl']; ?>">
<input type="text" class="input block" id="first_name" maxlength="40" name="first_name"placeholder="First Name *">
<input type="text" class="input block" id="last_name" maxlength="80" name="last_name" placeholder="Last Name *">
<input type="email" class="input block" id="email" maxlength="80" name="email" placeholder="Email *">
<input id="pdfButton" class="button" type="submit" value="Download File">
</form>
Config
<?php
function getConfig($key)
{
$db = [
'username' => 'user',
'pass' => 'password',
'dbname' => 'db',
];
$ar = [
'sf' => [
'oid' => 'real id',
'sf_url' => 'https://webto.salesforce.com/servlet/servlet.WebToLead?encoding=UTF-8',
'retUrl' => 'https://example.com',
],
'pdo' => new PDO("mysql:host=localhost;dbname={$db['dbname']}", $db['username'], $db['pass'])
];
if(array_key_exists($key, $ar))
return $ar[$key];
}
Send file
ini_set('display_errors', 1);
error_reporting(E_ALL);
require 'classes/Communication.php';
require_once '../config.php';
if ($_SERVER['REQUEST_METHOD'] != 'POST')
exit();
$file_mapping = [
//Index
'Linear Structure' => 'Belt_Driven_Linear_1_3D', //LM Index
'Dynamic Structure' => 'Belt_Driven_Linear_5_3D', //LM MH Index
//LM
'Ball-Screw Application' => 'Belt_Driven_Linear_2_3D',
'Belt-Driven Structure' => 'Belt_Driven_Linear_6_3D',
'Linear Motion Enclosure' => 'Belt_Driven_Linear_7_3D'
];
$first_name = trim(htmlspecialchars($_POST['first_name']));
$last_name = trim(htmlspecialchars($_POST['last_name']));
$email = trim(htmlspecialchars($_POST['email']));
$phone = trim(htmlspecialchars($_POST['phone']));
$company = trim(htmlspecialchars($_POST['company']));
$pdf_downloaded = trim(htmlspecialchars($_POST['pdf_downloaded']));
$page_name = $_POST['page_name'];
$hasError = false;
try {
$config = getConfig('db');
$sent = false;
$con = getConfig('pdo');
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$consult_insert = "
INSERT INTO pdf_submissions
(first_name, last_name, email, phone, company, date, pdf_downloaded, page_source)
VALUES(?,?,?,?,?,NOW(),?,?)
";
$consult_stmt = $con->prepare($consult_insert);
$consult_stmt->execute(array($first_name, $last_name, $email, $phone, $company, $pdf_downloaded, $page_name));
if (!array_key_exists($pdf_downloaded, $file_mapping)) {
$date = new DateTime();
$hasError = true;
file_put_contents('error_log', "\n[{$date->format('Y-m-d H:i:s')}]" . "Error adding attachment: The file selected could not be found in the file mapping. {$pdf_downloaded}.", FILE_APPEND);
}
} catch (PDOException $e) {
// echo "Connection failed: " . $e->getMessage();
}
if ($hasError !== true) {
/************************ Start to Requester ******************************/
$placeholders = [
'{first_name}',
'{last_name}',
'{phone}',
'{company}',
'{email}',
'{pdf_downloaded}'
];
$values = [
htmlentities($_POST['first_name']),
htmlentities($_POST['last_name']),
htmlentities($_POST['phone']),
htmlentities($_POST['company']),
htmlentities($_POST['email']),
htmlspecialchars($_POST['pdf_downloaded']),
];
$template = str_replace($placeholders, $values, file_get_contents("templates/pdf_to_requester.html"));
// Mail subject line goes here
$_POST['subject'] = 'Subject';
$_POST['h:Reply-To'] = 'sales#example.com';
$to_requester = Communication::mail_api($_POST, null, $template, 1, "{$_SERVER['DOCUMENT_ROOT']}/PDFs/{$pdf_downloaded}.pdf");
if (!$to_requester) {
$msg = [
'status_code' => 500,
'status_message' => 'Email Failed to send.'
];
echo json_encode($msg);
}
/************************ End to Requester ******************************/
/************************ Start to Domain ******************************/
$placeholders = [
'{first_name}',
'{last_name}',
'{email}',
'{phone}',
'{company}',
'{file_requested}',
'{page_name}'
];
$values = [
$first_name = trim(htmlspecialchars($_POST['first_name'])),
$last_name = trim(htmlspecialchars($_POST['last_name'])),
$email = trim(htmlspecialchars($_POST['email'])),
$phone = trim(htmlspecialchars($_POST['phone'])),
$company = trim(htmlspecialchars($_POST['company'])),
$pdf_downloaded = trim(htmlspecialchars($pdf_downloaded)),
$page_name = $_POST['page_name'],
];
$template = str_replace($placeholders, $values, file_get_contents("templates/pdf_to_domain.html"));
// Mail subject line goes here
$_POST['subject'] = 'Subject';
$_POST['h:Reply-To'] = 'sales#example.com';
$_POST['sendTo'] = "info#example.com";
$to_company = Communication::mail_api($_POST, null, $template, 0);
/************************ End to Domain ******************************/
if (!$to_company) {
$msg = [
'status_code' => 500,
'status_message' => 'Email was not sent.'
];
} else {
$msg = [
'status_code' => 200,
'status_message' => 'Check your Email.'
];
}
echo json_encode($msg);
JS
$("form#pdfForm").submit(function (form, e) {
console.log(send);
if(!send)
{
return false;
console.log("Should never touch this " + send);
}
var formData = new FormData(this);
$.ajax({
url: 'https://example.com/php',
type: 'POST',
data: formData,
success: function (e) {
$.LoadingOverlay("hide");
},
cache: false,
contentType: false,
processData: false
});
});
I have a problem with an ajax call to php mail() script failing on success, no json data is returned. It's basically just posting a form to a php script, validating & returning some json.
If I encounter either a validation error the json is returned correctly & my jquery executes as expected.
If NO errors are encountered, PHP processes and sends mail correctly but no data is returned to my jquery script.
Here is my code:
<?php
require "gump.class.php";
$gump = new GUMP();
$mailto = 'me#mydomain.com';
$subject = 'A new form inquiry has been submitted.';
$output = array(
'status' => 'success',
'msg' => 'Mail processed successfully',
'success' => 'success',
);
function render_email($input) {
//error_log("render_email " . print_r($input,TRUE), 0);
ob_start();
include "email-template.phtml";
return ob_get_contents();
}
$input = $gump->sanitize($_POST);
$gump->validation_rules(array(
'first_name' => 'required',
'last_name' => 'required',
'email' => 'required',
//'country' => 'required|valid_email',
//'gender' => 'required|exact_len,1',
//'company' => 'required|valid_cc|max_len,2|min_len,1',
//'bio' => 'required'
));
$gump->filter_rules(array(
'first_name' => 'trim|sanitize_string',
'last_name' => 'trim|sanitize_string',
'email' => 'trim|sanitize_string',
));
$validated = $gump->run($_POST);
if($validated === false){
error_log("GUMP: validation Error: " . print_r($gump->get_readable_errors(true),TRUE));
$output = array(
'status' => 'error',
'msg' => '<strong>Validation Error: </strong>' . $gump->get_readable_errors(true),
'error' => 'error',
);
}else{
error_log("GUMP: Successful Validation, processing mail",0);
// ghead & mail the form
$to = $mailto ;
$subject = $subject;
$body = render_email($input);
$headers = "From: Metz Tea <sales#mydomain.com>" . "\r\n";
$headers .= "Reply-To: sales#mydomain.com\r\n";
$headers .= "Return-Path: info#example.com\r\n";
$headers .= "X-Mailer: PHP\n";
$headers .= "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
if(!mail($to,$subject,$body,$headers)){
$output = array(
'status' => 'error',
'msg' => 'The system failed to send mail.',
'error' => 'error',
);
};
error_log("mail complete",0);
}
header("HTTP/1.1 200 OK");
header('Content-type: application/json');
$output = json_encode($output);
echo $output;
return;
and the jquery:
$('form').submit(function(event){
event.preventDefault();
})
$(document).on("forminvalid.zf.abide", function(event,frm) {
var modal = $('form').closest('.reveal').attr('id');
$(".success").hide();
$(".alert").show();
console.log("Form id "+event.target.id+" is invalid");
formToTop(modal);
}).on("formvalid.zf.abide", function(event,frm) {
console.log("Form id "+event.target.id+" is VALID");
var modal = $('form').closest('.reveal').attr('id');
var data = frm.serializeArray();
$.ajax({
type : 'POST',
url : 'process.php',
data : data,
dataType : 'json',
encode : true
}).done(function(data) {
console.log('completed successfully '+ data);
if (data.status != 'success') {
console.log('AJAX returned error = ' + data.msg);
$('.callout p').html(data.msg);
$('.alert').show();
formToTop(modal);
} else {
console.log( 'AJAX returned success = ' + data.status);
$('.callout p').html(data.msg);
$('#orderform').find("input[type=text], textarea, select").val("");
$('.alert').hide();
$('.success').show();
$('form').slideUp('500');
formToTop(modal);
}
}).fail(function(data) {
//error
});
event.preventDefault();
});
It must be the mail() function somehow, it does send mail on success, but no data is sent back to the ajax script.
what is my error here?
The problem is here:
function render_email($input) {
//error_log("render_email " . print_r($input,TRUE), 0);
ob_start();
include "email-template.phtml";
return ob_get_contents();
}
You've got side-effects both leaving the contents of your rendered template in the buffer, and leaving buffering enabled. You'll want to change this to:
function render_email($input) {
//error_log("render_email " . print_r($input,TRUE), 0);
ob_start();
include "email-template.phtml";
$ret = ob_get_contents();
ob_end_clean();
return $ret;
}