I'm trying to submit a form as an email through PHP but I'm sending the data through an AJAX function call in jQuery so the page itself doesn't refresh (in short, the user fills out the form and then when they hit submit, it sets the data to a variable and sends that to the PHP page via AJAX call, all without the page reloading) but for some reason, the emails aren't sending, but the code itself seems to function?
Here's the code that I have (just the AJAX call and the php code).
var dataString = 'name=' + name + '&email=' + email + "&subject=" + subject + '&msg=' + msg;
$.ajax ({
type: "POST",
url: "process.php",
data: dataString,
success: function() {
$("#success").show();
$( '#contactUs' ).each(function(){
this.reset();
});
}
});
PHP
<?php
if(isset($_POST['email'])) {
$email_to = "xxx#someplace.net";
$email_subject = "subject";
$name = $_POST['name']; // required
$email_from = $_POST['email']; // required
$message = $_POST['msg']; // required
function clean_string($string) {
$bad = array("content-type","bcc:","to:","cc:","href");
return str_replace($bad,"",$string);
}
$email_message .= "Name: ".clean_string($name)."\n";
$email_message .= "Email: ".clean_string($email_from)."\n";
$email_message .= "Message: ".clean_string($message)."\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, $message, $headers);
?>
try to use this syntax for posting your variables as an object
$.ajax ({
type: "POST",
url: "process.php",
dataType: 'json'
data: {
dataString : name,
email : email,
subject :subject,
msg : msg
},
success: function() {
$("#success").show();
$( '#contactUs' ).each(function(){
this.reset();
});
}
});
Related
I have never coded using PHP before so I have no idea if my code is correct. I am trying to run my PHP file from my JavaScript/jQuery code using ajax. I don't seem to understand what is wrong. No emails are being sent but I'm not being given any errors either. Please help! Also, the email being used in the PHP code is my actual email just didn't want it in the question so I changed to example. Everything is pulling from an HTML form also. I gave each input the name according to what info it collects.
JavaScript
$.ajax({
type: "CONNECT",
url: "mail.php"
}).done(function(data){
alert("Message is sent");
});
PHP
<?php
$email = $_GET['email'];
$company_name = $_GET['companyname'];
$sender_name = $_GET['customername'];
$telephone_num = $_GET['telephonenum'];
$message = $_GET['message'];
$to = "example#gmail.com";
$subject = $company_name . " " . $sender_name;
$finished_message = "Name: " . $sender_name . "\n
Company: " . $company_name . "\n
Telephone Number: " . $telephone_num . "\n
Email: " . $email . "\n
Message:\n" . $message . "";
$finished_message = wordwrap($finished_message,70);
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= "Content-type:text/html;charset=UTF-8" . "\r\n";
$headers .= "From: ". $sender_name . " <" . $email . ">";
mail($to,$subject,$finished_message,$headers);
?>
I've tried changing the type in the js file but then I throw errors.
Here is the solution of your problem of calling a file through ajax
$.ajax({
type: 'POST',
url: '/mail.php',
data: {
// Parameters with values
}
success: function (res) {
alert("Message is sent");
},
error: function (error) {
alert("Message not sent"+error);
}
});
Hope helpful for you!
You seem to be using ajax wrong. You don't send the body with your request. I would suggest something like this:
$.ajax({
method: "POST",
url: "mail.php",
data: {} // your form data
})
.done(function(msg) {
alert("Data sent!");
});
Or using FormData:
$.ajax({
method: "POST",
url: "mail.php",
data: new FormData() // your form data
})
.done(function(msg) {
alert("Data sent!");
});
And PHP part: you are getting your values from GET object. However, you schould send your email-forms using POST method. In ajax I already wrote method: 'post'. Change $_GET to $_POST and everything should work fine.
And I strongly recommend validating your incoming data, at least if it exists or not.
Firstly, thanks because viewing my question here. My problem is i cannot send email through my ajax request. Actually, my ajax request to post email is in another ajax request.
Here is my code for my ajax :
$.ajax({
url: 'creating_bill.php',
data: {
paid_amount : JSON.stringify(jumlah_semua),
email : emel,
name : nama
},
type: "POST",
dataType: "json",
success: function (data) {
id = data.id;
url = data.url;
confirm('Terima Kasih ! Sila membuat pembayaran dengan segera.');
window.open(data.url, '_blank');
setTimeout(checkBillStatus, 1000);
$('li#progress2').removeClass('active').next().addClass("active");
$('.container_waiting').fadeIn();
$('#cara_pembayaran_form').fadeOut();
var name =$('input#nama').val();
var phone =$('input#phone').val();
var negeri =$('input#negeri').val();
var bandar =$('input#bandar').val();
var poskod = $('input#poskod').val();
var alamat =$('input#alamat').val();
var emel = $('input#emel').val();
var jumlah = $('input#jumlah_semua').val();
var bill_url = url;
// Here is my ajax request to send email
$.ajax({
type: "POST",
url: "send_bill_email.php",
data: {
name : name,
phone : phone,
negeri : negeri,
bandar : bandar,
poskod : poskod,
alamat : alamat,
emel : emel,
jumlah : jumlah,
bill_url : bill_url
},
dataType:"json",
success: function(data2){
console.log("Success!");
}
});
},
async: false,
error: function(data) {
handleRequestError(data);
}
})
}
and this is my code in php :
<?php
$name = $_POST['name'];
$phone = $_POST['phone'];
$email = $_POST['emel'];
$address = $_POST['alamat'];
$poskod = $_POST['poskod'];
$negeri = $_POST['negeri'];
$bandar = $_POST['bandar'];
$jumlah_harga = $_POST['jumlah'];
$bill_url = $_POST['bill_url'];
$to = $email;
// Subject
$subject = 'FROM: Ordering System From - ' . $name;
// Message
$message = '
<html>
<head>
<title>' . $subject . '</title>
</head>
<body>
<p>Nama: ' . $name . '</p>
<p>Telefon: ' . $phone . '</p>
<p>Email: ' . $email . '</p>
<p>Alamat: ' . $address . '</p>
<p>Poskod: ' . $poskod . '</p>
<p>Negeri: ' . $negeri . '</p>
<p>Bandar: ' . $bandar . '</p>
<p>Jumlah Harga: ' . $jumlah_harga . '</p>
<p>Bill url: ' . $bill_url . '</p>
</body>
</html>
';
// To send HTML mail, the Content-type header must be set
$headers[] = 'MIME-Version: 1.0';
$headers[] = 'Content-type: text/html; charset=iso-8859-1';
// Additional headers
$headers[] = 'From: ' . $name . ' <' . $email . '>';
// Mail it
mail($to, $subject, $message, implode("\r\n", $headers));
?>
Thank you for your time. I hope there is someone that could help me solve this.
Can you try to wrap your entire to php code to this
if($_SERVER['REQUEST_METHOD']=='POST'){
//YOUR CODE GOES HERE
}
also i strongly suggest to use the development window of your browser to see the process.
The script below helps with processing of a form that request number and name values, and than sends it to process.php and also displays a confirmation and hides the button that would fired the modal to the form so user cannot retry to fill the form.
Script to handle pass data to process.php
$(document).ready(function () {
function successHandler(){
console.log('Success');
$("#thanks").html(msg);
$('#form-content').modal('hide');
}
function errorHandler(){
console.log('Error');
alert("Error");
}
var nameval = $('#name').val();
var numberval = $('#number').val();
$("form#contact").submit(function(){
$.ajax({
type: "POST",
url: "process.php",
data: {
name: nameval,
number: numberval,
submit: true
},
success: function(msg){
$("#thanks").html(msg);
$('#form-content').modal('hide');
return false;
},
error: function(){
alert("Error");
return false;
}
});
return false;
});
});
The whole action does generate an email with HTML from the process.php script but does not include the data that was captured from the form, I believe there is a error within this script as I cannot find anything on the form or process.php that is using PHPMail() doing anything wrong.
Could you help?
Update
<?php
if (isset($_POST['submit'])) {
$name = ($_POST['name']);
$number = ($_POST['number']);
echo "<span class=\"alert alert-success\">THANKS! SUBMITTED</span>";
$to = "EMAIL BLANKED";
$subject = "Alert!";
$message = "name: $name number: $number";
// Always set content-type when sending HTML email
$headers = "MIME-Version: 1.0" . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// More headers
$headers .= 'From: <email blank>' . "\r\n";
mail($to,$subject,$message,$headers);
}
else { echo '<div class="alert alert-error">Error</div>' ; }
?>
You should put this two lines:
var nameval = $('#name').val();
var numberval = $('#number').val();
inside the submit function like this
$("form#contact").submit(function(){
var nameval = $('#name').val();
var numberval = $('#number').val();
because if you set the values of the variables before the submission of the form the inputs will most likely be empty.
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.";
}
?>
I have built a form which is submitted via Ajax and then processed with the mail() function in PHP. The form validation and form submission works perfectly (I can console log the data and receive a success message), yet I'm not receiving any emails from my form. I'm assuming it's the process.php.
This is my first time doing this, so also any pointers/code improvements would be much appreciated.
Javascript:
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
var dataString = 'name=' + name + '&email=' + email + '&message=' + message;
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function () {
alert('success');
}
});
PHP:
<?php
$myemail = "name#example.com";
$subject = "Subject";
$message = "
Name: $name
E-mail: $email
Message: $message
";
mail($myemail, $subject, $message);
?>
I think indeed the problem resides within the php mail() method.
Just make sure it is, by commenting out the mail() call, and replace it with
echo 'I should be sending mail now!';
exit;
Then change your ajax call to:
$.ajax({
type: "POST",
url: "process.php",
data: dataString,
success: function (response) {
alert(response);
}
});
Now send the form to the server, and see what comes up in the alert box.
If you get the expected string, you should indeed setup a smtp server so you can send mail.
Another option would be to use an external mailserver, but it requires you to have a proper email account somewhere else.
There are a bunch of scripts out there, check out phpmailer for instance.
Thanks to dibs and dabs of help, I've managed to work it out.
The Ajax was all good, as expected.
The email wasn't sending because it was running locally, not using my servers mail PHP.
And the data from the form wasn't being referenced, thus returning blank emails.
SO, this is what ended up working:
<?php
$myemail = "name#example.com";
$subject = "Subject";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$body = "
Name: $name
Email: $email
Message: $message
";
mail($myemail, $subject, $body);
?>