Error while sending a mail with AJAX and PHPMailer - javascript

I've encountered a problem. I wanted to send a mail with PHPMailer but I passed the values from the form via jQuery AJAX. But when the mail is sent I get an email without the info that I've passed via AJAX.
Here is my JS code:
$.ajax({
url: post_url,
type: request,
data: {
ime: ucenikOdabrao.ime,
email: ucenikOdabrao.email,
broj: ucenikOdabrao.broj,
grad: ucenikOdabrao.grad,
pol: ucenikOdabrao.pol,
studij: ucenikOdabrao.studij,
faks: ucenikOdabrao.faks,
univerziteti: ucenikOdabrao.univerziteti,
dokumenti: ucenikOdabrao.dokumenti
},
contentType: false, // The content type used when sending data to the server.
cache: false, // To unable request pages to be cached
processData:false,
dataType: "json"
}).done(function(res){
if(res.type == "error"){
alert(res.text);
}
if(res.type == "done"){
alert(res.text);
}
})
I've printed out the object ucenikOdabrao and it printed out in my console perfectly with all the data being there.
Here is my PHP code:
require "PHPMailer-master/PHPMailerAutoload.php";
header('Content-Type: application/json');
$ime = $_POST["ime"];
$email = $_POST["email"];
$broj = $_POST["broj"];
$grad = $_POST["grad"];
$pol = $_POST["pol"];
$studij = $_POST["studij"];
$faks = $_POST["faks"];
$univerziteti = $_POST["univerziteti"];
$dokumenti = $_FILES["dokumenti"];
$dokumenti_count = count($dokumenti['name']);
$subject = "Aplikacija za faks - ".$ime;
$body = "Prijava za faks - ".$ime."\n";
$body .= "Email: ".$email."\n";
$body .= "Broj: ".$broj."\n";
$body .= "Grad: ".$grad."\n";
$body .= "Pol: ".$pol."\n";
$body .= "Studij: ".$studij."\n";
$body .= "Faks na koji aplicira: ".$faks."\n";
$body .= "Univerziteti na koje aplicira: ".$univerziteti."\n";
for($x = 0; $x < $dokumenti_count; $x++){
if(!empty($dokumenti['name'][$x])){
if($dokumenti['error'][$x]>0){
print json_encode("Došlo je do greške! Molimo pokušajte ponovo!");
exit;
}
$file_name = $dokumenti['name'][$x];
$file_size = $dokumenti['size'][$x];
$file_type = $dokumenti['type'][$x];
// Čitamo fajl bajo moj
$handle = fopen($dokumenti['tmp_name'][$x], "r");
$content = fread($handle, $file_size);
fclose($handle);
$encoded_content = chunk_split(base64_encode($content));
$body .="Content-Type: $file_type; name=".$file_name."\r\n";
$body .="Content-Disposition: attachment; filename=".$file_name."\r\n";
$body .="Content-Transfer-Encoding: base64\r\n";
$body .="X-Attachment-Id: ".rand(1000,99999)."\r\n\r\n";
$body .= $encoded_content;
}
}
$mail = new PHPMailer();
$mail->isSMTP();
$mail->SMTPDebug = 1;
$mail->SMTPAuth = true;
$mail->SMTPSecure = 'ssl';
$mail->Host = "smtp.gmail.com";
$mail->Port = 465;
$mail->isHTML(true);
$mail->Username = "cccc#gmail.com";
$mail->Password = "passs";
$mail->SetFrom("cccc#gmail.com");
$mail->Subject = $subject;
$mail->Body = $body;
$mail->AddAddress("dddd#gmail.com");
if(!$mail->Send()){
print json_encode(array('type'=>'error', 'text' => 'Došlo je do greške. Molimo pokušajte kasnije!'));
exit;
} else{
print json_encode(array('type'=>'done', 'text' => 'Vaša aplikacija je uspješno poslata!'));
exit;
}
I also have a problem that I can't get anything as a response in jQuery AJAX function. I just can't see where the problem is :/

Related

My contact form using ajax is not working

The code is this. It's not responding. JavaScript.
Am trying to do a contact form.
function sendContact() {
var valid;
valid = validateContact();
if(valid) {
jQuery.ajax({
url: "contact.php",
data:'name='+$("#name").val()+'&email='+$("#email").val()+'&subject='+$("#subject").val()+'&content='+$(content).val(),
type: "POST",
success:function(data){
$("#mail-status").html(data);
},
error:function (){}
});
}
}
The php file is
<?php
include_once "config.php";
$name = validate($_POST["name"]);
$email = validate($_POST["email"]);
$message = validate($_POST["message"]);
$subject = validate($_POST["subject"]);
$to = 'myemail#example.com';
$mailHeaders = "From: " . $name . "<" . $email . ">\r\n";
if (mail($to, $subject, $message, $mailHeaders)) {
print "<p class='success'>Contact Mail Sent.</p>";
} else {
print "<p class='Error'>Problem in Sending Mail.</p>";
}
function validate($data)
{
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}

500 Internal Server Error (Contact Form, PHP)

We are running a website on a local server. After entering the required data into contact form and clicking the button Send, we get the "500 Internal Server Error". I'm assuming this relates to PHP mail configuration for local servers.
PHP:
<?php
if(isset($_POST["name"]) && isset($_POST["email"]) && isset($_POST["msg"])){
$name = $_POST["name"];
$email = $_POST["email"];
$subject = $_POST["subject"];
$msg = nl2br($_POST["msg"]);
$to = "info#companyname.com";
$from = $email;
$message = "<b>Name:</b> ".$name." <br><b>E-mail:</b> ".$email." <br><b>Subject:</b> ".$subject." <br><p> ".$msg." </p>";
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=iso-8859-1" . "\r\n";
$headers .= "From: $from" . "\r\n";
if(mail($to, $subject, $message, $headers)){
echo "Success";
}else{
echo "The server failed to send the message. Please try again later.";
}
}
?>
JS:
function _(id){return document.getElementById(id);}
function submitForm(){
_("submit").disabled = true;
_("status").innerHTML = "Please wait...";
var formdata = new FormData();
formdata.append("name", _("name").value);
formdata.append("email", _("email").value);
formdata.append("subject", _("subject").value);
formdata.append("msg", _("msg").value);
var ajax = new XMLHttpRequest();
ajax.open("POST", "contact.php");
ajax.onreadystatechange = function(){
if(ajax.readyState == 4 && ajax.status == 200){
if(ajax.responseText == "Success"){
_("status").innerHTML = "";
_("response").innerHTML = "Your message has been successfully sent.";
}else{
_("status").innerHTML = ajax.responseText;
_("submit").disabled = false;
}
}
}
ajax.send(formdata);
}
I think your problem is caused by SMTP server configuration. There are no syntax errors in the code. If the php would be in wrong folder it would return 404 error not 500.
Try to comment the if/else part of the php file just to make sure the other parts of the file are working.
Solved. The problem was with the configuration of our local server which runs on MS IIS.

Facebook javascript api - webhook

i am having a problem to do a webhook with the facebook api on a lead ads form.
Last day it was working like a charm. On the 'Lead Ads Testing Tool' i received a status = success. Now i received a status = failure, error code = 102, error message = server failure
image of the error 102
Anyone know this issue ?
here my webhook.php :
if (isset($_GET['hub_verify_token'])) {
if ($_GET['hub_verify_token'] === 'your verify token') {
echo $_GET['hub_challenge'];
return;
} else {
echo 'Invalid Verify Token';
return;
}
}
$input = json_decode(file_get_contents('php://input'), true);
$emailfrom = "test#test.com";
$emailto = "my#email.com";
$subject = "You've got a new submission Test";
$headers = "From: " . $emailfrom . "\r";
$headers .= "Reply-To: ". $emailfrom . "\r";
$headers .= "MIME-Version: 1.0\r";
$headers .= "Content-Type: text/html; charset=utf-8\r";
$body = 'hello';
mail($emailto, $subject, $body, $headers);
and the callback_url is good = "success": true image graph api subscription to webhook
Thanks

user enters name before quiz starts using javascript

I have created a quiz but would like to know how to start when making a user input to email.
Basically I would like the user to enter their name before they start my quiz and then once they have finished the quiz the results get sent to me by email using Javascript.
Is this possible?
You can't send email with plain JavaScript as far as I know, you will need to have a service, backend or a php file..
for example this php file:
<?php
header('Content-type: application/json');
$errors = '';
if(empty($errors))
{
$from_name = $_POST['name'];
$from_email = $_POST['email'];
$message = $_POST['message'];
$to_email = 'your#email.com';
$to_email_cc = $from_email;
$contact = "<p><strong>Name:</strong> $from_name</p>
<p><strong>Email:</strong> $from_email</p>";
$content = "<p>$message</p>";
$email_subject = "Neue Nachricht von $from_name erhalten";
$email_subject_cc = "Deine Nachricht wurde gesendet";
$email_body = '<html><body>';
$email_body .= "$contact $content";
$email_body .= '</body></html>';
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
$headers .= "From: $my_email\n";
$headers .= "Reply-To: $from_email";
mail($to_email,$email_subject,$email_body,$headers);
mail($to_email_cc,$email_subject_cc,$email_body,$headers);
$response_array['status'] = 'success';
echo json_encode($response_array);
} else {
$response_array['status'] = 'error';
echo json_encode($response_array);
}
?>
and then you could do a post on that with for example angular, jquery or other..
something like this:
postEmail(newMail: Email): Observable<string>{
let body = `name=${newMail.name}&email=${newMail.email}&message=${newMail.message}`;
let headers = new Headers({ 'Content-Type': 'application/x-www-form-urlencoded' });
let options = new RequestOptions({ headers: headers });
return this._http.post(this._contactUrl, body, options)
//.map(res => <string> res.json())
.catch(this.handleError)
}
this is some old code from angular2 i wrote once and is not tested, but it should give you an idea of how to do it.

getting a 500 error when submitting email but email still goes through

I am lost on why i am getting this internal error(500). My email info still go through when i click submit. The only problem i have is that the ajax success method is not being called so basically my callback function is never getting called on. Any help would be greatly appreciated. I have been pulling my hair out for hours on this problem.
My scipt-ajax call:
emailValidation: function(e){
e.preventDefault();
$('body, html').animate({scrollTop:0},"slow");
var valid = '';
var name = $("#f_name").val();
var email = $("#f_email").val();
var message = $("#f_message").val();
var emailReg = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
if(name === '' || name.length <= 2){
valid += '<p class="error">Name must be longer than 2 char.</p>';
}
if(message === '' || message.length <= 5){
valid += '<p class="error">Message must be longer than 5 char.</p>';
}
if (!(email).match(emailReg)){
valid += '<p class="error">Invalid Email</p>';
}
if (valid !== ''){
$('#form-messages').html(''+valid+'').fadeIn();
}
else {
var formData = $("#contact").serialize();//Value for sanitized form values to be paased to email.php. Value returns an array
portfolio.submitEmail(formData);
}
},
submitEmail: function(formData){
console.log(formData);
//$('#form-messages').html("Proccessing...<img src='img/processing_bar.png' alt='Proccessing' />").fadeIn('fast');
$('body, html').animate({scrollTop:0},"fast");
$.ajax({
type: 'POST',
url: 'mailer.php',
data: formData,
dataType: 'json',
success: function(result){
console.log(result.statusText);
if(result.statusText === 'OK'){
console.log('jam');
// Make sure that the formMessages div has the 'success' class.
$('#form-messages').removeClass('error');
$('#form-messages').addClass('success');
// Set the message text.
$('#form-messages').html('<p class="success">Message has been sent succesfully! Thank you '+ $('#f_name').val() +', a response will be returned in less than one business day.</p>');
$("#contact").fadeOut('slow').remove();
$('body, html').animate({scrollTop:0},"fast");
}
},
error: function(error){
console.log(error.statusText);
if(error.statusText === 'OK'){
// Make sure that the formMessages div has the 'success' class.
$('#form-messages').removeClass('error');
$('#form-messages').addClass('success');
// Set the message text.
$('#form-messages').html('<p class="success">Message has been sent succesfully! Thank you '+ $('#f_name').val() +', a response will be returned in less than one business day.</p>');
$("#contact").fadeOut('slow').remove();
$('body, html').animate({scrollTop:0},"fast");
}
},
});
},
Here is my mail.php file:
<?php
// Only process POST reqeusts.
if ($_SERVER["REQUEST_METHOD"] == "POST") {
// Get the form fields and remove whitespace.
$em_name = strip_tags(trim($_POST["name"]));
$em_name = str_replace(array("\r","\n"),array(" "," "),$em_name);
$em_email = filter_var(trim($_POST["email"]), FILTER_SANITIZE_EMAIL);
$em_message = $_POST["message"];
$em_phone = $_POST['phone'];
$em_website = $_POST['website'];
$em_hear = $_POST['hear'];
$em_startdate = $_POST['startdate'];
$em_budget = $_POST['budget'];
$to = 'theller5567#gmail.com';
$subject = 'Website Change Request';
$headers = "From: " . $em_email . "\r\n";
$headers .= "Reply-To: ". $em_email . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
// Build the email content.
$message = "<h3>Name: ". $em_name. "\n</h3>";
$message .= "<h3>Message: ". $em_message. "\n</h3>";
$message .= "<p>Budget: ". $em_budget. "\n</p>";
$message .= "<p>Start Date: ". $em_startdate. "\n</p>";
$message .= "<p>How did you hear about us?: ". $em_hear. "\n</p>";
$message .= "<p>Email: ". $em_email. "\n</p>";
$message .= "<p>Phone: ". $em_phone. "\n</p>";
$message .= "<p>Website: ". $em_website. "\n</p>";
if (mail($to, $subject, $message, $headers)) {
http_response_code(200);
echo "Thank You! Your message has been sent.";
} else {
http_response_code(500);
echo "Oops! Something went wrong and we couldn't send your message.";
}
} else {
http_response_code(403);
echo "There was a problem with your submission, please try again.";
}
?>

Categories