I'm creating a plugin for my contact form using ajax and add shortcode wordpress . I don't get how to do it and it work perfect, and read several forums about the admin- ajax.php but do not understand how to pass data to this file.
This is the code :
<?php
/*
Plugin Name: Formulario de contacto
Plugin URI: http://www.e-world.co
Description: Formulario de contacto con ajax
Version: 1.0
Author: Jorge Moreno
Author URI: http://www.e-world.co
license: GLP2
*/
function the_action_function(){
$adminemail = "jorge.moreno#e-world.co";
if ($_GET['send'] == 'comments')
{
$_uname = $_POST['name'];
$_uemail = $_POST['email'];
$_website = $_POST['website'];
$_comments = stripslashes($_POST['comment']);
$email_check = '';
$return_arr = array();
if($_uname=="" || $_uemail=="" || $_comments=="")
{
$return_arr["frm_check"] = 'error';
$return_arr["msg"] = "Please fill in all required fields!";
}
else if(filter_var($_uemail, FILTER_VALIDATE_EMAIL))
{
$to = $adminemail;
$from = $_uemail;
$subject = "Renew Email: " .$_uname;
$message = 'Name: ' . $_uname . '<br><br> Email: ' . $_uemail . '<br><br> website: ' . $_website . '<br><br> Comment: ' . $_comments;
$headers = "MIME-Version: 1.0\r\n";
$headers .= "Content-type: text/html; charset=iso-8859-1\r\n";
$headers .= "Content-Transfer-Encoding: 7bit\r\n";
$headers .= "From: " . $from . "\r\n";
#mail($to, $subject, $message, $headers);
} else {
$return_arr["frm_check"] = 'error';
$return_arr["msg"] = "Please enter a valid email address!";
}
echo json_encode($return_arr);
}
}
function createAjaxContactForm() {
return '
<div class="form">
<form action="process.php" method="post" name="ContactForm" id="ContactForm" >
<div class="form-group">
<input type="text" class="form-control" name="name" placeholder="Full Name *">
</div>
<div class="form-group">
<input type="text" class="form-control" name="email" placeholder="Email *">
</div>
<div class="form-group">
<input type="text" class="form-control" name="website" placeholder="Website">
</div>
<div class="form-group">
<textarea rows="5" class="form-control" name="comment" placeholder="Your Message *" style="height:175px;"></textarea>
</div>
<div id="message_post"></div>
<input class="btn btn-default" type="submit" value="ENVIAR" name="submitf" id="submitf">
</form>
</div>';
}
add_shortcode('AjaxContactForm', 'createAjaxContactForm');
?>
and my ajax:
jQuery(function(){
jQuery("#ContactForm").submit(function(){
jQuery("#submitf").value='Please wait...';
jQuery.post("password/wp-admin/admin-ajax.php", jQuery("#ContactForm").serialize(),
function(data){
if(data.frm_check == 'error'){
jQuery("#message_post").html("<div class='errorMessage'>ERROR: " + data.msg + "!</div>");
document.ContactForm.submitf.value='Resend >>';
document.ContactForm.submitf.disabled=false;
} else {
jQuery("#message_post").html("<div class='successMessage'>Your message has been sent successfully!</div>");
jQuery("#submitf").value='Send >>';
}
}, "json");
return false;
});
});
This is ajaxurl write this code your-theme/functions.php
<?php function frontend_custom_ajaxurl() { ?>
<script type="text/javascript">
var ajaxurl = '<?php echo admin_url('admin-ajax.php'); ?>';
</script>
<?php
}
add_action('wp_head','frontend_custom_ajaxurl');
This is your php function can do anything. And also write this code in your-theme/functions.php file
function your_function() {
parse_str($_POST['data'], $params);
print_r($params)
exit;
}
add_action('wp_ajax_your_function', 'your_function');
add_action('wp_ajax_nopriv_your_function', 'your_function');
This is JQuery.
jQuery("#ContactForm").submit(function(event) {
event.preventDefault();
jQuery("#submitf").value = 'Please wait...';
var data = {
action: 'your_function', // here php function such as your_function
data: jQuery("#ContactForm").serialize(),
};
jQuery.post(ajaxurl, data, function(response) {
......................
});
});
Any confusion comment?
for ajax use this code :
use the below code in .php file and replace $ with jQuery if it not works
$().ready(function() {
var ajaxurl = "<?php echo admin_url('admin-ajax.php'); ?>";
$.post(
ajaxurl, {
'action': 'set_the_city',
//pass all the parameter from the form in key value pairs here
},
function(output) {
console.log(output)
});
});
WordPress provides a hook for ajax call use that instead.
add_action('wp_ajax_set_the_city', 'set_the_city');
add_action('wp_ajax_nopriv_set_the_city', 'set_the_city');
function set_the_city() {
//all the data can be retrieved by $_REQUEST so do the coding for the_action_function() here.
}
Related
I have form on my website, when I click the button I trigger a JS function that take the inputs from my form and send a mail using php. After the mail are sent a modal is showing a thanks for contact. Everything works perfect until I try to validate the form using "HTML5 required". And if I use the submit form the validation works but not my modal. This drives me crazy and it must be some easy solution that I miss. I have search a lot but don't find any solution that's fits my issue.
BR
Mats
MY HTML
<input type="text" name="name" id="name" required placeholder="Ditt namn:"><br>
<input type="email" name="mail" id="mail" required placeholder="Din e-post:"><br>
<input type="tel" name="phone" id="phone" required placeholder="Ditt telefonnummer:"><br>
<textarea name="message" id="message" required placeholder="Ditt meddelande:" rows="10"></textarea>
<table>
<td><input type="checkbox" name="checkbox" id="checkbox" value="checkbox" required ></td><td>
<label for="checkbox"> Jag har läst och godkänner news <a onclick="showModal('intrigitetspolicyModal')">integritetspolicy</a></label>
</td> <br>
</table>
<input id="buttonMail" type='button' onclick=”sendMail()” value='Skicka'/>
</form>
My JS
function sendMail(){
var data = {
name: $("#name").val(),
mail: $("#mail").val(),
phone: $("#phone").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "javaScript/mail.php",
data: data,
success: function(){
}
});
showModal('kontaktModal');
$("#formMail").trigger('reset');
return false;
}
function showModal(Modal){
var modal = document.getElementById(Modal);
modal.style.display = "block";
}
MY PHP
<?php
if($_POST){
$to = "example#example";
$subject = "Medelande från example";
$subject2 = "Kopia på det formulär du skicka på example";
$name = $_POST['name'];
$from = $_POST['mail'];
$phone = $_POST['phone'];
$message = $name . " skrev:" . "\n\n" . $_POST['message'] . "\n\n" . $_POST['name'] . "\n" . $_POST['mail'] . "\n" . $_POST['phone'];
$message2 = "Här är en kopia på ditt meddelande " . $first_name . "\n\n" . $_POST['message'];
$headers = "From:" . $from;
$headers2 = "From:" . $to;
mail($to,$subject,$message,$headers); //send email
mail($from,$subject2,$message2,$headers2); // sends a copy of the message to the sender
}
?>
Basically, you just need to call reportValidity() on your sendMail() function to benefit from the HTML5 validation without actually triggering the form submit.
Something like this should work for you:
function sendMail(){
var isValid = document.querySelector('from').reportValidity();
if (!isValid) {
return false;
}
var data = {
name: $("#name").val(),
mail: $("#mail").val(),
phone: $("#phone").val(),
message: $("#message").val()
};
$.ajax({
type: "POST",
url: "javaScript/mail.php",
data: data,
success: function(){
}
});
showModal('kontaktModal');
$("#formMail").trigger('reset');
return false;
}
See more info/example here: https://googlechrome.github.io/samples/report-validity/
This question already has answers here:
AJAX form not displaying succes or error message
(3 answers)
Closed 5 years ago.
I'm still learning the code languages that I used to create my form with. So I can't seem to figure out what seems to be the problem. Here's my code:
HTML:
<form action="mail.php" method="POST">
<ul class="form-style-1">
<li>
<input type="text" id="mail-name" name="name" class="field-divided" maxlength="15" placeholder="Voornaam *" /> <input type="text" id="mail-lastname" name="lastname" class="field-divided" maxlength="15" placeholder="Achternaam" >
</li>
<li>
<input type="email" id="mail-email" name="email" placeholder="E-mail *" class="field-long" maxlength="40" >
</li>
<li>
<input type ="text" id="mail-phone" name="phone" placeholder="Telefoonnummer" class="field-long" maxlength = "15">
</li>
<li>
<select name="subject" id="mail-subject" class="field-select" >
<option disabled value="" selected hidden >--Onderwerp-- *</option>
<option value="Kennismakingsgesprek">Kennismakingsgesprek</option>
<option value="Meer informatie">Meer informatie</option>
<option value="activiteit">Aanmelding activiteit</option>
<option value="Vraag/klacht">Vraag/klacht</option>
<option value="Contact">Overig</option>
</select>
</li>
<li>
<textarea name="information" id="mail-information" placeholder =" Je bericht *"class="field-long field-textarea" maxlength="2000"></textarea>
</li>
<button class="mail-submit" id="mail-submit" type="submit" name="submit">Send e-mail</button>
<span class="form-message"></span>
</ul>
</form>
JS:
$(document).ready(function() {
$('form').submit(function(event) {
event.preventDefault();
var name = $("#mail-name").val();
var name = $("#mail-lastname").val();
var email = $("#mail-email").val();
var phone = $("#mail-phone").val();
var subject = $("#mail-subject").val();
var information = $("#mail-information").val();
$(".form-message").load("mail.php", {
name: name,
lastname: lastname,
email: email,
phone: phone,
subject: subject,
information: information
});
});
});
**PHP: **
<?php
if (isset($_POST['submit'])) {
$email_to = "#";
$email_subject = "#";
$name = $_POST['name'];
$lastname = $_POST['lastname'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$subject = $_POST['subject'];
$information = $_POST['information'];
$errorEmpty = false;
$errorEmail = false;
if (empty($name) || empty($lastname) || empty($email) || empty($phone) || empty($subject) || empty($information)) {
echo "<span class='form-error'>Voer alle velden in!</span>";
$errorEmpty = true;
}
elseif (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
echo "<span class='form-error'>Geef een geldig E-mail!</span>";
$errorEmail = true;
}
else {
$formcontent=" Naam: $name \n\n Achternaam: $lastname \n\n Email: $email \n\n Telefoon: $phone \n\n Onderwerp: $subject \n\n Informatie: $information";
$mailheader = "From: ".$_POST["email"]."\r\n";
$headers = "From: ". htmlspecialchars($_POST['name']) ." <" . $_POST['email'] . ">\r\n";
$headers .= "Reply-To: " . $_POST['email'] . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=ISO-8859-1\r\n";
mail($email_to, $subject, $formcontent, $mailheader);
echo "<span class='form-success'>E-mail has been sent!</span>";
}
}
else {
echo "Not working!";
}
?>
I know for a fact that this line of code is stopping the form from basically doing anything:
$('form').submit(function (event) {
event.preventDefault();
Without this line of code, the form works. But instead of getting a display message under the form, it just sends you to an echo page with the text in it.
What I'm looking for is that the page doesn't refresh after the form has been sent, so that it can display the form-succes or error message.
Thank you for your time.
You should use ajax here like this for example on submit of your form just
$("#mail-submit").click(function(event){
event.preventDefault();
var name = $("#mail-name").val();
var lastname = $("#mail-lastname").val();
var email = $("#mail-email").val();
var phone = $("#mail-phone").val();
var subject = $("#mail-subject").val();
var information = $("#mail-information").val();
$.post("mail.php",
{
name: name,
lastname: lastname,
email: email,
phone: phone,
subject: subject,
information: information,
submit: "yes" // this is for your php if isset($_POST['submit'])
},
function(data){
$(".form-message").html( data ); // put return in html element
}
);
});
let me know if you need some more details
I've got html form with inputs and js array of objects. Array of objects doesn't correlates with the array. They are separate units.
html:
<form id="form-order">
First name:<br>
<input type="text" name="firstname">
<input type="tel" name="phonenumber" >
<input type="submit" value="Submit">
</form>
JS
$.ajax({
type: "POST",
data: {mydata: JSON.stringify(MyObjects)},
url: "index.php",
success: function(data){
}
});
var array = [{count:1,image:"images/1.jpg",name:"Bouquet 1",price:49},{count:5,image:"images/1.jpg",name:"Bouquet 9",price:77}];
$("#form-order").submit(function() {
var order_data = cart;
$.ajax({
type: "POST",
url: "../order.php",
data: {form: form_data,
order:JSON.stringify(order_data)},
success: function() {
console.log('OK');
});
});
php
$to = "mail#mail.ru";
$message = '
<html>
<head>
</head>
<body>
<p>Name: '.$_POST['first name'].'</p>
<p>Phone: '.$_POST['phone number'].'</p>
$someArray;
foreach ($extradata as $key => $value) {
$someArray .= "<p>".$value["image"] . ", " .
$value["name"] . "</p>";
</body>
</html>';
Could you check, please, weather this code works right or not?
<form id="formoid" action="" method="post">
<input type="text" id="firstname" name="firstname" >
<input type="text" id="lphonenumber" name="lphonenumber" >
<input type="submit" id="submitButton" name="submitButton" value="Submit">
</form>
you could do something like this
<script type='text/javascript'>
/* attach a submit handler to the form */
$("#formoid").submit(function(event) {
var array = [{count:1,image:"images/1.jpg",name:"Bouquet 1",price:49},{count:5,image:"images/1.jpg",name:"Bouquet 9",price:77}];
/* stop form from submitting normally */
event.preventDefault();
/* get the action attribute from the <form action=""> element */
var $form = $( this ),
url = $form.attr( 'action' );
/* Send the data using post with element id firstname, lphonenumber along with your array*/
var posting = $.post( url, { name: $('#firstname').val(), name2: $('#lphonenumber').val(),extradata: array } );
/* Alerts the results */
posting.done(function( data ) {
alert('success');
});
});
</script>
and in php you could do something like,
<?php
if(isset($_POST['name'])){
// To send HTML mail, the Content-type header must be set
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
// Convert JSON string to Array
$extradata = json_decode($_POST['extradata'], true);
// print_r($someArray); // Dump all data of the Array
// Loop through Array if necessary
$someArray;
foreach ($extradata as $key => $value) {
$someArray .= "<p>".$value["image"] . ", " . $value["name"] . "</p>";
}
$to = "mail#mail.ru";
$message = '
<html>
<head>
</head>
<body>
<p>Name: '.$_POST['first name'].'</p>
<p>Phone: '.$_POST['phone number'].'</p>'.$someArray.'
</body>
</html>';
$subject = "Wooo Email!";
mail($to, $subject, $message, "From: system#yourdomain.com\r\n", $headers);
} else {
echo "error";
}?>
or you could use phpmailer or swift mailer for the same
My PHP:
include_once ('db.php');
$capt_err = '';
$error = 0;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$captcha = $_POST['g-recaptcha-response'];
if (!$captcha) {
echo '<script language="javascript">';
echo 'alert("please check the captcha!");';
// echo 'window.location.href="#mymodal";';
echo '</script>';
exit();
}
else {
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LcoHioTAAAAAHvJ0FIRLC-VWVmpBSs_-7igEkXh&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
}
if ($response . success == false) {
echo '<h2>You are spammer ! Get the #$%K out</h2>';
}
else {
$result = mysqli_query($mysqli, "INSERT INTO vibodha_feedback (`id`,`name`,`email`,`phone`,`message`,`date`) VALUES('','$name','$email','$phone','$message',now())");
echo "<script>" . "alert('Your Message has been sucessfully sent.')" . "</script>";
}
}
// header('location:testimonials.php');
My HTML:
<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']); ?>" method="post">
<fieldset>
<label for="name">Name:</label>
<input type="text" id="name" name="name" required>
<label for="mail">Email:</label>
<input type="email" id="email" name="email" required>
<label for="phone">Phone:</label>
<input type="number" id="phone" name="phone" required>
<label for="message">Message:</label>
<textarea id="message" name="message" required></textarea>
<div class="g-recaptcha" data-sitekey="6LewHioTAAAAANGO-VChqdjsoZARTVOxsrgPW6T8"></div>
</fieldset>
<button type="submit">Send!</button>
</form>
My JavaScript:
the script is default for g-recapcha(google),the google intergrate only recaptcha option..not to give required option.
i wrote validation in php code.the captcha is empty alert will come(refer php code)
the above three parts in my code..i give required in div class,,,the div not taken,then how to give required in captcha.
Try something like this
<input type="text" class="inputcontact" id="captcha_contact" placeholder="Cod securitate" name="captcha" onchange="isEmpty('captcha_contact', 'hiba-captcha_contact')">
<div id="error-captcha_contact"><span style="font-size: 8px;"></span></div>
JS file:
jQuery(document).ready(function () {
jQuery('#contact_send').click(function () {
var minden_ok = true;
if (minden_ok == true) {
minden_ok = isEmpty('captcha_contact', 'error-captcha_contact');
}
if (minden_ok == true) {
//your code here
}
});
function isEmpty(ID, errorID) {
var value= jQuery('#' + ID).val();
if (value.length > 0) {
jQuery("#" + errorID).hide("slow");
jQuery("#" + ID).css("border-color", "");
return true;
} else {
jQuery("#" + errorID + " span:first").text("Please fill !");
jQuery("#" + ID).css("border-color", "red");
jQuery("#" + errorID).show("slow");
jQuery("#" + ID).focus();
return false;
}
You can get it by $_POST['g-recaptcha-response'];
like
include_once ('db.php');
$capt_err = '';
$error = 0;
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
$name = $_POST['name'];
$email = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
if($_POST['g-recaptcha-response']=='')
{
echo '<script language="javascript">';
echo 'alert("please check the captcha!");';
// echo 'window.location.href="#mymodal";';
echo '</script>';
exit();
}
else {
$response = file_get_contents("https://www.google.com/recaptcha/api/siteverify?secret=6LcoHioTAAAAAHvJ0FIRLC-VWVmpBSs_-7igEkXh&response=" . $captcha . "&remoteip=" . $_SERVER['REMOTE_ADDR']);
}
if ($response . success == false) {
echo '<h2>You are spammer ! Get the #$%K out</h2>';
}
else {
$result = mysqli_query($mysqli, "INSERT INTO vibodha_feedback (`id`,`name`,`email`,`phone`,`message`,`date`) VALUES('','$name','$email','$phone','$message',now())");
echo "<script>" . "alert('Your Message has been sucessfully sent.')" . "</script>";
}
}
// header('location:testimonials.php');
I am trying to send an email from a form using php ,here is my PHP code(along with the validation ,didn't want to leave anything out :_)
<?php
/*
* Contact Form Class
*/
header('Cache-Control: no-cache, must-revalidate');
header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
header('Content-type: application/json');
$admin_email = 'sgg3590#rit.edu'; // Your Email
$message_min_length = 5; // Min Message Length
class Contact_Form{
function __construct($details, $email_admin, $message_min_length){
$this->name = stripslashes($details['name']);
$this->email = trim($details['email']);
$this->subject = 'Contact from Your Website'; // Subject
$this->message = stripslashes($details['message']);
$this->email_admin = $email_admin;
$this->message_min_length = $message_min_length;
$this->response_status = 1;
$this->response_html = '';
}
private function validateEmail(){
$regex = '/^([\w-]+(?:\.[\w-]+)*)#((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i';
if($this->email == '') {
return false;
} else {
$string = preg_replace($regex, '', $this->email);
}
return empty($string) ? true : false;
}
private function validateFields(){
if(!$this->name)
{
$this->response_html .= '<p>Please enter your name</p>';
$this->response_status = 0;
}
// Check email
if(!$this->email)
{
$this->response_html .= '<p>Please enter an e-mail address</p>';
$this->response_status = 0;
}
// Check valid email
if($this->email && !$this->validateEmail())
{
$this->response_html .= '<p>Please enter a valid e-mail address</p>';
$this->response_status = 0;
}
// Check message length
if(!$this->message || strlen($this->message) < $this->message_min_length)
{
$this->response_html .= '<p>Please enter your message. It should have at least '.$this->message_min_length.' characters</p>';
$this->response_status = 0;
}
}
private function sendEmail(){
$mail = mail($this->email_admin, $this->subject, $this->message,
"From: ".$this->name." <".$this->email.">\r\n"
."Reply-To: ".$this->email."\r\n"
."X-Mailer: PHP/" . phpversion());
if($mail)
{
$this->response_status = 1;
$this->response_html = '<p>Thank You!</p>';
}
else
{
$this->response_status = 0;
$this->response_html = '<p>Sending failed</p>';
}
}
function sendRequest(){
$this->validateFields();
if($this->response_status)
{
$this->sendEmail();
}
$response = array();
$response['status'] = $this->response_status;
$response['html'] = $this->response_html;
echo json_encode($response);
}
}
$contact_form = new Contact_Form($_POST, $admin_email, $message_min_length);
$contact_form->sendRequest();
?>
here is how I am calling it
BRUSHED.contactForm = function(){
$("#contact-submit").on('click',function() {
$contact_form = $('#contact-form');
var fields = $contact_form.serialize();
$.ajax({
type: "POST",
url: "_include/php/contact.php",
data: fields,
dataType: 'json',
success: function(response) {
if(response.status){
$('#contact-form input').val('');
$('#contact-form textarea').val('');
}
$('#response').empty().html(response.html);
}
});
return false;
});
}
And here is my form
<form id="contact-form" class="contact-form" action="#">
<p class="contact-name">
<input id="contact_name" type="text" placeholder="Full Name" value="" name="name" />
</p>
<p class="contact-email">
<input id="contact_email" type="text" placeholder="Email Address" value="" name="email" />
</p>
<p class="contact-message">
<textarea id="contact_message" placeholder="Your Message" name="message" rows="5" cols="40"></textarea>
</p>
<p class="contact-submit">
<a id="contact-submit" class="submit" href="#">Send Your Email</a>
</p>
<div id="response">
</div>
</form>
The validations work proper so its going to the php file, but I can't send the email and the response div is not fill after I push the send button(neither with thank you or sending fail)
I followed this code from a website and I Don't really understand whats wrong here.. :(
First make sure you have set your machine host same as domain name, as sometimes mail-servers will deny mail-headers that doesn't have matching domain, like Sender: test#test.org but From: localhost.
Then, install postfix so it will correct any improper / incorrect stuff in the email and lastly, you're missing email headers there. Here are my example that works for me:
<?php
try {
$to = 'user#test.org';
$subject = 'Mail Test';
$message = <<<TEXT
Mail request received
TEXT;
$message = str_replace("\n.", "\n..", $message);
$headers = 'MIME-Version: 1.0' . "\r\n";
$headers .= 'Content-type: text/html; charset=iso-8859-1' . "\r\n";
$headers .= 'From: Test Org. <webmaster#test.org>' . "\r\n" .
'Reply-To: webmaster#test.org' . "\r\n" .
'X-Mailer: PHP/' . phpversion();
mail($to, $subject, $message, $headers);
printf("Mail sent to " + $to);
} catch (Exception $e) {
printf("Error occured: " + $e);
}
?>
If it still fails, you can try sending a test message from console echo "this is the body" | mail -s "test" "receipent#test.org" and see if it works. If both failed, best to ask server vendor as maybe they have set outgoing mail disabled or something.
Well I was using local host with WAMP and realized wamp server doesn't provide the functionality . THe code is good and working though.
Thanks