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);
Related
I am working on a WordPress site and I am trying to convert my jQuery code to vanilla JavaScript (mostly as a learning experience, but also so I don't have to rely on jQuery). The goal is once the form is submitted, instead of going to a thank you page or something else, simply display an overlay over the form saying "Thank you for your message". Again, everything works fine with jQuery/AJAX, but I want to try and get it working with plain JavaScript as well.
Here is the working jQuery code:
jQuery('#myContactForm').on('submit', function () {
var formData = jQuery(this).serializeArray();
formData.push({
name: 'security',
value: ajaxNonce
});
jQuery.ajax({
type: 'POST',
url: ajaxUrl,
data: formData
});
jQuery('.form-overlay').addClass('visible');
return false;
});
And here is the working code from functions.php:
<?php
function javascript_variables() { ?>
<script type="text/javascript">
var ajaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>';
var ajaxNonce = '<?php echo wp_create_nonce('secure_nonce_name'); ?>';
</script>
<?php
}
add_action('wp_head', 'javascript_variables');
add_action('wp_ajax_send_form', 'send_form');
add_action('wp_ajax_nopriv_send_form', 'send_form');
function send_form() {
check_ajax_referer('secure_nonce_name', 'security');
$to = 'myemailaddressgoeshere#gmail.com';
$subject = $_POST['subject'];
$body = 'From: ' . $_POST['full_name'] . '<br />';
$body .= 'Email: ' . $_POST['email'] . '<br />';
$body .= 'Phone: ' . $_POST['phone'] . '<br />';
$body .= 'Message: ' . $_POST['message'] . '<br />';
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($to, $subject, $body, $headers);
wp_die();
}
And finally, here is the relevant input inside the form:
<input class="form-inputs" type="hidden" name="action" value="send_form" />
Here is what I came up with when trying to use the Fetch API instead of jQuery:
// handle form submission
const formSubmissionHandler = () => {
const form = document.getElementById('myContactForm');
const formOverlay = document.querySelector('.form-overlay');
const formInputs = Array.from(document.querySelectorAll('.form-inputs'));
const formData = [];
form.addEventListener('submit', (e) => {
e.preventDefault();
formInputs.forEach((input) => {
if (!input.name || !input.value) {
return;
}
formData.push({
name: input.name,
value: input.value,
});
});
formData.push({
name: 'security',
value: ajaxNonce,
});
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
};
// send post request
fetch(ajaxUrl, fetchOptions)
.then((res) => res.json())
.then((res) => console.log(res))
.catch((err) => console.error(err));
formOverlay.classList.add('visible');
});
};
document.addEventListener('DOMContentLoaded', formSubmissionHandler);
I've come across the FormData() constructor from searching, not sure where/if I would use that here?
And here is what I wrote in my functions.php file:
function send_form() {
check_ajax_referer('secure_nonce_name', 'security');
$to = 'myemailaddressgoeshere#gmail.com';
$subject = $_POST['subject'];
$json_input = json_decode(file_get_contents('php://input'), true);
$body = '';
foreach ($json_input as $key => $value) {
$body = 'From: ' . $value['full_name'] . '<br />';
$body .= 'Email: ' . $value['email'] . '<br />';
$body .= 'Phone: ' . $value['phone'] . '<br />';
$body .= 'Message: ' . $value['message'] . '<br />';
}
$headers = array('Content-Type: text/html; charset=UTF-8');
wp_mail($to, $subject, $body, $headers);
wp_die();
}
I am new to all this so if someone could help me out it would be much appreciated. I think my issue is how I am parsing the JSON data in functions.php. Or could I simply not format the data the same in vanilla JS as it's done in jQuery? Thank you!
I know it is probably a bit late for me to post this but incase somebody in future runs into this, here is the deal:
const fetchOptions = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(formData),
};
here, you are making a json string to pass to the destination URL but you have to remember, Wordpress's ajax parser can't understand data being sent to it as raw json.
$json_input = json_decode(file_get_contents('php://input'), true);
here, you're turning the raw input that you received into an array, but before this, all Wordpress got was a piece of data which is a simple string. So, it doesn't know how to deal with it and what user-defined hook and actions should be fired to validate this.
add_action('wp_ajax_send_form', 'send_form');
add_action('wp_ajax_nopriv_send_form', 'send_form');
here, you are telling wordpress to expect some request with the 'action' name of 'send_form' and if you got it, pass it to a function named 'send_form'. Wordpress however is not recieving that request with the name 'action'. Hence the error.
The fix, however, is quite simple, just add this request name as a GET to the url you're sending the raw data to and clear it up for wordpress:
var ajaxUrl = '<?php echo admin_url('admin-ajax.php'); ?>?action=send_for';
or, the version I prefer:
// send post request
fetch(ajaxUrl + '?action=send_form', fetchOptions)
.then((res) => res.json())
.then((res) => console.log(res))
.catch((err) => console.error(err));
and done!
I think once you star to work with fetch() and WP, at least for now (untill Wordpress figures out a way), this could come handy.
I've created contact form that send form data to an email
then I'm sending ajax to the server which returns json response with success message or alert message
but I'm getting the data commented as below :
<!-- TESS -->
// {"type":"success","message":"Contact form successfully submitted. Thank you, I will get back to you soon!"}
this is the php code :
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);
}
// if requested by AJAX request return JSON response
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 just display the message
else {
echo $responseArray['message'];
}
and the js code :
// when the form is submitted
$('#contact-form').on('submit', function (e) {
// if the validator does not prevent form submit
if (!e.isDefaultPrevented()) {
var url = "../../forms/contact.php";
// POST values in the background the the script URL
$.ajax({
type: "POST",
url: url,
data: $(this).serialize(),
success: function (data)
{
// data = JSON object that contact.php returns
// we recieve the type of the message: success x danger and apply it to the
var messageAlert = 'alert-' + data;
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>';
console.log(alertBox,messageText);
console.log("data ",data,data.type,data.message);
// If we have messageAlert and messageText
if (messageAlert && messageText) {
// console.log("messages ok")
// inject the alert to .messages div in our form
$('.messages').append(alertBox);
// empty the form
$('#contact-form')[0].reset();
}
}
});
return false;
}
})
this code is taken from this tutorial
HOW TO BUILD A WORKING BOOTSTRAP CONTACT FORM
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 have created an application in AngularJS and it has an email contact form and it sends emails using PHP file in server.
Here's my Controller.js part in AngularJS:
$scope.feedbacksubmit= function (){
var name1 = document.getElementById("name").value;
var email1 = document.getElementById("email").value;
var message1 = document.getElementById("message").value;
$http({
url: "http://boost.meximas.com/mobile/email.php",
method: "POST",
data: { name: name1, email: email1, message:message1 }
}).success(function(data, status, headers, config) {
// this callback will be called asynchronously
// when the response is available
if(status == 200) {
var return_data = data;
if(return_data != 0){
$scope.hide();
//$scope.closeFeedback();
}else{
$scope.showEmailError();
}
}
}).
error(function(data, status, headers, config) {
// called asynchronously if an error occurs
// or server returns response with an error status.
console.log(status);
$scope.showAlertNetwork();
$scope.hide();
});
};
Here's my PHP Code:
<?php
$array = json_decode(file_get_contents('php://input'), true);
$name = $array['name'];
$email = $array['email'];
$message = $array['message'];
if (($name=="")||($email=="")||($message==""))
{
printf("0");
}
else{
$from="From: $name<$email>\r\nReturn-path: $email";
$subject="Message sent using your contact form";
mail("mygmail#gmail.com", $subject, $message, $from);
}
?>
The problem arises when I fill in the contact form and hit the Send button. I'm getting $scope.showEmailError();. But I get the email without problem.
And if I try to hit the button without filling the form still getting same $scope.showEmailError(); message.
Why don't you use model values from input? It looks like you try to use AngularJS but you still think with other frameworks in mind
In the following example I'm sending model to php script, if NAME is not filled then PHP returns 404 error and it's handled in AngularJS $http via .error handler. You don't have to add so much extra logic to success to deal with it
http://plnkr.co/edit/sw9RRXb3kdEWXszJdwX3?p=preview
html
<input type="text" ng-model="formData.name" placeholder="name">
<input type="text" ng-model="formData.email" placeholder="email">
<input type="text" ng-model="formData.message" placeholder="message">
javascript
$scope.formData = {
'name': '',
'email': '',
'message': ''
};
$scope.postData = function () {
$http.post('http://edeen.pl/form.php', $scope.formData)
.success(
function(data){
$scope.response = data.replace(/\ /g, ' ').replace(/\n/g, '<br/>') //format response
})
.error(
function(data){
$scope.response = data
})
}
php
$input = json_decode(file_get_contents('php://input'));
if($input->name === ''){
header("HTTP/1.0 404 Not Found");
echo "Something went terribly wrong, missing name maybe?";
return;
}
header('Content-Type: application/json');
var_dump($input);
<?php
$data = json_decode(file_get_contents("php://input"),true);
$name = $data->name;
$email = $data->email;
$sujet = $data->sujet;
$contenu = $data->contenu;
if($name && $email && $sujet && $contenu){
$destinataire = 'bercybilingualschool#gmail.com';
// Pour les champs $expediteur / $copie / $destinataire, séparer par une virgule s'il y a plusieurs adresses
$expediteur = $email;
$copie = 'sss17#gmail.com';
$copie_cachee = 'xxx#xxx.xxx';
$objet = $sujet; // Objet du message
$headers = 'MIME-Version: 1.0' . "\n"; // Version MIME
$headers .= 'Content-type: text/html; charset=ISO-8859-1'."\n"; // l'en-tete Content-type pour le format HTML
$headers .= 'Reply-To: '.$expediteur."\n"; // Mail de reponse
$headers .= 'From: '.$name.'<'.$name.'>'."\n"; // Expediteur
$headers .= 'Delivered-to: '.$destinataire."\n"; // Destinataire
$headers .= 'Cc: '.$copie."\n"; // Copie Cc
$headers .= 'Bcc: '.$copie_cachee."\n\n"; // Copie cachée Bcc
$message = '<div style="width: 100%; text-align: justify; font-weight: bold">hello</div>';
mail($destinataire, $objet, $message, $headers);
}else{
}
?>
I'm using the Jquery Ajax to post a form data and display the success message. Everything works fine, but I'm not able to display the success message. Below is the code :
Javascript
<script>
$(document).ready(function() {
$('form').submit(function(event) { //Trigger on form submit
$('#stage').empty();
var postForm = { //Fetch form data
"name": $("#name").val(),
"element_4_1": $("#element_4_1").val(),
"element_4_2": $("#element_4_2").val(),
"element_4_3": $("#element_4_3").val(),
"email": $("#email").val(),
"input4": $("#input4").val(),
};
$.ajax({ //Process the form using $.ajax()
type : 'POST', //Method type
url : 'contact.php', //Your form processing file url
data : postForm, //Forms name
dataType : 'json',
success : function(data) {
console.log("inside success3") ;
alert(data);
$("#stage").html(data);
if (!data.success) { //If fails
if (data.errors) { //Returned if any error from process.php
$('.throw_error').fadeIn(1000).html(data.errors); //Throw relevant error
console.log("inside failure") ;
}
} else {
console.log("inside success") ;
$('#stage').fadeIn(1000).append('<p>' + data.posted + '</p>');
console.log("inside success2") ;
}
}
});
event.preventDefault(); //Prevent the default submit
});
});
</script>
PHP :
<?php
ini_set('display_errors','On');
error_reporting(E_ALL);
$errors = array();
$form_data = array();
header('Content-type: application/json');
echo json_encode($form_data);
$name=$_POST['name'];
$phone=chop($_POST['element_4_1']);
$phone.=chop($_POST['element_4_2']);
$phone.=chop($_POST['element_4_3']);
$email=chop($_POST['email']);
$message1=chop($_POST['input4']);
if ($name && $phone && $email) {
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/plain; charset=iso-8859-1\r\n";
$headers .= "From: sales#test.com \n";
$recipient= "test#test.in";
$subject="Online Enquiry ";
$message="\nName : $name\n";
$message.="\nPhone : $phone\n";
$message.="\nEmail ID : $email\n";
$message.="\nMessage : $message1\n";
//send auto-reply
$subject_reply="Thank you for contacting us";
$message_reply="Thank you for contacting us. We will get back to you shortly.";
//mail($email, $subject_reply, $message_reply, $headers);
//Send Mail
//===========
if(isset($recipient, $subject, $message, $headers)) {
error_log($message);
$form_data['status'] = 'success';
error_log($form_data['status']);
} else {
$form_data['status'] = 'error';
error_log($form_data['status']);
} ?>
HTML
<div id="stage">
</div>
How can I print the success message
You have this at the start of your php script:
echo json_encode($form_data);
where $form_data is an empty array at that time.
You should remove that and put it at the end.