how to give required in google captcha - javascript

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');

Related

I want to change or remove my html element by getting URL parameters that I set after successful register

First of all I must say that I'm very new to website design and coding so please make your answer simple thanks a lot .
So I have my file register.php that contains my form .
I have my action file named register-controller.php that gets the data from user , checks it and inserts it to database .
What I need is that whenever the register is success , my form gets hidden or removed and my new div shows up that contains 'register successful' . ( On the same page "register.php" )
Can I use the variable that I passed to header "register=success" to do this action ? Should I use AJAX ? JSON ? what should I do ? Please give me the simplest answer thank you all .
MY "register.php" file contains these :
<?php
require_once "../DB/users-database.php";
?>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="/Header.CSS">
<link rel="stylesheet" href="/Style.CSS">
<link rel="stylesheet" href="/Footer.CSS">
<script src="https://kit.fontawesome.com/38b3678073.js" crossorigin="anonymous"></script>
<script src="../JS/main.js" async></script>
<title>ثبت نام | PCGA</title>
</head>
<body>
<?php include '../header.php' ?>
<div class="register-container">
<form action="../controllers/register-controller.php" method = "POST">
<label class = "email-label" for="email">ایمیل</label>
<input type="text" id="email" name="email" placeholder="example#example.com" value = '<?php if(isset($_REQUEST['email'])){echo $_REQUEST['email'];}else{echo '';} ?>'>
<?php
if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyEmail'){
echo "<span class = 'empty-email'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidEmailFormat') {
echo "<span class = 'formaterr-email'>فرمت ایمیل نادرست است*</span>";
}
?>
<label class = "phone-label" for="phone">شماره موبایل</label>
<input type="text" id="phone" name="phone" placeholder="09xxxxxxxxx" value = '<?php if(isset($_REQUEST['phone'])){echo $_REQUEST['phone'];}else{echo '';} ?>'>
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyPhone'){
echo "<span class = 'empty-phone'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidPhoneNumber') {
echo "<span class = 'formaterr-phone'>شماره موبایل حداکثر 11 عدد است و حروف قابل قبول نیست*</span>";
}
?>
<label class = "user-label" for="username">نام کاربری</label>
<input type="text" id="username" name="username" placeholder="Username" value = '<?php if(isset($_REQUEST['username'])){echo $_REQUEST['username'];}else{echo '';} ?>'>
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyUsername'){
echo "<span class = 'empty-user'>فیلد نباید خالی باشد *</span>";
}
else if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'invalidUserName') {
echo "<span class = 'formaterr-user'>فرمت نام کابری نادرست است*</span>";
}
?>
<label class="pass-label" for="password">رمز عبور</label>
<input type="password" id = "password" name = "password" placeholder = "Password" >
<?php if (isset($_REQUEST['error']) && $_REQUEST['error'] == 'emptyPass'){
echo "<span class = 'empty-pass'>فیلد نباید خالی باشد *</span>";
}
?>
<div class="checkbox-container">
<input type="checkbox" class = 'checkbox-style' name = 'rules-check'>
<label for="checkbox" class="checkbox-label">من قوانین فروشگاه را کامل مطالعه کرده ام و با آن موافق هستم</label>
<?php if (isset($_REQUEST['rules'])){
echo "<span class = 'rules-error'>قبول قوانین اجباری است و آن را حتما مطالعه کنید *</span>";
}
?>
</div>
<button type="submit" name = "submit" id="submit">ثبت نام</button>
</form>
</div>
<?php
if (isset($_REQUEST['register'])){
echo "<div class = 'register-success'>
<span class = 'register-success-span'>ثبت نام با موفقیت انجام شد</span>
</div>" ;
}
?>
<?php include '../footer.php' ?>
</body>
</html>
MY "register-controller.php" file contains these :
<?php
require "../DB/users-database.php";
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
if (isset($_POST['submit']) && $_POST['rules-check']) {
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$username = test_input($_POST["username"]);
$pass = test_input($_POST["password"]);
if (empty($username)){
header("Location: ../page/register.php?error=emptyUsername&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($phone)){
header("Location: ../page/register.php?error=emptyPhone&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($pass)){
header("Location: ../page/register.php?error=emptyPass&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (empty($email)){
header("Location: ../page/register.php?error=emptyEmail&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
elseif (!filter_var($email , FILTER_VALIDATE_EMAIL)) {
header("Location: ../page/register.php?error=invalidEmailFormat&username=".$username."&phone=".$phone);
exit();
}
elseif (!preg_match("/^[a-z\d_]{2,20}$/i" , $username)){
header("Location: ../page/register.php?error=invalidUserName&email=".$email."&phone=".$phone);
exit();
}
elseif (!preg_match("/^[0-9]{11}+$/" , $phone)){
header("Location: ../page/register.php?error=invalidPhoneNumber&email=".$username."&phone=".$phone);
exit();
}
else {
$sql = "SELECT username FROM registered WHERE username = ?";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt , $sql)){
header("Location: ../page/register.php?error=SQLcheckUser");
exit();
}
else {
mysqli_stmt_bind_param($stmt , "s" , $username);
mysqli_stmt_execute($stmt);
mysqli_stmt_store_result($stmt);
$rowcount = mysqli_stmt_num_rows($stmt);
if($rowcount > 0 ) {
header("Location: ../page/register.php?error=UserNameTaken");
exit();
}
else {
$sql = "INSERT INTO registered(email,phone,username,password) VALUES(?,?,?,?)";
$stmt = mysqli_stmt_init($conn);
if(!mysqli_stmt_prepare($stmt , $sql)){
header("Location: ../page/register.php?error=SQLInsert");
exit();
}
else {
$hased_pass = password_hash($pass , PASSWORD_DEFAULT);
mysqli_stmt_bind_param($stmt , "ssss" , $email , $phone , $username , $hased_pass);
mysqli_stmt_execute($stmt);
header("Location: ../page/register.php?register=success");
exit();
}
}
}
}
mysqli_stmt_close($stmt);
mysqli_close($conn);
}
elseif (isset($_POST['submit']) && !isset($_POST['rules-check'])) {
$email = test_input($_POST["email"]);
$phone = test_input($_POST["phone"]);
$username = test_input($_POST["username"]);
$pass = test_input($_POST["password"]);
header("Location: ../page/register.php?rules=notChecked&username=".$username."&email=".$email."&phone=".$phone);
exit();
}
else {
header("Location: ../page/register.php?access=denied");
exit();
}
?>
You can render the part of the page you prefer depending on your URL parameters by doing
<?php
if ($_GET['success']) { ?>
<-- YOUR HTML SUCCESS CODE -->
<?php } else { ?>
<-- YOUR HTML FORM CODE -->
<?php }
?>
Ajax is the best solution for me (it can be difficult to understand but the code is clean), here an example of Ajax with your situation :
Extras is the ID of all the input in the form
Page is the PHP page to be executed (register-controller.php)
Origin is the ID where you want to put the result, Origin can be null.
(To have something in the return, you have to put an echo in the php file you specified in Page)
static Ajax(origin,Extras,page)
{
var xhr = new XMLHttpRequest();
let formData = new FormData();
for(var element in Extras)
{
if(document.getElementById(element))
{
formData.append(element,document.getElementById(element));
}
else
{
let checkbox = document.getElementsByName(element);
if(checkbox)
{
//Checkbox don't work with an ID so put instead a name
for(let i=0;i<checkbox.length;i++)
{
if(checkbox[i].checked)
{
formdata.append(element+i,"1")
}
else
{
formdata.append(element+i,"0")
}
}
}
}
}
xhr.open('POST',page);
xhr.addEventListener('readystatechange', function () {
if (xhr.readyState === XMLHttpRequest.DONE && xhr.status === 200) {
let i= xhr.responseText;
if(origin!=null)
{
if(document.getElementById(origin) && xhr.responseText!="")
// the result document.getElementById(origin).innerHTML=xhr.responseText;
}
finish(i);
}
else if (xhr.readyState === XMLHttpRequest.DONE && xhr.status != 200) {
// error message XHR,
let textError = "Ajax Error : " + xhr.status + ", " + xhr.statusText + ", ";
alert(textError);
}
});
// send
xhr.send(formData);
}

window.location.reload reloads constantly

I didn't find an answer so im asking you guys.
window.location.reload() constantly reloads without a break.
I'm trying to make something that checks if the form has no input in it, and if doesn't I want it to make an alert, it's working but it reloads constantly. Here's my code:
<?php
$from = $_POST['email_adress'];
$subject = $_POST['subject'];
$select = $_POST['select'];
$message2 = $_POST['message2'];
$name = $_POST['firstname'];
$name2 = $_POST['lastname'];
if ($_POST['firstname'] == "") {
echo '<script language="javascript">';
echo 'alert("First Name is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['subject'] == "") {
echo '<script language="javascript">';
echo 'alert("Subject is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['email_adress'] == "") {
echo '<script language="javascript">';
echo 'alert("Email Adress is Mandatory.");';
echo 'window.location.reload("contactus.html");';
echo '</script>';
exit;
}
elseif ($_POST['message2'] == "") {
echo '<script language="javascript">';
echo 'alert("A Message is Mandatory.");';
echo 'window.location.reload("contactus.html");';
exit;
echo '</script>';
exit;
} else {
header("Location: contactus.html");
$email_subject = "A submittion form";
$to ="sudaiguy1#gmail.com";
$headers = "From: sudaiguy1#gmail.com";
$email_body = 'You have been contacted by $name $name2 and his email is $from. \n The message he wanted to say was in the general subject of $select and more specifically $subject and the message is $message2';
mail($to,$email_subject,$email_body, $headers);
}
?>
Maybe this can be an inspiration?
<?php
session_start();
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
$is_redirect = isset($_SESSION['to']);
if ($is_redirect && !is_mail_valid($_SESSION)) {
$to = $_SESSION['to'];
$subject = $_SESSION['subject'];
$body = $_SESSION['body'];
}
$_SESSION = array();
} else {
if (is_mail_valid($_POST)) {
$to = $_POST['to'];
$subject = $_POST['subject'];
$body = $_POST['body'];
mail($to, $subject, $body);
} else {
$_SESSION = $_POST;
}
header("Location: index.php");
exit;
}
function is_mail_valid($mail) {
global $errors;
global $valid;
$errors = array();
if (trim($mail['to']) == FALSE) { $errors['empty_to'] = TRUE; }
if (trim($mail['subject']) == FALSE) { $errors['empty_subject'] = TRUE; }
if (trim($mail['body']) == FALSE) { $errors['empty_body'] = TRUE; }
$valid = empty($errors);
return $valid;
}
?>
<?php if (!$valid) { ?>
<script type="text/javascript">
<?php if ($errors['empty_to']) {?>
alert('To: cannot be empty')
<?php } ?>
<?php elseif ($errors['empty_subject']) {?>
alert('Subject: cannot be empty')
<?php } ?>
<?php elseif ($errors['empty_body']) {?>
alert('Body: cannot be empty')
<?php } ?>
</script>
<?php } ?>
<form method="post">
<div>
<label for="to">To</label>
<input id="to" type="email" name="to" value="<?php echo $to;?>" />
</div>
<div>
<label for="subject">Subject</label>
<input id="subject" type="text" name="subject" value="<?php echo $subject;?>" />
</div>
<div>
<label for="body">Body</label>
<textarea id="body" name="body"><?php echo $body;?></textarea>
</div>
<div>
<input type="submit" value="Send">
</div>
</form>
Basically you start using session using session_start()
On POST:
If you don't have an error:
send the mail
redirect to the conctactus page.
If you have an error:
save the input in the session
redirect to the contact us page
On GET:
If you have nothing in session or the mail in session is valid, just render the html.
If you have something in session and that data is invalid, render the html, render the alert script, and set the "value" attributes of the input to maintain the user's input values.
Clear the session data.
This solution requires that you change your contactus.html to contactus.php in order to use sessions.
<?php
// to use a session, you must start it
session_start();
// variable to store any error message
$error = null;
$from = $_POST['email_adress'];
$subject = $_POST['subject'];
$select = $_POST['select'];
$message2 = $_POST['message2'];
$name = $_POST['firstname'];
$name2 = $_POST['lastname'];
if ($_POST['firstname'] == "") {
$error = "First Name is Mandatory.";
} elseif ($_POST['subject'] == "") {
$error = "Subject is Mandatory.";
} elseif ($_POST['email_adress'] == "") {
$error = "Email Adress is Mandatory.";
} elseif ($_POST['message2'] == "") {
$error = "A Message is Mandatory.";
}
if ($error) {
// store the error in a session so that you can use it on another page
$_SESSION['error'] = $error;
} else {
$email_subject = "A submittion form";
$to ="sudaiguy1#gmail.com";
$headers = "From: sudaiguy1#gmail.com";
$email_body = 'You have been contacted by $name $name2 and his email is $from. \n The message he wanted to say was in the general subject of $select and more specifically $subject and the message is $message2';
mail($to,$email_subject,$email_body, $headers);
}
// regardless of whether there is an error or not, it always goes to Contact Us page
header("Location: contactus.php");
exit;
?>
Then in your contactus.php, you would have
<?php
// resume session again
session_start();
?>
<!-- somewhere in your HTML code -->
<?php if (isset($_SESSION['error'])) : ?>
<div class="error-message"><?php echo $_SESSION['error'] ?></div>
<?php endif ?>
<?php
// you probably will want to remove the error afterwards
unset($_SESSION['error']);
?>
If you can't do that, then this solution will not work and you'll have to resort to AJAX (where you send back your error message via the response you get back from your AJAX response).

getting the email value from the database and sending it (PHP email) / refresh page without the website link being changed

I Have 2 problems with this script, something is wrong
1. the email address value can't be selected from the database.
the script works only if I manually type the e-mail
$yourEmail = "email#exemple.com";
after I press the submit button, I want the page to refresh without the website link being changed or after i click send, the contact box should close.
Could you please help to solve these problems?
Thank you in advance!
<?php
$sql = "select * from tables where email='" . $email . "'";
while($row=mysql_fetch_array($sql))
{
$email=$row['email'];
}
$yourEmail = $email; // the email address you wish to receive these mails through
$yourWebsite = "WEBSITE NAME";
$thanksPage = ''; // URL to 'thanks for sending mail' page; leave empty to keep message on the same page
$maxPoints = 4;
$requiredFields = "name,email,comments";
$error_msg = array();
$result = null;
$requiredFields = explode(",", $requiredFields);
function clean($data) {
$data = trim(stripslashes(strip_tags($data)));
return $data;
}
function isBot() {
$bots = array("Indy", "Blaiz", "Java", "libwww-perl", "Python", "OutfoxBot", "User-Agent", "PycURL", "AlphaServer", "T8Abot", "Syntryx", "WinHttp", "WebBandit", "nicebot", "Teoma", "alexa", "froogle", "inktomi", "looksmart", "URL_Spider_SQL", "Firefly", "NationalDirectory", "Ask Jeeves", "TECNOSEEK", "InfoSeek", "WebFindBot", "girafabot", "crawler", "www.galaxy.com", "Googlebot", "Scooter", "Slurp", "appie", "FAST", "WebBug", "Spade", "ZyBorg", "rabaz");
foreach ($bots as $bot)
if (stripos($_SERVER['HTTP_USER_AGENT'], $bot) !== false)
return true;
if (empty($_SERVER['HTTP_USER_AGENT']) || $_SERVER['HTTP_USER_AGENT'] == " ")
return true;
return false;
}
if ($_SERVER['REQUEST_METHOD'] == "POST") {
if (isBot() !== false)
$error_msg[] = "No bots please! UA reported as: ".$_SERVER['HTTP_USER_AGENT'];
// lets check a few things - not enough to trigger an error on their own, but worth assigning a spam score..
// score quickly adds up therefore allowing genuine users with 'accidental' score through but cutting out real spam :)
$points = (int)0;
$badwords = array("adult", "beastial", "bestial", "blowjob", "clit", "cum", "cunilingus", "cunillingus", "cunnilingus", "cunt", "ejaculate", "fag", "felatio", "fellatio", "fuck", "fuk", "fuks", "gangbang", "gangbanged", "gangbangs", "hotsex", "hardcode", "jism", "jiz", "orgasim", "orgasims", "orgasm", "orgasms", "phonesex", "phuk", "phuq", "pussies", "pussy", "spunk", "xxx", "viagra", "phentermine", "tramadol", "adipex", "advai", "alprazolam", "ambien", "ambian", "amoxicillin", "antivert", "blackjack", "backgammon", "texas", "holdem", "poker", "carisoprodol", "ciara", "ciprofloxacin", "debt", "dating", "porn", "link=", "voyeur", "content-type", "bcc:", "cc:", "document.cookie", "onclick", "onload", "javascript");
foreach ($badwords as $word)
if (
strpos(strtolower($_POST['comments']), $word) !== false ||
strpos(strtolower($_POST['name']), $word) !== false
)
$points += 2;
if (strpos($_POST['comments'], "http://") !== false || strpos($_POST['comments'], "www.") !== false)
$points += 2;
if (isset($_POST['nojs']))
$points += 1;
if (preg_match("/(<.*>)/i", $_POST['comments']))
$points += 2;
if (strlen($_POST['name']) < 3)
$points += 1;
if (strlen($_POST['comments']) < 15 || strlen($_POST['comments'] > 1500))
$points += 2;
if (preg_match("/[bcdfghjklmnpqrstvwxyz]{7,}/i", $_POST['comments']))
$points += 1;
// end score assignments
foreach($requiredFields as $field) {
trim($_POST[$field]);
if (!isset($_POST[$field]) || empty($_POST[$field]) && array_pop($error_msg) != "Please fill in all the required fields and submit again.\r\n")
$error_msg[] = "Please fill in all the required fields and submit again.";
}
if (!empty($_POST['name']) && !preg_match("/^[a-zA-Z-'\s]*$/", stripslashes($_POST['name'])))
$error_msg[] = "The name field must not contain special characters.\r\n";
if (!empty($_POST['email']) && !preg_match('/^([a-z0-9])(([-a-z0-9._])*([a-z0-9]))*\#([a-z0-9])(([a-z0-9-])*([a-z0-9]))+' . '(\.([a-z0-9])([-a-z0-9_-])?([a-z0-9])+)+$/i', strtolower($_POST['email'])))
$error_msg[] = "That is not a valid e-mail address.\r\n";
if (!empty($_POST['url']) && !preg_match('/^(http|https):\/\/(([A-Z0-9][A-Z0-9_-]*)(\.[A-Z0-9][A-Z0-9_-]*)+)(:(\d+))?\/?/i', $_POST['url']))
$error_msg[] = "Invalid website url.\r\n";
if ($error_msg == NULL && $points <= $maxPoints) {
$subject = "Automatic Form Email";
$message = "You received this e-mail message through your website: \n\n";
foreach ($_POST as $key => $val) {
if (is_array($val)) {
foreach ($val as $subval) {
$message .= ucwords($key) . ": " . clean($subval) . "\r\n";
}
} else {
$message .= ucwords($key) . ": " . clean($val) . "\r\n";
}
}
$message .= "\r\n";
$message .= 'IP: '.$_SERVER['REMOTE_ADDR']."\r\n";
$message .= 'Browser: '.$_SERVER['HTTP_USER_AGENT']."\r\n";
$message .= 'Points: '.$points;
if (strstr($_SERVER['SERVER_SOFTWARE'], "Win")) {
$headers = "From: $yourEmail\r\n";
} else {
$headers = "From: $yourWebsite <$yourEmail>\r\n";
}
$headers .= "Reply-To: {$_POST['email']}\r\n";
if (mail($yourEmail,$subject,$message,$headers)) {
if (!empty($thanksPage)) {
header("Location: $thanksPage");
exit;
} else {
$result = 'Your mail was successfully sent.';
$disable = true;
}
} else {
$error_msg[] = 'Your mail could not be sent this time. ['.$points.']';
}
} else {
if (empty($error_msg))
$error_msg[] = 'Your mail looks too much like spam, and could not be sent this time. ['.$points.']';
}
}
function get_data($var) {
if (isset($_POST[$var]))
echo htmlspecialchars($_POST[$var]);
}
?>
html form
<form action="<?php echo basename(__FILE__); ?>" method="post">
<noscript>
<p><input type="hidden" name="nojs" id="nojs" /></p>
</noscript>
<p>
<label for="name">Name: *</label>
<input type="text" name="name" id="name" value="<?php get_data("name"); ?>" /><br />
<label for="email">E-mail: *</label>
<input type="text" name="email" id="email" value="<?php get_data("email"); ?>" /><br />
<label for="url">Website URL:</label>
<input type="text" name="url" id="url" value="<?php get_data("url"); ?>" /><br />
<label for="location">Location:</label>
<input type="text" name="location" id="location" value="<?php get_data("location"); ?>" /><br />
<label for="comments">Comments: *</label>
<textarea name="comments" id="comments" rows="5" cols="20"><?php get_data("comments"); ?></textarea><br />
</p>
<p>
<input type="submit" name="submit" id="submit" value="Send" <?php if (isset($disable) && $disable === true) echo ' disabled="disabled"'; ?> />
</p>
</form>
Before your while loop your suppose to actually perform the query with mysql_query or mysqli_query in your case mysql_query.
Your other problem is your fetching the results as an array which is index based (0...) and your using a string to access it so you should call mysql_fetch_assoc which returns an associative array which can be accessed in your current implementation
$sql = "select * from tables where email='" . $email . "'";
$result = mysql_query($sql, $connection);// this actually performs the query and returns the result to be fetched using mysql_fetch_array or it's other methods such as mysql_fetch_assoc
while($row=mysql_fetch_assoc($result)){
$email=$row['email'];
}
Also declare your $email variable outside the while loop as if no rows were returned from the database your $email variable won't exist therefore breaking your code so you should bring it to the top of the while loop and initialize it to some default value.

Ajax status received but not applying next steps

I have a comment system in which user comments and through ajax it validates the data and sent to .php page. The problem is it receives the status=1 but does not apply the else if Ajax code. I am stuck here. Any suggestions or help will be highly regarded.
AJAX
<script type="text/javascript">
$(document).ready(function() {
$("#submit_comment").click(function() {
var proceed = true;
$(" #comment_form textarea[required=true]").each(function(){
$(this).css('border-color','');
if(!$.trim($(this).val())){ //if this field is empty
$(this).css('border-color','red'); //change border color to red
proceed = false; //set do not proceed flag
}
});
if(proceed)
post_data = {
'user_email' : $('input[name=email]').val(),
'pid' : $('input[name=productid]').val(),
'msg' : $('textarea[name=comment]').val()
};
$.post('comments.php', post_data, function(response){
if(response.type == 'error'){ //load json data from server and output message
output = '<div class="error">'+response.text+'</div>';
}
else if(response.status && response.type != 'error')
{
output = '<div class="success">'+response.text+'</div>';
$(response.html).hide().insertBefore('#comment_form').slideDown();
$(" #comment_form textarea[required=true]").val('');
$("#comment_form #comment_body").slideUp();
}
$("#comment_form #comment_results").hide().html(output).slideDown();
}, 'json');
});
//reset previously set border colors and hide all message on .keyup()
$("#comment_form input[required=true], #comment_form textarea[required=true]").keyup(function() {
$(this).css('border-color','');
$("#result").slideUp();
});
});
</script>
Form
<?php
include "comment.php";
$comments = array();
$result = mysqli_query($con,"SELECT * FROM comments where product_id='$id' ORDER BY dt LIMIT 5");
while($row = mysqli_fetch_assoc($result))
{
$comments[] = new Comment($row);
}
?>
<?php
foreach($comments as $c){
echo $c->markup();
}
?>
</div>
<?php
}
}
?>
<div class="form-style" id="comment_form">
<div id="comment_results"></div>
<div id="comment_body">
<input type="hidden" name="email" id="email" value="<?php echo $email?>">
<input type="hidden" name="productid" id="productid" value="<?php echo $pid?>" />
<label for="field5"><span>Comment: <span class="required">*</span></span>
<textarea name="comment" id="comment" class="textarea-field" required="true"></textarea>
</label>
<label>
<span> </span><input type="submit" id="submit_comment" value="Submit"">
</label>
</div>
</div>
comment.php
<?php
class Comment
{
private $data = array();
public function __construct($row)
{
$this->data = $row;
}
public function markup()
{ $d = &$this->data;
// Converting the time to a UNIX timestamp:
$d['dt'] = strtotime($d['dt']);
// Needed for the default gravatar image:
return '
<div class="comment">
<div class="name">'.$d['email'].'</div>
<div class="date" title="Added at '.date('H:i \o\n d M Y',$d['dt']).'">'.date('d M Y',$d['dt']).'</div>
<p>'.$d['body'].'</p>
</div>
';
}
}
?>
comments.php
<?php
include("db/db.php");
include "comment.php";
if($_POST)
{
if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') {
$output = json_encode(array( //create JSON data
'type'=>'error',
'text' => 'Sorry Request must be Ajax POST'
));
die($output); //exit script outputting json data
}
//Sanitize input data using PHP filter_var().
$user_name = filter_var($_POST["user_email"], FILTER_SANITIZE_STRING);
$pid = filter_var($_POST["pid"], FILTER_VALIDATE_INT);
$message = filter_var($_POST["msg"], FILTER_SANITIZE_STRING);
$arr = array();
//additional php validation
if(strlen($message)<3){ //check emtpy message
$output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.'));
die($output);
}
mysqli_query($con,"INSERT INTO comments(email,body,product_id) values('$user_name','$message','$pid')");
$arr['dt'] = date('r',time());
$arr['id'] = mysql_insert_id();
$res=mysqli_query($con,$query);
$arr = array_map('stripslashes',$arr);
$insertedComment = new Comment($arr);
if(!$res)
{
$output = json_encode(array('type'=>'error', 'text' => 'Cannot recieve your comment.'));
die($output);
}else{
$output= json_encode(array('type'=>'message', 'text' => 'Hi '.$user_name .' Thank you for your review','status'=>1,'html'=>$insertedComment->markup()));
echo $output;
die($output);
}
}
?>

Add Contact form ajax with shortcode in wordpress

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.
}

Categories

Resources