Checking Google ReCaptcha for success on backend - php

I have a contact form that is performing validation on the back end, what I want to check for is if the user has successfully completed the captcha or not and if not print an error message.
Currently, I am getting an error message:
Notice: Undefined index: g-recaptcha-response in /var/www/html/mangoForm.php on line 99
So it isn't printing the error message that is in the JSON:
{"success":false,"errors":{"captcha":"ReCaptcha is required."}}
Line 99:
$captcha = checkCaptcha($formData['g-recaptcha-response']);
Code Block in Question:
if (!empty($validationMSG)) {
return $validationMSG;
}
else {
$captcha = checkCaptcha($formData['g-recaptcha-response']);
if(!$captcha['isSuccess']){
$validationMSG['captcha'] = 'ReCaptcha is required.';
return $validationMSG;
}
//End of Validation Function
}
}
Full Code:
<?php
//show errors - enable this
//ini_set('display_errors', 1);
//ini_set('display_startup_errors', 1);
//error_reporting(E_ALL);
//Var Dump (Debugging)
//var_dump($_POST);
//Load Required Components
require_once 'src/recaptcha_autoload.php';
require_once "functions.php";
use PHPMailer\PHPMailer\PHPMailer;
use PHPMailer\PHPMailer\Exception;
require 'src/Exception.php';
require 'src/PHPMailer.php';
require 'src/SMTP.php';
function validate($formData)
{
// Initiate Array
$validationMSG = array(); // array to hold validation errors
$pname_exp = '/^[a-zA-Z0-9\_]{2,20}/';
if (!isset($formData['firstName'])) {
$validationMSG['firstName'] = 'First Name is required.';
}elseif (!preg_match($pname_exp, $formData['firstName'])){
$validationMSG['firstName'] = 'First Name is not valid.';
}
// Validate lastName
if (!isset($formData['lastName'])) {
$validationMSG['lastName'] = 'Last Name is required.';
}
// Check RegEx for Last Name
elseif (!preg_match($pname_exp, $formData['lastName'])) {
$validationMSG['lastName'] = 'Last Name is not valid.';
}
// Validate companyName
if (!isset($formData['companyName'])) {
$validationMSG['companyName'] = 'Company Name is required.';
}
// Validate companyAddress
if (!isset($formData['companyAddress'])) {
$validationMSG['companyAddress'] = 'Company Address is required.';
}
// Validate state
if (!isset($formData['state'])) {
$validationMSG['state'] = 'State is required.';
}
// Validate city
if (!isset($formData['city'])) {
$validationMSG['city'] = 'City is required.';
}
// Validate Zipcode - If Field is Empty
if (!isset($formData['zipcode'])) {
$validationMSG['zipcode'] = 'Zipcode is required.';
}
// Validate emailAddress
if (!isset($formData['emailAddress'])) {
$validationMSG['emailAddress'] = 'Email Address is required.';
}
// Check if emailAddress is a valid email address
elseif (!filter_var($formData['emailAddress'], FILTER_VALIDATE_EMAIL)) {
$validationMSG['emailAddress'] = 'Email address is not valid.';
}
//Validate phoneNumber
if (!isset($formData['phoneNumber'])) {
$validationMSG['phoneNumber'] = 'Phone Number is required.';
}
//Validate phoneNumber
elseif (preg_match("/^[0-9]{3}-[0-9]{4}-[0-9]{4}$/", $formData['phoneNumber'])) {
$validationMSG['phoneNumber'] = 'Must be a valid phone number.';
}
var_dump($formData);
// Validate message
if (!isset($formData['message'])) {
$validationMSG['message'] = 'Message is required.';
}
if (!empty($validationMSG)) {
return $validationMSG;
}
else {
$captcha = checkCaptcha($formData['g-recaptcha-response']);
if(!$captcha['isSuccess']){
$validationMSG['captcha'] = 'ReCaptcha is required.';
return $validationMSG;
}
//End of Validation Function
}
}
function checkCaptcha($g_recaptcha_response)
{
$recaptcha_secret_key = 'REDACTED';
$recaptcha = new \ReCaptcha\ReCaptcha($recaptcha_secret_key);
$resp = $recaptcha->verify($g_recaptcha_response, $_SERVER['REMOTE_ADDR']);
return [
'isSuccess' => $resp->isSuccess(),
'errorCodes' => $resp->getErrorCodes(),
];
}
function sendMail($formData)
{
$mail = new PHPMailer(true); // Passing `true` enables exceptions
// Server settings
//$mail->SMTPDebug = 2; // Enable verbose debug output
$mail->isSMTP(); // Set mailer to use SMTP
$mail->Host = 'smtp.server.com'; // Specify main and backup SMTP servers
$mail->SMTPAuth = true; // Enable SMTP authentication
$mail->Username = 'user#server.com'; // SMTP username
$mail->Password = 'REDACTED'; // SMTP password
$mail->SMTPSecure = 'ssl'; // Enable TLS encryption, `ssl` also accepted
$mail->Port = 465; // TCP port to connect to
// Recipients
$mail->setFrom('user#server.com', 'Mailer');
$mail->addAddress('user#server.com', 'Joe User'); // Add a recipient
// Content
$mail->isHTML(true); // Set email format to HTML
$mail->Subject = 'New Message from Contact Form';
// prepare email body
$body_message = "";
$body_message.= "Sender IP: " . get_client_ip() . "<br />";
// #todo: make the other rows the same way, i.e. $formData['key'];
$body_message.= "First Name: " . $formData['firstName'] . "<br />";
$body_message.= "Last Name: " . $formData['lastName'] . "<br />";
$body_message.= "Company Name: " . $formData['companyName'] . "<br />";
$body_message.= "Company Address: " . $formData['companyAddress'] . "<br />";
$body_message.= "City: " . $formData['city'] . "<br />";
$body_message.= "State: " . $formData['state'] . "<br />";
$body_message.= "Sender email: " . $formData['emailAddress'] . "<br />";
$body_message.= "Sender Phone: " . $formData['phoneNumber'] . "<br />";
$body_message.= "\n\n" . $formData['message'];
$mail->Body = $body_message;
$mail->send();
}
/////////////////////////////////////////////////
// process
//this will be our whole response (jsoned later)
$response = [
//we'll change these later, possibly:
'success' => false,
'errors' => [],
// 'message' => 'There has been an issue sending your message!!!!',//could be an "OK" error message as well, depends on the 'success' key.
];
// Copy $_POST to $formData
//$formData = $_POST;
//$formData = json_decode($_POST, true);
$formData = json_decode(file_get_contents("php://input"), true);
//validate
$errors = validate($formData);
if(!empty($errors)){
$response['success'] = false;
$response['errors'] = $errors;
}else {//it's ok
//send it
try{
sendMail($formData);
//Print Success Message
$response['success'] = true;
$response['message'] = 'Message was Sent!';
}
catch(Exception $e) {
// Print phpMailer Error Message
$response['success'] = false;
$response['message'] = 'There has been an issue sending your message';
}
}
echo json_encode($response);
exit;
How I can achieve where the PHP script checks for a successful response from Google ReCaptcha and either permits the script to go on further in the event of a success or print an error message?
EDITED JS:
document.querySelector("#form").addEventListener("submit", function(e){
//create variable for contact form url
var formURL = 'mangoForm.php';
//prevent default submission
event.preventDefault();
//define form fields
var mangoForm = {
'firstName' : document.querySelector('input[name=firstName]').value,
'lastName' : document.querySelector('input[name=lastName]').value,
'companyName' : document.querySelector('input[name=companyName]').value,
'companyAddress' : document.querySelector('input[name=companyAddress]').value,
'city' : document.querySelector('input[name=city]').value,
'state' : document.querySelector('select[name=state]').value,
'zipcode' : document.querySelector('input[name=zipcode]').value,
'emailAddress' : document.querySelector('input[name=emailAddress]').value,
'phoneNumber' : document.querySelector('input[name=phoneNumber]').value,
'message' : document.querySelector('input[name=message]').value,
}
//define request variable
var formRequest = new Request(formURL, {
method: 'POST',
body: JSON.stringify(mangoForm),
headers: {
"content-type":"application/json; charset=utf-8"
}
});
//fetch
fetch(formRequest)
//console.log(formRequest)
.then(function(formResponse) {
return formResponse.json();
})
.then(function(data) {
//handle server responses
if ( ! data.success) {
//handle error messages
//handle error message for firstName
//console.log(data);
if (data.errors.firstName && !document.querySelector('#firstName-group .help-block')) {
document.getElementById("firstName-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.firstName;
document.getElementById("firstName-group").append(helpBlock);
}
//handle errors for lastName
if (data.errors.lastName && !document.querySelector('#lastName-group .help-block')) {
document.getElementById("lastName-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.lastName;
document.getElementById("lastName-group").appendChild(helpBlock);
}
//handle errors for companyName
if (data.errors.companyName && !document.querySelector('#companyName-group .help-block')) {
document.getElementById("companyName-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.companyName;
document.getElementById("companyName-group").appendChild(helpBlock);
}
//handle errors for companyAddress
if (data.errors.companyAddress && !document.querySelector('#companyAddress-group .help-block')) {
document.getElementById("companyAddress-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.companyAddress;
document.getElementById("companyAddress-group").appendChild(helpBlock);
}
//handle errors for city
if (data.errors.city && !document.querySelector('#city-group .help-block')) {
document.getElementById("city-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.city;
document.getElementById("city-group").appendChild(helpBlock);
}
//handle errors for state
if (data.errors.state && !document.querySelector('#state-group .help-block')) {
document.getElementById("state-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.state;
document.getElementById("state-group").appendChild(helpBlock);
}
//handle errors for zipcode
if (data.errors.zipcode && !document.querySelector('#zipcode-group .help-block')) {
document.getElementById("zipcode-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.zipcode;
document.getElementById("zipcode-group").appendChild(helpBlock);
}
//handle errors for emailAddress
if (data.errors.emailAddress && !document.querySelector('#emailAddress-group .help-block')) {
document.getElementById("emailAddress-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.emailAddress;
document.getElementById("emailAddress-group").appendChild(helpBlock);
}
//handle errors for phoneNumber
if (data.errors.phoneNumber && !document.querySelector('#phoneNumber-group .help-block')) {
document.getElementById("phoneNumber-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.phoneNumber;
document.getElementById("phoneNumber-group").appendChild(helpBlock);
}
//handle errors for message
if (data.errors.message && !document.querySelector('#message-group .help-block')) {
document.getElementById("message-group").classList.add("has-error");
let helpBlock = document.createElement('div');
helpBlock.classList.add('help-block');
helpBlock.innerHTML = data.errors.message;
document.getElementById("message-group").appendChild(helpBlock);
}
// handle errors for captcha ---------------
if (data.errors.captcha) {
swal({
title: "Error!",
text: data.errors.captcha,
icon: "error",
});
}
// handle errors for phpmailer ---------------
if (data.message) {
swal({
title: "Error!",
text: data.message,
icon: "error",
});
}
if (data.success) {
swal({
title: "Success!",
text: data.message,
icon: "success",
});
//document.getElementById("form").reset();
}
}
});
})

As mentioned by #marv255 there actually is no captcha data in your request apparently.
So try adding this:
'g-recaptcha-response' : grecaptcha.getResponse()
Just below
'message' : document.query ...
In your js file.

Related

Contact form PHP / HTML / JS - Phone not printing

I've been trying to figure out why my phone string is the only one not being printed in the received email from the contact form.
I have the following:
HTML:
<input
id="phone"
type="text"
name="phone"
placeholder="Telefone"
/>
PHP:
include_once (dirname(dirname(__FILE__)) . '/config.php');
$response = null;
if (isset($_POST["action"])) {
$action = $_POST["action"];
switch ($action) {
case "SendMessage": {
if (isset($_POST["email"]) && !empty($_POST["email"])) {
$message = $_POST["message"];
$message .= "<br/><br/>";
$message .= "phone:".$_POST["phone"];
$response = (SendEmail($message, $_POST["subject"], $_POST["name"], $_POST["email"], $email)) ? 'Mensagem Enviada!!' : "Sending Message Failed";
} else {
$response = "Sending Message Failed";
}
}
break;
default: {
$response = "Invalid action is set! Action is: " . $action;
}
}
}
JS:
function SendMail() {
$('.contact-form [type="submit"]').on('click', function () {
var emailVal = $('#contact-email').val();
if (isValidEmailAddress(emailVal)) {
var params = {
'action': 'SendMessage',
'name': $('#name').val(),
'email': $('#contact-email').val(),
'phone': $('#phone').val(),
'subject': $('#subject').val(),
'message': $('#message').val()
};
As i said, everything else is being received on our email, but the phone string.
What am i doing wrong?

Fetch data from mysql and if the result === 0 then do something

My main task is to create a contacts list. So the user presses the button, then the user sees on the screen, types in an Email of contact user and then if the response from server is "result === 0" the contact user will be successfully added to the contacts list. If the response from server is "result === -1", then the user was not found because of email does not exist.
Everything works fine, except one thing: even when the Email is wrong, it shows that the response from the user was successful.
I can't find what I do wrong. Can anyone help me please?
Here is my code:
Contact List (React Native):
addNewContact = (email) => {
this.setState({
promptVisible: false,
});
if (email === this.props.email) {
Alert.alert('This is your username', 'You cannot add yourself to contacts!');
return;
}
for (var i = 0; i < this.state.contacts.length; i++) {
if (email === this.state.contacts[i].email) {
Alert.alert('Existing Contact', 'Contact ' + email + ' already exists');
return;
}
}
this.showLoading();
fetch('LINK')
.then((response) => response.json())
.then((responseData) => {
this.hideLoading();
var result = responseData.result;
var contactId = responseData.id;
var name = responseData.name;
if (result === 0) {
console.log("Success");
var newContacts = this.state.contacts.slice();
newContacts[newContacts.length] = {
contact_id: contactId,
name: name,
email: email
}
this.setState({
dataSource: this.state.dataSource.cloneWithRows(newContacts),
contacts: newContacts
});
Alert.alert('Contact added', 'User ' + email + ' was added to your contacts')
console.log(newContacts);
} else {
if (result === -1) {
Alert.alert('Not Found', 'User ' + email + ' not found');
console.log("Bad");
console.log(responseData);
}
}
})
.done;
}
Server (PHP):
<?php
include 'DBConfig.php';
$conn = new mysqli($Name, $User, $Pass, $Database);
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$json = file_get_contents('php://input');
$obj = json_decode($json,true);
$email = $obj['email'];
$sql = "SELECT id, name, email FROM Registration WHERE email='$email'";
$result = mysqli_fetch_array(mysqli_query($conn,$sql));
if (isset($result)) {
$result = array('result' => 0);
echo json_encode($result);
} else {
$result = array('result' => -1);
echo json_encode($result);
}
echo $json;
$conn->close();
?>
upd: I found out that in my console it shows:
Success
Array [
Object {
"contact_id": undefined,
"email": "Djdf",
"name": undefined,
},
]

Open cart send mail from model

I am using Opencart V2.0.1.1 for one project and i have a custom form in product page(.tpl). I want to send mail to store owner on submit of that form. I am able to process it and receiving the data till model but from model i am not able to send the mail and i am getting below error.
SyntaxError: Unexpected token < OK Notice: Undefined property:
Mail::$ErrorInfo in
/opt/lampp/htdocs/dutees/catalog/model/catalog/product.php on
line 784{"success":"success"}
Below is my code
// CONTROLLER FUNCTION
public function getquote()
{
$data = array(); $json = array();
if (isset($this->request->post['name'])) {
$data['name'] = $this->request->post['name'];
}
if (isset($this->request->post['email'])) {
$data['email'] = $this->request->post['email'];
}
if (isset($this->request->post['mobile'])) {
$data['mobile'] = $this->request->post['mobile'];
}
if (isset($this->request->post['address'])) {
$data['address'] = $this->request->post['address'];
}
if (isset($this->request->post['description'])) {
$data['description'] = $this->request->post['description'];
}
if($this->config->get('config_email') != 'null' || $this->config->get('config_email') !='')
$data['store_email'] = $this->config->get('config_email');
if($this->config->get('config_name') != 'null' || $this->config->get('config_name') !='')
$data['store_name'] = $this->config->get('config_name');
$this->load->model('catalog/product');
$gq_status = $this->model_catalog_product->sendQuote($data);
if($gq_status = "success"){
$json['success'] = "success";
}else{
$json['error'] = "Error : We are unable to send your request now, please use contact-us form";
}
$this->response->addHeader('Content-Type: application/json');
$this->response->setOutput(json_encode($json));
}
// MODEL FUNTION
public function sendQuote($data = array()) {
$status = ""; $name ="";$email ="";$mobile ="";$address ="";$description ="";
if(isset($data['name']))
$name = $data['name'];
else
$name = "Not Available";
if(isset($data['email']))
$email = $data['email'];
else
$email = "Not Available";
if(isset($data['mobile']))
$mobile = $data['mobile'];
else
$mobile = "Not Available";
if(isset($data['address']))
$address = $data['address'];
else
$address = "Not Available";
if(isset($data['description']))
$description = $data['description'];
else
$description = "Not Available";
if(isset($data['store_email']))
$store_email = $data['store_email'];
else
$store_email = "abc#def.net";
if(isset($data['store_name']))
$store_name = $data['store_name'];
else
$store_name = "Enquiry";
$message = '
<html>
<body>
<MY HTML MAIL CONTENT GOES HERE>
</body>
</html>
';
$this->load->mail;
$mail = new Mail();
$mail->protocol = $this->config->get('config_mail_protocol');
$mail->parameter = $this->config->get('config_mail_parameter');
$mail->hostname = $this->config->get('config_smtp_host');
$mail->username = $this->config->get('config_smtp_username');
$mail->password = $this->config->get('config_smtp_password');
$mail->port = $this->config->get('config_smtp_port');
$mail->timeout = $this->config->get('config_smtp_timeout');
$mail->setTo($store_email);
$mail->setFrom($email);
$mail->setSender($store_name);
$mail->setSubject("Product Get Quote");
//$mail->setText("test message body text");
$mail->setHtml($message);
if(!$mail->send()) {
$status = 'Mailer Error: ' . $mail->ErrorInfo;
} else {
$status = 'success';
}
return $status;
}
// VIEW AJAX
<script>
$('#gq-submit').click(function(){
var name=$('#gq-name').val();
var email=$('#gq-email').val();
var mobile=$('#gq-mobile').val();
var address=$('#gq-address').val();
var description=$('#gq-description').val();
if(name != '' && email != ''&& mobile != '' && description != ''){
$.ajax({
type:'post',
url:'index.php?route=product/product/getquote',
dataType: 'json',
data:'name='+name+'&email='+email+'&mobile='+mobile+'&address='+address+'&description='+description,
beforeSend: function() {
$('#gq-submit').button('loading');
},
complete: function() {
$('#gq-submit').button('reset');
},
success: function(json) {
$('.alert-success, .alert-danger').remove();
$('.form-group').removeClass('has-error');
if (json['error']) {
$('#gq-showcheck').after('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + json['error'] + '</div>');
}
if (json['success']) {
$('#gq-showcheck').after('<div class="alert alert-success"><i class="fa fa-check-circle"></i> ' + json['success'] + '<button type="button" class="close" data-dismiss="alert">×</button></div>');
}
},
error: function(xhr, ajaxOptions, thrownError) {
console.log(thrownError + "\r\n" + xhr.statusText + "\r\n" + xhr.responseText);
}
});}else{
$('#gq-showcheck').after('<div class="alert alert-danger"><i class="fa fa-exclamation-circle"></i> ' + "Please fill all the fields" + '</div>');
}
});
</script>
You can't send mail, maybe the mail settings are incorrect and
the Opencart own Mail class hasn't any ErrorInfo field inside it.
See: system/library/mail.php
First of all set the the correct mail parameters and don't use $mail->ErrorInfo because it doesn't exist. When error occured during sending mail it calls a trigger_error.

Php ajax just want to display error message only form submit

After send my form data to php file its return if any error found. But its also return success before ajax redirect page. I want display error message only and if success, redirect another page.
ajax:
$("#msform").submit(function(){
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
dataType : 'json',
success: function(data){
if ( ! data.success) {
$(".help-block").fadeIn().html(data.error);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});
php:
include_once ("db.php");
global $dbh;
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
$error ="* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
$error ="* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
$error ="* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}
$data = array();
$data['error'] = $error;
$data['success'] = $success;
if (!empty($data)) {
echo json_encode($data);
}
Solved the problem, in this way:
Ajax:
$("#msform").submit(function(){
// collect input name
ver name = var catag=$('#name').val();
$.ajax({
type:"post",
url:"pagesubmit.php",
data: $("#msform").serialize(),
success: function(data){
if ( data != 'success') {
$(".help-block").fadeIn().html(data);
} else {
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + name;
}
}
});
});
php:
function check($name){
if(!$name || strlen($name = trim($name)) == 0){
echo "* Username not entered";
}
else{
$name = stripslashes($name);
if(strlen($name) < 5){
echo "* Name below 5 characters";
}
else if(!preg_match("/^([0-9a-z])+$/i", $name)){
echo "* Name not alphanumeric";
}
else {
return 1;
}
}
}
$name = mysqli_real_escape_string($dbh, $_POST['name']);
$thisname = strtolower($name);
$retval = check($thisname);
if($retval ==1){ // if no error found
echo 'success';
}
EDIT
Set your variables $success and $error
$success = "";
$error= "";
If you doesn't init them, you cannot use them and the .=operator is for concatenation not for set.
Then you should encode the response in php in JSON.
Something like
$response = json_encode(
array(
'success'=> true,
'route' => "mypage/info?user=$_SESSION['username']"
)
);
And return this, then access your response like you already do :
var success = response.success;
UPDATE
change this code to add an else statement :
if($retval ==1){ // if no error found
$success ='upage/userpage?user='.$_SESSION['username'].'';
}else{
$success = 'error';
}
and this line :
else {
return 1;
}
to :
else {
$error = 'none';
}
and in your javascript :
$("#msform").submit(function(){
$.ajax({
type :"post",
url :"pagesubmit.php",
data : $("#msform").serialize(),
dataType : 'json',
success : function(data){
if(data.success == 'error') {
$(".help-block").fadeIn().html(data.error);
}else{
$(".help-block").fadeOut();
$("#msform")[0].reset();
window.location = 'http://dbsvawdez.com/' + data.success;
}
}
});
});

Manually sending a post in PHP

I have a form that will be validated client side before being submitted via an ajax request to the server for server-side validation. Should the validation fail server side then a postback will need to be made containing all the error messages. Is there some way I can do this?
For example:
if ((!empty($nameError) && (!empty($emailError)) {
$_POST['nameError'] = $nameError;
$_POST['emailError'] = $emailError;
// send postback with values
}
else {
echo 'No errors';
}
UPDATE ------------------------------------------------
Here is the javascript that handles the submission of the form:
$(".button").click(function() {
$(".error").hide();
var name = $(":input.name").val();
if ((name == "") || (name.length < 4)){
$("label#nameErr").show();
$(":input.name").focus();
return false;
}
var email = $(":input.email").val();
if (email == "") {
$("label#emailErr").show();
$(":input.email").focus();
return false;
}
var phone = $(":input.phone").val();
if (phone == "") {
$("label#phoneErr").show();
$(":input.phone").focus();
return false;
}
var comment = $.trim($("#comments").val());
if ((!comment) || (comment.length > 100)) {
$("label#commentErr").show();
$("#comments").focus();
alert("hello");
return false;
}
var info = 'name:' + name + '&email:' + email + '&phone:' + phone + '&comment:' + comment;
var ajaxurl = '<?php echo admin_url("admin-ajax.php"); ?>';
alert(info);
jQuery.ajax({
type:"post",
dataType:"json",
url: myAjax.ajaxurl,
data: {action: 'submit_data', info: info},
success: function(response) {
if (response.type == "success") {
alert("success");
}
else {
alert("fail");
}
}
});
$(":input").val('');
return false;
});
And here is the php function that the ajax posts to:
function submit_data() {
$nameErr = $emailErr = $phoneErr = $commentErr = "";
$full = explode("&", $_POST["info"]);
$fname = explode(":", $full[0]);
$name = $fname[1];
$femail = explode(":", $full[1]);
$email = $femail[1];
$fphone = explode(":", $full[2]);
$phone = $fphone[1];
$fcomment = explode(":", $full[3]);
$comment = $fcomment[1];
if ((empty($name)) || (strlen($name) < 4)){
$nameErr = "Please enter a name";
}
else if (!preg_match("/^[a-zA-Z ]*$/", $name)) {
$nameErr = "Please ensure you have entered your name and surname";
}
if (empty($email)) {
$emailErr = "Please enter an email address";
}
else if (!preg_match("/([\w\-]+\#[\w\-]+\.[\w\-]+)/", $email)) {
$emailErr = "Please ensure you have entered a valid email address";
}
if (empty($phone)) {
$phoneErr = "Please enter a phone number";
}
else if (!preg_match("/(?:\(?\+\d{2}\)?\s*)?\d+(?:[ -]*\d+)*$/",$phone)) {
$phoneErr = "Please ensure you have entered a valid phone number";
}
if ((empty($nameErr)) && (empty($emailErr)) && (empty($phoneErr)) && (empty($commentErr))) {
$conn = mysqli_connect("localhost", "John", "Change9", "plugindatadb");
mysqli_query($conn, "INSERT INTO data (Name, Email, Phone, Comment) VALUES ('$name', '$email', '$phone', '$comment')");
}
else {
// display error messages
}
die();
}
Your answer will be in two parts:
Pseudo code:
Part1: PHP
if ($error) {
$reply["status"]=false;
$reply["message"]="Fail message"; //Here you have to put your own message, maybe use a variable from the validation you just did before this line: $reply["message"] = $fail_message.
}
else {
$reply["status"]=true;
$reply["message"]="Success message"//$reply["message"] = $success_message;
}
echo json_encode($reply);//something like {"status":true, "message":"Success message"}
Part2 AJAX: modify you ajax response to this.
success: function(response) {
if (response.status == true) {
alert("success: "+response.message);
}
else {
alert("fail: " + response.message);
}
}
Use json ajax request. In case error exists show the error message. I generally put a flag for success or fail .
$message='';
if ((!empty($nameError) && (!empty($emailError)) {
$errorArray=array();
$errorArray['nameError'] = $nameError;
$errorArray['emailError'] = $emailError;
// send postback with values
}
else {
$message='No errors';
}
echo json_encode(array(
"message"=>$message,
"errors"=>$errorArray
));

Categories