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.
Related
I am working on a form located in the notify button here
I am testing the form now and I get every submission in my email, but on the frontend my success message is showing on the screen.
I would like for this form to work exactly like the contact form on the site where the success message pops up in a placeholder.. or at the bottom of the form
the html and js for the form are below. I have a feeling like I messed up on the class and/or id somewhere. I got all of this code online and have been editing it to make it do what I need it to do LOL! now I am stuck
HTML
<form action="php/newsletter-process.php" id="newsletter-form" method="post">
<input type="text" class="form-control form-control-custom" tabindex="-1"
id="text-field-nl" name="text-field-nl">
<!-- Input Name -->
<div class="nl-form-group" id="name-field">
<label for="form-name" class="sr-only">Name</label>
<input type="text" class="form-control form-control-light"
id="form-name" name="form-name" placeholder="Name">
</div>
<!-- /End Input Name -->
<!-- Input Email -->
<div class="nl-form-group" id="email-field">
<label for="form-email" class="sr-only">Email</label>
<input type="email" class="form-control form-control-light"
id="form-email" name="form-email" placeholder="Email">
</div>
<!-- /End Input Email -->
<!--Check Interest-->
<div class="nl-form-group">
<p>Which are you more interested in?</p>
<input type="checkbox" id="workbook" name="interest-type[]" value="Digital Workbook"/> Digital Workbook<br/>
<input type="checkbox" id="vclass" name="interest-type[]" value="Virtual Class Session"/>Virtual Class Session
</div>
<!-- /End Input Group -->
<!-- Submit Button -->
<div class="btn-row">
<div class="form-group">
<button type="submit" class="btn btn-light" role="button">
Send Message
</button>
</div>
</div>
<!-- /End Submit Button -->
<!-- Message Alert -->
<!--div id="message-newsletter" class="message-wrapper text-white message">
<span><i class="icon icon-sm icon-arrows-slim-right-dashed"></i><label
class="message-text" for="email"></label></span>
</div-->
<div id="message-newsletter" class="message-wrapper text-white message">
<i class="icon icon-sm icon-arrows-slim-right-dashed"></i>
<span class="message-text"></span>
</div>
<!-- /End Message Alert -->
</form>
<!-- /End Newsletter Form -->
JS
/*
--------------------------------
Ajax Contact Form
--------------------------------
+ https://github.com/pinceladasdaweb/Ajax-Contact-Form
+ A Simple Ajax Contact Form developed in PHP with HTML5 Form validation.
+ Has a fallback in jQuery for browsers that do not support HTML5 form validation.
+ version 1.0.1
+ Copyright 2014 Pedro Rogerio
+ Licensed under the MIT license
+ https://github.com/pinceladasdaweb/Ajax-Contact-Form
*/
(function ($, window, document, undefined) {
'use strict';
var form = $('#newsletter-form'),
messageContainer = $('#message-newsletter'),
messageText = $('#message-newsletter .message-text');
form.submit(function (e) {
// remove the error class
form.find('.nl-form-group').removeClass('error');
messageContainer.removeClass('error');
var errorAll = '';
// get the form data
var formData = {
'name': $('input[name="form-name"]').val(),
'email': $('input[name="form-email"]').val(),
'textfield': $('input[name="text-field"]').val()
};
// process the form
$.ajax({
type: 'POST',
url: 'php/newsletter-process.php',
data: formData,
dataType: 'json',
encode: true
}).done(function (data) {
// handle errors
if (!data.success) {
if (data.errors.name) {
$('#name-field').addClass('error');
errorAll = data.errors.name;
}
if (data.errors.email) {
$('#email-field').addClass('error');
errorAll = errorAll + ' ' + data.errors.email;
}
messageContainer.addClass('error');
messageText.html(errorAll);
} else {
// display success message
messageText.html(data.confirmation);
$('#newsletter-form .form-control').each(function () {
$(this).fadeIn().val($(this).attr('placeholder'));
});
}
});
messageContainer.slideDown('slow', 'swing');
setTimeout(function () {
messageContainer.slideUp('slow', 'swing');
}, 10000);
}).fail(function (data) {
// for debug
console.log(data)
});
e.preventDefault();
});
}(jQuery, window, document));
PHP
<?php
$subjectPrefix = 'App It Out Notify';
$emailTo = 'taking this out';
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
if($_SERVER['REQUEST_METHOD'] === 'POST') {
$name = stripslashes(trim($_POST['form-name']));
$email = stripslashes(trim($_POST['form-email']));
$spam = $_POST['textfield'];
foreach($_POST['interest-type'] as $inttype) {
$check_boxes .= $inttype." ";
}
if (empty($name)) {
$errors['form-name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['form-email'] = 'Email is invalid.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$subject = "Message from $subjectPrefix";
$body = '
<strong>Name: </strong>'.$name.'<br />
<strong>Email: </strong>'.$email.'<br />
<strong>Email: </strong>'.$check_boxes.'<br />
';
$headers = "MIME-Version: 1.1" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
$headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
$headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
$headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
$headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
if (empty($spam)) {
mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
}
$data['success'] = true;
$data['confirmation'] = 'Congratulations. Your message has been sent successfully';
}
// return all our data to an AJAX call
echo json_encode($data);
}
Change your button type to "button" to not reload the page.
<button type="button" class="btn btn-light" role="button">
Send Message
</button>
Use the Ajax 'success' and 'error' properties to handle the request success/errors
$.ajax({
type: 'POST',
url: '...',
data: {...},
datatype: 'JSON',
success: function(data){...},
error: function(){...},
});
Use the success/error function to push your success message into the HTML
<div id="message-newsletter" class="message-wrapper text-white message">
<i class="icon icon-sm icon-arrows-slim-right-dashed"></i>
<span class="message-text" id="messageText"></span>
</div>
JS
document.getElementById('messageText').innerHTML = <success or error message>
Your code is a little bit messed up, what you can do is:
Step one
Serialize your form data, change your formData variable to:
var formData = $("form#newsletter-form").serialize();
also change the sent data and the url in your ajax:
$.ajax({
type: 'POST',
url: 'index.php' /*Now, we are requesting the index page instead of the php page.*/,
data: {'submission': formData},
datatype: 'JSON',
success: function(data){...},
error: function(){...},
});
Step two
Instead of writing a messed up php code you can create a functions like this:
<?php
class classname{
public function funcName($formdata,$errors,$data){
$get = explode('&', $formdata); // explode with and
foreach ( $get as $key => $value) {
$valn[ substr( $value, 0 , strpos( $value, '=' ) ) ] = substr( $value, strpos( $value, '=' ) + 1 ) ;
}
// access your query param
$name = stripslashes(trim($valn['name']));
$email = stripslashes(trim($valn['email']));
$spam = $valn['spam'];
foreach($_POST['interest-type'] as $inttype) {
$check_boxes .= $inttype." ";
}
if (empty($name)) {
$errors['form-name'] = 'Name is required.';
}
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$errors['form-email'] = 'Email is invalid.';
}
// if there are any errors in our errors array, return a success boolean or false
if (!empty($errors)) {
$data['success'] = false;
$data['errors'] = $errors;
} else {
$subject = "Message from $subjectPrefix";
$body = '
<strong>Name: </strong>'.$name.'<br />
<strong>Email: </strong>'.$email.'<br />
<strong>Email: </strong>'.$check_boxes.'<br />
';
$headers = "MIME-Version: 1.1" . PHP_EOL;
$headers .= "Content-type: text/html; charset=utf-8" . PHP_EOL;
$headers .= "Content-Transfer-Encoding: 8bit" . PHP_EOL;
$headers .= "Date: " . date('r', $_SERVER['REQUEST_TIME']) . PHP_EOL;
$headers .= "Message-ID: <" . $_SERVER['REQUEST_TIME'] . md5($_SERVER['REQUEST_TIME']) . '#' . $_SERVER['SERVER_NAME'] . '>' . PHP_EOL;
$headers .= "From: " . "=?UTF-8?B?".base64_encode($name)."?=" . " <$email> " . PHP_EOL;
$headers .= "Return-Path: $emailTo" . PHP_EOL;
$headers .= "Reply-To: $email" . PHP_EOL;
$headers .= "X-Mailer: PHP/". phpversion() . PHP_EOL;
$headers .= "X-Originating-IP: " . $_SERVER['SERVER_ADDR'] . PHP_EOL;
if (empty($spam)) {
mail($emailTo, "=?utf-8?B?" . base64_encode($subject) . "?=", $body, $headers);
}
$data['success'] = true;
$data['confirmation'] = 'Congratulations. Your message has been sent successfully';
}
// return all our data to an AJAX call
echo json_encode($data);
}
}
?>
Now, we need to request the function from the index.php. so, add this php code to your index page
<?php
if (isset($_POST['submission'])) {
header('Content-Type: application/json; charset=utf-8');
$subjectPrefix = 'App It Out Notify';//I don't know if you need this in your php file if so you can add it.
$emailTo = 'taking this out';//I don't know if you need this in your php file if so you can add it.
$errors = array(); // array to hold validation errors
$data = array(); // array to pass back data
require_once('yourphppage.php');
$conform = new classname;
$search->funcName($_POST['data'],$errors,$data);
die();
}
?>
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.";
}
?>
The problem:
Javascript function( which was premade by template) cleans the form data sent to me by php
The php code:
<?php
header('Content-type: application/json');
$status = array(
'type'=>'success',
'message'=>'GJ '
);
$name = #trim(stripslashes($_POST['name']));
$phone = #trim(stripslashes($_POST['phone']));
$subject = #trim(stripslashes($_POST['subject']));
$message = #trim(stripslashes($_POST['message']));
$email_to = 'email#email.com';//replace with your email
$body = 'Name: ' . $name . "\n\n" . 'Телефон: ' . $phone . "\n\n" . 'Subject: ' . $subject . "\n\n" . 'Message: ' . $message;
$success = #mail($email_to, $subject, $body);
echo json_encode($status);
die;
The javascript function code:
var form = $('.contact-form');
form.submit(function () {'use strict',
$this = $(this);
$.post($(this).attr('action'), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
When there's no js code php returns white screen with a line but the #mail sends normal message, but when there is this code fade in and out works good, but the data arrives empty. The message in message and name is cyrylic if that is important.
Please help me fix it(i.e. i need both data arriving and success fade-in appearing or at least data arriving with no .php white screen) or just explain what the js code does i don't get it.
Thanks
You haven't provided the data argument for $.post
Try
var form = $('.contact-form');
form.submit(function () {'use strict',
var $this = $(this);
$.post($(this).attr('action'), $this.serialize(), function(data) {
$this.prev().text(data.message).fadeIn().delay(3000).fadeOut();
},'json');
return false;
});
References:
jQuery.post() Docs
jQuery.serialize() Docs
Some help needed here, I'm building a one page wordpress theme and I don't really know how to make the contact form submit without loading. Basically all my code is on index.php.
This is the form submission php code above the get_header(); It works just fine but I can't really make it submit without loading the page.
if(isset($_POST['user_submit'])) {
$parse_uri = explode( 'wp-content', $_SERVER['SCRIPT_FILENAME'] );
require_once( $parse_uri[0] . 'wp-load.php' );
$name = esc_html($_POST['user_name']);
$email = esc_html($_POST['user_email']);
$comment = esc_html($_POST['user_message']);
$website = esc_html($_POST['user_url']);
$msg = esc_attr('Name: ', 'silver') . $name . PHP_EOL;
$msg .= esc_attr('E-mail: ', 'silver') . $email . PHP_EOL;
$msg .= esc_attr('Website: ', 'silver') . $website . PHP_EOL;
$msg .= esc_attr('Message: ', 'silver') . $comment;
$to = get_option( 'admin_email' );
$sitename = get_bloginfo('name');
$subject = '[' . $sitename . ']' . ' New Message';
$headers = 'From: ' . $name . ' <' . $email . '>' . PHP_EOL;
wp_mail($to, $subject, $msg, $headers);
}
This is the jQuery post I'm using for that:
$( "#contact_form" ).submit(function( event ) {
event.preventDefault();
var $form = $( this ),
name = $form.find( "input[name='user_name']" ).val(),
email = $form.find( "input[name='user_email']" ).val(),
website = $form.find( "input[name='user_url']" ).val(),
comment = $form.find( "input[name='user_message']").val();
$.post( templateDir + "/index.php", { website : website, comment : comment, name : name, email : email, submit : "yes" } );
});
This is the site http://silviuandrei.eu/themes/bornagain/
You're checking for the user_submit POST variable:
if(isset($_POST['user_submit']))
But sending a different variable via $.post
$.post( templateDir + "/index.php", { website : website, ..... submit : "yes" } );
Change it to user_submit : "yes"
I recommend doing it at functions.php using the init action:
add_action('init','form_submits');
function form_submits() {
if( isset($_REQUEST['user_submit']) ){
require("process_post.php");
exit;//prevents the default blog output
}
}
Note that using require is just a suggestion to keep functions.php clean.
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();
});
}
});