Google reCAPTCHA is not working - php

I integrated Google Recaptcha to my website.
However, people can still fill the form and send mail without completing the captcha. (So they do not have to solve any puzzles they can just get straight through which is leaving me vunerable to bots of course)
So, I basically need PHP code that checks to see if the users has actually "Ticked" or "Completed" the Recaptcha. So then they can proceed to send mail.
Here is my PHP form code:
<!-- Start Contact Form -->
<div id="contact-form" class="contatct-form">
<div class="loader"></div>
<form method="post" action="mail.php">
<div class="row">
<div class="col-md-4">
<label for="name">Name<span class="required">*</span></label>
<span class="name-missing">Please enter your name</span>
<input id="name" name="name" type="text" value="" size="60">
</div>
<div class="col-md-4">
<label for="e-mail">Email<span class="required">*</span></label>
<span class="email-missing">Please enter a valid e-mail</span>
<input id="e-mail" name="email" type="text" value="" size="60">
</div>
<div class="col-md-4">
<label for="url">Website</label>
<input id="url" name="url" type="text" value="" size="80">
</div>
</div>
<div class="row">
<div class="col-md-12">
<label for="message">Add Your Comment</label>
<span class="message-missing">Say something!</span>
<textarea id="message" name="message" cols="45" rows="10"></textarea>
</br>
<!--Google reCAPTCHA-->
<?php
require_once('recaptchalib.php');
$publickey = "My Public Key"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<!--End Google reCAPTCHA-->
<input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" onclick="return valtest();">
</div>
</div>
</form>
Here is my mail.php code:
<?php
require_once('recaptchalib.php');
$privatekey = "My private key";
$resp = recaptcha_check_answer ($privatekey,
$_SERVER["REMOTE_ADDR"],
$_POST["recaptcha_challenge_field"],
$_POST["recaptcha_response_field"]);
if (!$resp->is_valid) {
// What happens when the CAPTCHA was entered incorrectly
die ("The reCAPTCHA wasn't entered correctly. Go back and try it again." .
"(reCAPTCHA said: " . $resp->error . ")");
} else {
$sendto = "myemail#domain.com";
$name=$_REQUEST['name'];
$usermail = $_REQUEST['email'];
$url=$_REQUEST['url'];
$content = nl2br($_POST['message']);
$subject = "Web Enquiry";
$headers = "From: " . strip_tags($name) . "\r\n";
$headers .= "Reply-To: ". strip_tags($usermail) . "\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html;charset=utf-8 \r\n";
$msg = "<html><body style='font-family:Arial,sans-serif;'>";
$msg .= "<h2 style='font-weight:bold;border-bottom:1px dotted #ccc;'>New Enquiry</h2>\r\n";
$msg .= "<p><strong>Sent by:</strong> ".$usermail."</p>\r\n";
$msg .= "<p><strong>Client Name:</strong> ".$name."</p>\r\n";
$msg .= "<p><strong>Message:</strong> ".$content."</p>\r\n";
$msg .= "<p><strong>Contact:</strong> ".$url."</p>\r\n";
$msg .= "</body></html>";
mail($sendto, $subject, $msg, $headers);
echo "<script>window.location =\"index.php\";</script>";
Here is recaptchalib.php Code:
<?php
/**
* This is a PHP library that handles calling reCAPTCHA.
* - Documentation and latest version
* https://developers.google.com/recaptcha/docs/php
* - Get a reCAPTCHA API Key
* https://www.google.com/recaptcha/admin/create
* - Discussion group
* http://groups.google.com/group/recaptcha
*
* #copyright Copyright (c) 2014, Google Inc.
* #link http://www.google.com/recaptcha
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
/**
* A ReCaptchaResponse is returned from checkAnswer().
*/
class ReCaptchaResponse
{
public $success;
public $errorCodes;
}
class ReCaptcha
{
private static $_signupUrl = "https://www.google.com/recaptcha/admin";
private static $_siteVerifyUrl =
"https://www.google.com/recaptcha/api/siteverify?";
private $_secret;
private static $_version = "php_1.0";
/**
* Constructor.
*
* #param string $secret shared secret between site and ReCAPTCHA server.
*/
function ReCaptcha($secret)
{
if ($secret == null || $secret == "") {
die("To use reCAPTCHA you must get an API key from <a href='"
. self::$_signupUrl . "'>" . self::$_signupUrl . "</a>");
}
$this->_secret=$secret;
}
/**
* Encodes the given data into a query string format.
*
* #param array $data array of string elements to be encoded.
*
* #return string - encoded request.
*/
private function _encodeQS($data)
{
$req = "";
foreach ($data as $key => $value) {
$req .= $key . '=' . urlencode(stripslashes($value)) . '&';
}
// Cut the last '&'
$req=substr($req, 0, strlen($req)-1);
return $req;
}
/**
* Submits an HTTP GET to a reCAPTCHA server.
*
* #param string $path url path to recaptcha server.
* #param array $data array of parameters to be sent.
*
* #return array response
*/
private function _submitHTTPGet($path, $data)
{
$req = $this->_encodeQS($data);
$response = file_get_contents($path . $req);
return $response;
}
/**
* Calls the reCAPTCHA siteverify API to verify whether the user passes
* CAPTCHA test.
*
* #param string $remoteIp IP address of end user.
* #param string $response response string from recaptcha verification.
*
* #return ReCaptchaResponse
*/
public function verifyResponse($remoteIp, $response)
{
// Discard empty solution submissions
if ($response == null || strlen($response) == 0) {
$recaptchaResponse = new ReCaptchaResponse();
$recaptchaResponse->success = false;
$recaptchaResponse->errorCodes = 'missing-input';
return $recaptchaResponse;
}
$getResponse = $this->_submitHttpGet(
self::$_siteVerifyUrl,
array (
'secret' => $this->_secret,
'remoteip' => $remoteIp,
'v' => self::$_version,
'response' => $response
)
);
$answers = json_decode($getResponse, true);
$recaptchaResponse = new ReCaptchaResponse();
if (trim($answers ['success']) == true) {
$recaptchaResponse->success = true;
} else {
$recaptchaResponse->success = false;
$recaptchaResponse->errorCodes = $answers [error-codes];
}
return $recaptchaResponse;
}
}
?>
When I replace
<!--Google reCAPTCHA-->
<?php
require_once('recaptchalib.php');
$publickey = "My Site Key"; // you got this from the signup page
echo recaptcha_get_html($publickey);
?>
<!--End Google reCAPTCHA-->
with
<!--Google reCAPTCHA-->
<div class="g-recaptcha" data-sitekey="My Site key"></div>
<!--End Google reCAPTCHA-->
it will display the widget but people can still fill the form and send mail without completing the captcha.

First of all you have to check if the recaptcha isset:
<?php
$errMsg = "";
$succMsg = "";
/**************************/
/* GOOGLE reCAPTCHA START */
/**************************/
require_once '../../reCAPTCHA/autoload.php';
$siteKey = 'sitekey';
$secret = 'secretkey';
/************************/
/* GOOGLE reCAPTCHA END */
/************************/
if ((isset($_POST['submit']) | !empty($_POST["submit"]))) {
if ((isset($_POST['g-recaptcha-response'])) && !empty($_POST["g-recaptcha-response"])) {
$recaptcha = new \ReCaptcha\ReCaptcha($secret);
$resp = $recaptcha->verify($_POST['g-recaptcha-response'], $_SERVER['REMOTE_ADDR']);
if ($resp->isSuccess()) {
$succMsg = "Success Message";
/**
* DO THE DB ENTRIES HERE
*/
}
} else {
$errMsg = "Error With Captcha";
}
}
?>
and you will need these files from google.
they are loaded here: require_once '../../reCAPTCHA/autoload.php';
your form page should look like:
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<div id="contact-form" class="contatct-form">
<div class="loader"></div>
<form method="post">
<div class="row">
<?php
if (isset($succMsg)) {
echo $succMsg;
} else {
echo "";
}
if (isset($errMsg)) {
echo $errMsg;
} else {
echo "";
}
?>
<div class="col-md-4">
<label for="name">Name<span class="required">*</span></label>
<span class="name-missing">Please enter your name</span>
<input id="name" name="name" type="text" value="" size="60">
</div>
<div class="col-md-4">
<label for="e-mail">Email<span class="required">*</span></label>
<span class="email-missing">Please enter a valid e-mail</span>
<input id="e-mail" name="email" type="text" value="" size="60">
</div>
<div class="col-md-4">
<label for="url">Website</label>
<input id="url" name="url" type="text" value="" size="80">
</div>
</div>
<div class="row">
<div class="col-md-12">
<label for="message">Add Your Comment</label>
<span class="message-missing">Say something!</span>
<textarea id="message" name="message" cols="45" rows="10"></textarea>
<br>
<div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>"></div>
<input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" onclick="return valtest();">
</div>
</div>
</form>
</div>

Here is my Contact page:
<!doctype html>
<!--[if IE 8 ]><html class="ie ie8" lang="en"> <![endif]-->
<!--[if (gte IE 9)|!(IE)]><html lang="en" class="no-js"> <![endif]-->
<html lang="en">
<head>
<!-- Basic -->
<title> </title>
<!-- Define Charset -->
<meta charset="utf-8">
<!-- Responsive etatag -->
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1">
<!-- Page Description-->
<meta name="Description"">
<meta name="keywords" ">
<META NAME="ROBOTS" CONTENT="INDEX, FOLLOW">
<meta name="author" content=" ">
<meta name="googlebot" content="noodp">
<link rel="canonical" href=" "/>
<!-- CSS Styles -->
<?php
?>
<!-- CSS Styles END-->
<script type="text/javascript">
function valtest()
{
var name=document.getElementById('name').value;
var email=document.getElementById('e-mail').value;
var url=document.getElementById('url').value;
var message=document.getElementById('message').value;
if((name==null||name==""))
{
alert("Please Enter Name");
return false;
}
if((email==null||email==""))
{
alert("Please Enter email");
return false;
}
else
{
alert('Thank you for Send The Details');
return true;
}
}
</script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
</head>
<body oncontextmenu="return false" ondragstart="return false" onselectstart="return false">
<!-- Container -->
<div id="container">
<!-- Start Header -->
<div class="hidden-header"></div>
<header class="clearfix">
<!-- Start Top Bar -->
<?php include_once(); ?>
<!-- End Top Bar -->
<!-- Start Header ( Logo & Naviagtion ) -->
<div class="navbar navbar-default navbar-top">
<div class="container">
<div class="navbar-header">
<!-- Stat Toggle Nav Link For Mobiles -->
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<i class="fa fa-bars"></i>
</button>
<!-- End Toggle Nav Link For Mobiles -->
<a class="navbar-brand" href="index.php"><img alt="" src="images/margo.png"></a>
</div>
<div class="navbar-collapse collapse">
<!-- Start Navigation List -->
<!-- End Navigation List -->
</div>
</div>
</div>
<!-- End Header ( Logo & Naviagtion ) -->
</header>
<!-- End Header -->
<!-- Start Page Banner -->
<!-- End Page Banner -->
<!-- Start Content -->
<div id="content">
<div class="container">
<div class="page-content">
<div class="col-md-8">
<!-- Classic Heading -->
<h4 class="classic-title"><span>Contact Us</span></h4>
<!-- Start Contact Form -->
<div id="contact-form" class="contatct-form">
<div class="loader"></div>
<form method="post">
<div class="row">
<?php
if (isset($succMsg)) {
echo $succMsg;
} else {
echo "";
}
if (isset($errMsg)) {
echo $errMsg;
} else {
echo "";
}
?>
<div class="col-md-4">
<label for="name">Name<span class="required">*</span></label>
<span class="name-missing">Please enter your name</span>
<input id="name" name="name" type="text" value="" size="60">
</div>
<div class="col-md-4">
<label for="e-mail">Email<span class="required">*</span></label>
<span class="email-missing">Please enter a valid e-mail</span>
<input id="e-mail" name="email" type="text" value="" size="60">
</div>
<div class="col-md-4">
<label for="url">Website</label>
<input id="url" name="url" type="text" value="" size="80">
</div>
</div>
<div class="row">
<div class="col-md-12">
<label for="message">Add Your Comment</label>
<span class="message-missing">Say something!</span>
<textarea id="message" name="message" cols="45" rows="10"></textarea>
<br>
<div class="g-recaptcha" data-sitekey="<?php echo $siteKey; ?>"></div>
<input type="submit" name="submit" class="button" id="submit_btn" value="Send Message" onclick="return valtest();">
</div>
</div>
</form>
</div>
<br/>
<!-- End Contact Form -->
</div>
<div class="col-md-4">
<!-- Classic Heading -->
<h4 class="classic-title"><span>Head Office</span></h4>
<!-- Divider -->
<div class="hr1" style="margin-bottom:10px;"></div>
<!-- Info - Icons List -->
<ul class="icons-list">
</ul>
<div class="hr1" style="margin-bottom:50px;"></div>
</div>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- End content -->
<!-- Start Map -->
<!-- End Map -->
<!-- Start Footer -->
<?php
include_once('footer.php');
?>
<!-- End Footer -->
</div>
<!-- End Container -->
<!-- Go To Top Link -->
<i class="fa fa-angle-up"></i>
<div id="loader">
<div class="spinner">
<div class="dot1"></div>
<div class="dot2"></div>
</div>
</div>
</body>
</html>

Related

Success message pop-up after from submit button clicked

I have created a web php web page with html and php code in, see below.
When I submit my form, it sends me an email and a success of fail message appears. So, everything works well.
My problem: I want to make the success or failure message pop-up or be a modal, but I don't know how. Where should I change the code and add the modal?
I have php at the top and then my HTML form. My form also has the google recaptcha verification tool. I just want to add a modal, but I do not know how and where to add the code.
<?php
error_reporting(0);
$msg="";
if (isset($_POST['submit'])) {
$to = "aleciadeklerk.119#gmail.com";
$subject = "Form Submission";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$check = $_POST['check'];
$msgBody = 'Name: '.$name.'Message: '.$message.'Subscribe: '.$check.'E-mail: '.$email;
$headers = 'From: '.$email;
$secretKey = "6LdXbq8UAAAAAM1B79Yz2IPgcTuIynBXeJMF2ZLY";
$responseKey = $_POST['g-recaptcha-response'];
$url = "https://www.google.com/recaptcha/api/siteverify?secret=$secretKey&response=$responseKey";
$response = file_get_contents($url);
$response = json_decode($response);
if ($response->success) {
if (mail($to, $subject, $msgBody, $headers)) {
$msg="Message sent successfully!";
}
else {
$msg="Failed to send the message. Please try again.";
}
}
else {
$msg="Verification Failed";
}
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.0/css/all.css' integrity='sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ' crossorigin='anonymous'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="style.css">
<title>Dibene Solutions</title>
<link rel = "icon" type = "image/png" href = "images/dibene_icon_dark.png">
</head>
<body>
<div>
<div class="container-fluid" id="contact">
<div class="container">
<div class="row">
<div class="col-md-12">
<a name="contact"><h2>Contact us</h2></a>
</div>
</div>
<div class="row">
<div class="col-md-6">
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post" class="p-2">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Enter name" required>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Enter e-mail" required>
</div>
<div class="form-group">
<textarea name="message" rows="4" class="form-control" placeholder="Write your message" required></textarea>
</div>
<div class="form-group">
<label><input type="checkbox" name="check" class="form-control" checked>Subscribe to monthly newsletter.</label>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LdXbq8UAAAAAAf7mQJqfbBbLWA36c1Qiin8EhBp"></div>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Send" class="btn btn-block">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
</body>
</html>
My aim is to click the submit button and then a modal pops up with a success or failure message.
if you want to use modal as an information messages, put your modal inside your html after the body tag and then call it with a javascript after the event success or failed.
javascript used for modal: $('#myModal').modal(options).
or if you want simplier way, you can use javascript alert() to inform the success or failed event
I made few changes to the code. I included bootstrap modal code and javascript function to call pop up. check this code.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0, shrink-to-fit=no">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">
<link rel='stylesheet' href='https://use.fontawesome.com/releases/v5.7.0/css/all.css' integrity='sha384-lZN37f5QGtY3VHgisS14W3ExzMWZxybE1SJSEsQp9S+oqd12jhcu+A56Ebc1zFSJ' crossorigin='anonymous'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="style.css">
<title>Dibene Solutions</title>
<link rel = "icon" type = "image/png" href = "images/dibene_icon_dark.png">
</head>
<body>
<div>
<div class="container-fluid" id="contact">
<div class="container">
<div class="row">
<div class="col-md-12">
<a name="contact"><h2>Contact us</h2></a>
</div>
</div>
<div class="row">
<div class="col-md-6">
<form action="<?= $_SERVER['PHP_SELF'] ?>" method="post" class="p-2">
<div class="form-group">
<input type="text" name="name" class="form-control" placeholder="Enter name" required>
</div>
<div class="form-group">
<input type="email" name="email" class="form-control" placeholder="Enter e-mail" required>
</div>
<div class="form-group">
<textarea name="message" rows="4" class="form-control" placeholder="Write your message" required></textarea>
</div>
<div class="form-group">
<label><input type="checkbox" name="check" class="form-control" checked>Subscribe to monthly newsletter.</label>
</div>
<div class="form-group">
<div class="g-recaptcha" data-sitekey="6LdXbq8UAAAAAAf7mQJqfbBbLWA36c1Qiin8EhBp"></div>
</div>
<div class="form-group">
<input type="submit" name="submit" value="Send" class="btn btn-block">
</div>
</form>
</div>
</div>
</div>
</div>
</div>
<!-- Modal -->
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<!-- Modal content-->
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal">×</button>
<h4 class="modal-title">Modal Header</h4>
</div>
<div class="modal-body">
<p id="txtMsg"></p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>
<script>
function popup(msg){
document.getElementById("txtMsg").innerHTML = msg;
$("#myModal").modal();
}
</script>
<?php
error_reporting(0);
$msg="";
if (isset($_POST['submit'])) {
$to = "aleciadeklerk.119#gmail.com";
$subject = "Form Submission";
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$check = $_POST['check'];
$msgBody = 'Name: ' . $name . 'Message: ' . $message . 'Subscribe: ' . $check . 'E-mail: ' . $email;
$headers = 'From: ' . $email;
$secretKey = "6LdXbq8UAAAAAM1B79Yz2IPgcTuIynBXeJMF2ZLY";
$responseKey = $_POST['g-recaptcha-response'];
$url = "https://www.google.com/recaptcha/api/siteverify?
secret=$secretKey&response=$responseKey";
$response = file_get_contents($url);
$response = json_decode($response);
if ($response->success) {
if (mail($to, $subject, $msgBody, $headers)) {
$msg = "Message sent successfully!";
echo '<script type="text/javascript">',
'popup("'.$msg.'");',
'</script>';
} else {
$msg = "Failed to send the message. Please try again.";
echo '<script type="text/javascript">',
'popup("'.$msg.'");',
'</script>';
}
}
else {
$msg="Verification Failed";
echo '<script type="text/javascript">',
'popup("'.$msg.'");',
'</script>';
}
}
?>
</body>
</html>
You could create a hidden field like:
<input type="hidden" name="msg" id="msg" value="<?php echo $msg ?>">
Then using JQuery on document ready:
$(document).ready(function() {
if($('#msg').val() != "")
{
alert($('#msg').val()); // or replace with a JQuery modal
}
});

Getting errors after changing HTML file to PHP

I changed my html file to php in order to show php errors in form , I wasn't sure if I suppose to add or reduce php/html tags. I left as it is. When I open my form in browser its showing me the following errors. :
Notice: Undefined variable: name_error in C:\xampp\htdocs\BootstrapLandinPage\index.php on line 165
Notice: Undefined variable: lastname_error in C:\xampp\htdocs\BootstrapLandinPage\index.php on line 170
Notice: Undefined variable: phone_error in C:\xampp\htdocs\BootstrapLandinPage\index.php on line 175
and etc.
Basically every input showing an error.
My index.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">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<title>Bootstrap 101 Template</title>
<!-- Bootstrap -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<link rel="stylesheet" href="font-awesome-4.7.0/css/font-awesome.min.css">
<link rel="stylesheet" href="css/style.css">
<link rel="stylesheet" href="css/animate.min.css">
<!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
<!-- WARNING: Respond.js doesn't work if you view the page via file:// -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.3/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!--NAVIGATION-->
<div id="myNavbar" class="navbar navbar-default navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header navbar-right">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
Hello Dolly
</div>
<div class="navbar-collapse collapse" id="mainpanel">
<ul class="nav navbar-nav ">
<li>dolly</li>
<li>holly</li>
<li>holly</li>
<li>holly</li>
<li>holly</li>
<li>holly</li>
</ul>
</div>
</div>
</div>
<!--- Header ---->
<section class="parallax">
<div class="parallax-inner">
<div id="header" class="header">
<div class="container">
<div class="row">
<div class="col-md-6 wow bounceInLeft navbar-right">
<h1 class="text-right" id="main-title">dolly </h1>
<h2 class="text-right" id="changed-title">dolly</h2><br><br>
<!--- <button class="btn btn-lg btn-primary navbar-right">dolly</button> ---->
</div>
</div>
</div>
</div>
</div>
</section>
<!-- [CONTACT] -->
<section class="inspiration" id="three">
<div class="overlay">
<div class="container">
<div class="row">
<article class="col-md-12 text-center">
<div class="intermediate-container">
<div class="heading">
<h2>יש לכם שאלה? צרו איתי קשר</h2>
</div>
<div class="row">
<div class="col-md-3 col-sm-3"></div>
<div class="col-md-6 center-block col-sm-6 ">
<form id="mc-form" action ="send.php" method="POST">
<div class="form-group col-xs-12 ">
<label for="name" hidden >שם פרטי</label>
<input type="text" name="name" id="name" class="cv form-control" value="<?= $name ?>" placeholder="שם פרטי" >
<span class="error"><?= $name_error ?></span>
</div>
<div class="form-group col-xs-12 ">
<label for="lastName" hidden>שם משפחה</label>
<input type="text" name="lastName" id="lastName" class="cv form-control" value="<?= $lastName ?>" placeholder="שם משפחה" >
<span class="error"><?= $lastname_error ?></span>
</div>
<div class="form-group col-xs-12 ">
<label for="phone" hidden>טלפון</label>
<input type="text" name="phone" id="phone" class="cv form-control" value="<?= $phone ?>" placeholder="טלפון" >
<span class="error"><?= $phone_error ?></span>
</div>
<div class="form-group col-xs-12 ">
<label for="email" hidden>דואר אלקטרוני</label>
<input type="email" name="email" id="email" class="cv form-control" value="<?= $email ?>" placeholder="דואר אלקטרוני" >
<span class="error"><?= $email_error ?></span>
</div>
<div class="form-group col-xs-12 ">
<label for="subject" hidden>נושא</label>
<input type="text" name="subject" id="subject" class="cv form-control" value="<?= $subject?>" placeholder="נושא" >
</div>
<div class="form-group col-xs-12 ">
<label for="message" hidden>הודעה</label>
<textarea name="message" id="message" class="cv form-control message" placeholder="השאירו את הודעתכם פה" rows="4" cols="50"></textarea>
</div>
<input type="submit" id="submit-button" class="btn btn-custom-outline " value="שלח" >
<br>
<div class="success"><?= $success ?></div>
<!--<span class="error"></span> -->
</form>
</div>
</div>
</div>
</article>
</div>
</div>
</div>
</section>
<!-- [/CONTACT] -->
<!-- Optional JavaScript -->
<!-- jQuery first, then Popper.js, then Bootstrap JS -->
<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" ></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.3/umd/popper.min.js" ></script>
<script src="js/bootstrap.min.js" ></script>
<!-- [ SLIDER SCRIPT ] -->
<script type="text/javascript" src="js/SmoothScroll.js"></script>
<script src="js/script.js" ></script>
</body>
</html>
send.php:
// define variables and set to empty values
$name_error = $lastname_error = $email_error = $phone_error = "";
$name = $lastName = $email = $phone = $message = $subject = $success = "";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["name"])) {
$name_error = "Name is required";
} else {
$name = test_input($_POST["name"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Zא-ת ]*$/",$name)) {
$name_error = "Only letters and white space allowed";
}
}
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if (empty($_POST["lastName"])) {
$lastname_error = "Name is required";
} else {
$lastname = test_input($_POST["lastName"]);
// check if name only contains letters and whitespace
if (!preg_match("/^[a-zA-Zא- ]*$/",$lastName)) {
$lastname_error = "Only letters and white space allowed";
}
}
if (empty($_POST["email"])) {
$email_error = "Email is required";
} else {
$email = test_input($_POST["email"]);
// check if e-mail address is well-formed
if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
$email_error = "Invalid email format";
}
}
if (empty($_POST["phone"])) {
$phone_error = "Phone is required";
} else {
$phone = test_input($_POST["phone"]);
// check if e-mail address is well-formed
if (!preg_match("/^(\d[\s-]?)?[\(\[\s-]{0,2}?\d{3}[\)\]\s-]{0,2}?\d{3}[\s-]?\d{4}$/i",$phone)) {
$phone_error = "Invalid phone number";
}
}
if (empty($_POST["subject"])) {
$subject = "";
} else {
$subject = test_input($_POST["subject"]);
}
if (empty($_POST["message"])) {
$message = "";
} else {
$message = test_input($_POST["message"]);
}
if ($name_error == '' and $email_error == '' and $phone_error == '' and $lastname_error == '' ){
$message_body = '';
unset($_POST['submit']);
foreach ($_POST as $key => $value){
$message_body .= "$key: $value\n";
}
$to = 'ilonasemyweb#gmail.com';
$subjectm = 'Contact Form Submit';
if (mail($to, $subjectm, $message)){
$success = "Message sent, thank you for contacting us!";
$name = $lastName = $email = $phone = $message = $subject = '';
}
}
}
function test_input($data) {
$data = trim($data);
$data = stripslashes($data);
$data = htmlspecialchars($data);
return $data;
}
What you need to do is the following:
In index.php: Check if those variables are defined. If not, then there are no errors, so display nothing of that sorts, just as it would be on first entry.
In send.php: Properly send back index.php on error. This can be done using the require_once method.
So after checking all sent data for errors write:
if(/* there were errors */)
require_once("path/to/index.php");
This will then get all the text from index.php, "put it in that place in index.php" and continue interpreting. Using this, all variables defined in send.php are now also defined in index.php (and retain their values, of course). Note however that the new url will now end with send.php, unless you trick around that a bit.

Form not submitting when I load it with ng-view

I have configured the angularjs file so that the view is loaded when i press on the 'add item' button in the navigation bar, however when I try submitting the form nothing happens. But if I load the php file separately it works without any problems and adds the data to my json file.
MY HTML
<head>
<title></title>
<link href="almstyle.css" type="text/css" rel="stylesheet">
<link href="Framework/css/mycss.css" type="text/css" rel="stylesheet">
<link href="Framework/css/bootstrap.min.css" type="text/css" rel="stylesheet">
<script src="Framework/js/jquery-3.1.1.min.js"></script>
<script src="Framework/js/bootstrap.min.js"></script>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
</head>
<body>
<div class="container">
<!-- Start of header -->
<div class="row">
<div class="col-xs-12 col-sm-12 col-md-12 col-lg-12">
<h4 id="banner">LOGO</h4>
</div>
</div>
<!-- End of header -->
<nav class="navbar navbar-default">
<div class="container-fluid">
<div class="navbar-header navbar-left">
<button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
</div>
<div class="collapse navbar-collapse" id="bs-example-navbar-collapse-1">
<ul class="nav navbar-nav">
<li class="active">Home <span class="sr-only">(current)</span></li>
<li>Hair</li>
<li>Shop</li>
<li>News</li>
<li>Add Item</li>
<li class="dropdown">
LifeStyle <span class="caret"></span>
<ul class="dropdown-menu">
<li>Food</li>
<li>Passion</li>
<li>Travel</li>
</ul>
</li>
</ul>
</div>
</div>
</nav>
<div data-ng-view></div>
</div>
<script type="text/javascript" src="https://code.angularjs.org/1.6.5/angular.js"></script>
<script type="text/javascript" src="../node_modules/angular-route/angular-route.js"></script>
<script src="app.js"></script>
<script src="home/home.js"></script>
<script src="addItem/addItem.js"></script>
</body>
</html>
My Php Template
<?php
$message = '';
$error = '';
if(isset($_POST["submit"]))
{
if(empty($_POST["item"]))
{
$error = "<label class='text-danger'>Enter Item Name</label>";
}
else if(empty($_POST["id"]))
{
$error = "<label class='text-danger'>Enter Item Id</label>";
}
else if(empty($_POST["size"]))
{
$error = "<label class='text-danger'>Enter a size for your item</label>";
}
else if(empty($_POST["price"]))
{
$error = "<label class='text-danger'>Enter a suitable price for the item</label>";
}
else
{
if(file_exists('items.json'))
{
$current_data = file_get_contents('items.json');
$array_data = json_decode($current_data, true);
$extra = array(
'item' => $_POST['item'],
'id' => $_POST["id"],
'selected' => $_POST["selected"],
'prices' => [[
'size' => $_POST["size"],
'price' => $_POST["price"]
]]
);
$array_data[] = $extra;
$final_data = json_encode($array_data);
if(file_put_contents('items.json', $final_data))
{
$message = "<label class='text-success'>The Item has been added successfully</p>";
}
}
else
{
$error = 'JSON File does not exist';
}
}
}
?>
<!DOCTYPE html>
<html>
<head>
<title>Add items</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/css/bootstrap.min.css" />
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.6/js/bootstrap.min.js"></script>
</head>
<body>
<br />
<div class="container" style="width:500px;">
<h3 align="">Add items</h3><br />
<form method="post">
<?php
if(isset($error))
{
echo $error;
}
?>
<br />
<label>Item Name</label>
<input type="text" name="item" class="form-control" /><br />
<label>Item Id</label>
<input type="text" name="id" class="form-control" />
<input type="hidden" name="selected" value="0" class="form-control" hidden="hidden"/><br />
<div class="panel panel-default">
<div class="panel panel-heading">
Prices
</div>
<div class="panel panel-body">
<label>Size</label>
<input type="text" name="size" class="form-control" />
<label>Price</label>
<input type="number" name="price" class="form-control" />
</div>
<br />
</div>
<input type="submit" name="submit" value="Add Item" class="btn btn-info" /><br />
<?php
if(isset($message))
{
echo $message;
}
?>
</form>
</div>
<br />
</body>
This is what it should look like after submitting
few mistakes here ,
I don't see a form with the action attribute set as path to php resource.
For a form to submit, you should have a button of type submit. Some thing like this.
<html>
<body>
<form action="welcome.php" method="post">
Name: <input type="text" name="name"><br>
E-mail: <input type="text" name="email"><br>
<input type="submit">
</form>
</body>
</html>
And your PHP file can be
<html>
<body>
Welcome <?php echo $_POST["name"]; ?><br>
Your email address is: <?php echo $_POST["email"]; ?>
</body>
</html>
I hope this helps you to resolve this
For a form to work "the angular way", you need a couple to specify a couple of extra bits.
You'll firstly need the name the ng-app after the opening html tag to indicate that the that block of code will be 'watched' by an angular module (which you will specify also in the code).
You'll also need to add an ng-controller tag to the form which you will name and then refer to in your javascript
In the angular form , add an ng-click to send it to submit the form if the form validates successfully: ng-click=”formsubmit(userForm.$valid)”
Here is some sample code:
<!DOCTYPE html>
<html ng-app="formExample">
<head>
<title>simple form with AngualrJS</title>
<link rel="stylesheet" href="css/bootstrap.min.css" type="text/css" />
<script src="js/angular.js" ></script>
<script src="js/formjs.js"></script>
</head>
<body>
<div ng-controller="formCtrl">
<form name="userForm" class="well form-search" >
<input type="text" ng-model="name" class="input-medium search-query" placeholder="Name" required >
<input type="email" ng-model="email" class="input-medium search-query" placeholder="Email" required >
<input type="text" ng-model="message" class="input-medium search-query" placeholder="Message" required >
<button type="submit" class="btn" ng-click="formsubmit(userForm.$valid)" ng-disabled="userForm.$invalid">Submit </button>
</form>
<pre ng-model="result">
{{result}}
</pre>
</div>
</body>
</html>
JS:
<pre class="lang:default decode:true " title="formjs.js" >
/**
* #filesource : formjs.js
* #author : Shabeeb <mail#shabeebk.com>
* #abstract : controller fo HTML page
* #package sample file
* #copyright (c) 2014, Shabeeb
* shabeebk.com/blog
*
* */
var app = angular.module('formExample', []);
app.controller("formCtrl", ['$scope', '$http', function($scope, $http) {
$scope.url = 'submit.php';
$scope.formsubmit = function(isValid) {
if (isValid) {
$http.post($scope.url, {"name": $scope.name, "email": $scope.email, "message": $scope.message}).
success(function(data, status) {
console.log(data);
$scope.status = status;
$scope.data = data;
$scope.result = data;
})
}else{
alert('Form is not valid');
}
}
}]);</pre>
submit:
<?php
/**
* #filesource : submit.php
* #author : Shabeeb <mail#shabeeb.com>
* #abstract : simple submission php form
* #package sample file
* #copyright (c) 2014, Shabeeb
*
*
* */
$post_date = file_get_contents("php://input");
$data = json_decode($post_date);
//saving to database
//save query
//now i am just printing the values
echo "Name : ".$data->name."n";
echo "Email : ".$data->email."n";
echo "Message : ".$data->message."n";
?>

PHP Form not working at root level - JS Validation issue, maybe

I am totally stumped by this one.
My PHP form works just fine when within a folder on my server
see it here
http://getnice.co.uk/formTest/
but the same code at root level does not work.
Yes everything is pointing to the right places, so it is not that.
http://getnice.co.uk/form.html
Below is the code..
However I think it is a server issue? correct me if I am wrong.
<!-- Contact start -->
<section id="contact" class="pfblock pfblock-gray">
<div class="container">
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<div class="pfblock-header">
<h2 class="pfblock-title">Contact us</h2>
<div class="pfblock-line"></div>
<div class="pfblock-subtitle">
Tell us about your business and what your needs are:
</div>
</div>
</div>
</div><!-- .row -->
<div class="row">
<div class="col-sm-8 col-sm-offset-2">
<form id="contact-form" role="form" method="post" action="assets/php/contact.php">
<!-- <div class="contact.php"> -->
<div class="form-group wow fadeInUp">
<label class="sr-only" for="c_name">Name</label>
<input type="text" id="c_name" class="form-control" name="c_name" placeholder="Name">
</div>
<div class="form-group wow fadeInUp" data-wow-delay=".1s">
<label class="sr-only" for="c_email">Email</label>
<input type="email" id="c_email" class="form-control" name="c_email" placeholder="E-mail">
</div>
<div class="form-group wow fadeInUp" data-wow-delay=".1s">
<label class="sr-only" for="c_design">Design you like</label>
<select id="c_design" class="form-control" name="c_design" placeholder="Name of the Design you like">
<option value="" disabled selected>Select the design you like</option>
<option value="Office">Office Based Business</option>
<option value="Cafe or shop">Cafe or Shop</option>
<option value="Portfolio">Portfolio style</option>
<option value="Other small">Other Small Business</option>
<option value="Music">Musician Band style</option>
<option value="Agency">Agency style</option>
<option value="custom">Custom design required</option>
</select>
</div>
<div class="form-group wow fadeInUp" data-wow-delay=".2s">
<textarea class="form-control" id="c_message" name="c_message" rows="7" placeholder="Message"></textarea>
</div>
<button type="submit" class="btn btn-lg btn-block wow fadeInUp" data-wow-delay=".3s">Send Message</button>
</div>
<div class="ajax-response"></div>
</form>
</div><!-- .row -->
</div><!-- .container -->
</section>
<!-- Contact end -->
<!-- Javascript files -->
<script src="assets/js/jquery-1.11.1.min.js"></script>
<script src="assets/bootstrap/js/bootstrap.min.js"></script>
<script src="assets/js/jquery.parallax-1.1.3.js"></script>
<script src="assets/js/imagesloaded.pkgd.js"></script>
<script src="assets/js/jquery.sticky.js"></script>
<script src="assets/js/smoothscroll.js"></script>
<script src="assets/js/wow.min.js"></script>
<script src="assets/js/waypoints.min.js"></script>
<script src="assets/js/jquery.cbpQTRotator.js"></script>
<script src="assets/js/custom.js"></script>
PHP
<?php
if(isset($_POST['c_message'])){
$name = $_POST['c_name'];
$email = $_POST['c_email'];
$varDropdown = $_POST['c_design'];
$message = $_POST['c_message'];
$to = 'me#gmail.com';
$subject = 'Get Nice Contact Form';
$mailcontent2="<html>
<head>
</head>
<body>
<table width='800' border='0' cellspacing='2' cellpadding='0'>
<tr>
<td align='left'>
<p>Hi,</p>
<strong style='color:#C59800'>New request has been sent with the below details.</strong><br /><br />
<strong>Name: </strong>".stripslashes($_REQUEST['c_name'])."<br />
<strong>Email: </strong>".stripslashes($_REQUEST['c_email'])."<br />
<strong>Design: </strong>".stripslashes($_REQUEST['c_design'])."<br />
<strong>Message: </strong>".nl2br(stripslashes($_REQUEST['c_message']))."<br /><br />
<p>Thanks</p>
</td>
</tr>
</table>
</body>
</html>
";
//echo $mailcontent2;
$headers2 = "MIME-Version: 1.0" . "\r\n";
$headers2 .= "Content-type: text/html; charset=iso-8859-1" . "\r\n";
$headers2 .= "From: ".$email." <".$email.">" . "\r\n";
$status = mail($to,$subject,$mailcontent2,$headers2);
if($status == TRUE){
$res['sendstatus'] = 'done';
//Edit your message here
$res['message'] = 'Thank you your mail has been sent';
}
else{
$res['message'] = 'Failed to send mail. Please email me at hello#getnice.co.uk';
}
echo json_encode($res);
}
JS
/* ---------------------------------------------- /*
* E-mail validation
/* ---------------------------------------------- */
function isValidEmailAddress(emailAddress) {
var pattern = new RegExp(/^((([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+(\.([a-z]|\d|[!#\$%&'\*\+\-\/=\?\^_`{\|}~]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])+)*)|((\x22)((((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(([\x01-\x08\x0b\x0c\x0e-\x1f\x7f]|\x21|[\x23-\x5b]|[\x5d-\x7e]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(\\([\x01-\x09\x0b\x0c\x0d-\x7f]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF]))))*(((\x20|\x09)*(\x0d\x0a))?(\x20|\x09)+)?(\x22)))#((([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|\d|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.)+(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])|(([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])([a-z]|\d|-|\.|_|~|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])*([a-z]|[\u00A0-\uD7FF\uF900-\uFDCF\uFDF0-\uFFEF])))\.?$/i);
return pattern.test(emailAddress);
};
/* ---------------------------------------------- /*
* Contact form ajax
/* ---------------------------------------------- */
$('#contact-form').submit(function(e) {
e.preventDefault();
var c_name = $('#c_name').val();
var c_email = $('#c_email').val();
var c_message = $('#c_message ').val();
var c_design = $('#c_design ').val();
var response = $('#contact-form .ajax-response');
var formData = {
'c_name' : c_name,
'c_email' : c_email,
'c_design' : c_design,
'c_message' : c_message
};
if (( c_name== '' || c_email == '' || c_message == '') || (!isValidEmailAddress(c_email) )) {
response.fadeIn(500);
response.html('<i class="fa fa-warning"></i> Please fix the errors and try again.');
}
else {
$.ajax({
type : 'POST', // define the type of HTTP verb we want to use (POST for our form)
url : 'assets/php/contact.php', // the url where we want to POST
data : formData, // our data object
dataType : 'json', // what type of data do we expect back from the server
encode : true,
success : function(res){
var ret = $.parseJSON(JSON.stringify(res));
response.html(ret.message).fadeIn(500);
}
});
}
return false;
});
});
})(jQuery);
move the e.preventDefault(); towards the end in custom.js

How to display username as a value in PHP

I want to know how to display a user's username inside a textbox. I'm doing this because when they edit their settings and update them, it updates their email etc to blank fields in the database:
Here's the code i'd like to change
<input type="text" name="name" class="form-control" id="name" class="required" value="<? echo $row_settings['full_name']; ?>" />
I'd like to make the `value = $row_settings['full_name'];'
How can i do this?
ALL CODE:
<?php
/********************** MYSETTINGS.PHP**************************
This updates user settings and password
************************************************************/
include 'dbc.php';
page_protect();
$err = array();
$msg = array();
if($_POST['doUpdate'] == 'Update')
{
$rs_pwd = mysql_query("select pwd from users where id='$_SESSION[user_id]'");
list($old) = mysql_fetch_row($rs_pwd);
$old_salt = substr($old,0,9);
//check for old password in md5 format
if($old === PwdHash($_POST['pwd_old'],$old_salt))
{
$newsha1 = PwdHash($_POST['pwd_new']);
mysql_query("update users set pwd='$newsha1' where id='$_SESSION[user_id]'");
$msg[] = "Your new password is updated";
//header("Location: mysettings.php?msg=Your new password is updated");
} else
{
$err[] = "Your old password is invalid";
//header("Location: mysettings.php?msg=Your old password is invalid");
}
}
if($_POST['doSave'] == 'Save')
{
// Filter POST data for harmful code (sanitize)
foreach($_POST as $key => $value) {
$data[$key] = filter($value);
}
mysql_query("UPDATE users SET
`full_name` = '$data[name]',
`address` = '$data[address]',
`tel` = '$data[tel]',
`user_email` = '$data[user_email]',
`user_name` = '$data[user]',
`fax` = '$data[fax]',
`country` = '$data[country]',
`website` = '$data[web]'
WHERE id='$_SESSION[user_id]'
") or die(mysql_error());
//header("Location: mysettings.php?msg=Profile Sucessfully saved");
$msg[] = "Profile Sucessfully saved";
}
$rs_settings = mysql_query("select * from users where id='$_SESSION[user_id]'");
?>
<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">
<meta name="description" content="">
<meta name="author" content="">
<link rel="shortcut icon" href="../../assets/ico/favicon.ico">
<script language="JavaScript" type="text/javascript" src="js/jquery-1.3.2.min.js"></script>
<script language="JavaScript" type="text/javascript" src="js/jquery.validate.js"></script>
<script>
$(document).ready(function(){
$("#myform").validate();
$("#pform").validate();
});
</script>
<title>The Infibox - Edit Profile</title>
<!-- Bootstrap core CSS -->
<link href="css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="css/indexSettings.css" rel="stylesheet">
<!-- HTML5 shim and Respond.js IE8 support of HTML5 elements and media queries -->
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/libs/html5shiv/3.7.0/html5shiv.js"></script>
<script src="https://oss.maxcdn.com/libs/respond.js/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<div class="navbar navbar-inverse navbar-fixed-top" role="navigation">
<div class="container">
<div class="navbar-header">
<button type="button" class="navbar-toggle" data-toggle="collapse" data-target=".navbar-collapse">
<span class="sr-only">Toggle navigation</span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
<span class="icon-bar"></span>
</button>
<?php if (isset($_SESSION['user_id'])) {?>
<a class="navbar-brand" href="#">Infibox</a>
<a class="navbar-brand">|</a>
<a class="navbar-brand" href="/recruitment">My Account</a>
<a class="navbar-brand" href="#">Settings</a>
<a class="navbar-brand" href="#">Logout</a>
<?php }
?>
<?php
if (checkAdmin()) {
/*******************************END**************************/
?>
<a class="navbar-brand" href="admin.php">Admin CP </a>
<?php } ?>
</div>
<div class="navbar-collapse collapse">
<form class="navbar-form navbar-right" role="form">
<div class="form-group">
<input type="text" placeholder="Email" class="form-control">
</div>
<div class="form-group">
<input type="password" placeholder="Password" class="form-control">
</div>
<button type="submit" class="btn btn-success">Sign in</button>
</form>
</div><!--/.navbar-collapse -->
</div>
</div>
<!-- Main jumbotron for a primary marketing message or call to action -->
<p>
<?php
if(!empty($err)) {
echo "<div class=\"msg\">";
foreach ($err as $e) {
echo "* Error - $e <br>";
}
echo "</div>";
}
if(!empty($msg)) {
echo "<div class=\"msg\">" . $msg[0] . "</div>";
}
?>
</p>
<!-- Show their details inside the correct box. E.g. their first name they registered with will be shown inside the "First Name" box. Does not occur with passwords. -->
<center>
<div class="wrapper">
<h2 class="title">Edit Profile</h2>
<?php while ($row_settings = mysql_fetch_array($rs_settings)) ?>
<form action="mysettings1.php" method="post" name="myform" id="myform">
<div class="input-group" id="fname">
<span class="input-group-addon">Name</span>
<input type="text" name="name" class="form-control" id="name" class="required" value="<? echo $row_settings['full_name']; ?>" />
</div>
<div class="input-group">
<span class="input-group-addon">Customer ID</span>
<input type="text" name="user" class="form-control" maxlength="6" id="web2" value="<? echo $row_settings['user_name']; ?>">
</div>
<div class="input-group">
<span class="input-group-addon">Email</span>
<input type="text" class="form-control" name="user_email" id="web3" value="<? echo $row_settings['user_email']; ?>">
</div>
<div class="input-group">
<span class="input-group-addon">Add Paypal Email</span>
<input type="text" class="form-control" name="tel" id="tel" class="required" value="<? echo $row_settings['tel']; ?>">
</div>
<div class="btn-group">
<input name="doSave" type="submit" id="doSave" value="Save" class="btn btn-success">
</div>
<hr class="hr" />
<!-- When Changing Password Old Password Must Be Entered + Correct-->
<h2 class="title2">Change Password</h2>
<div class="input-group">
<span class="input-group-addon">Old Password</span>
<input type="password" class="form-control" name="pwd_old" class="required password" id="pwd_old" >
</div>
<div class="input-group">
<span class="input-group-addon">New Password</span>
<input type="password" class="form-control" name="pwd_new" class="required password" id="pwd_new" >
</div>
<div class="btn-group">
<input name="doUpdate" type="submit" id="doUpdate" value="Update" class="btn btn-success">
</div>
</div>
</center>
</form>
<!-- ##################################################################################### -->
<!-- ##################################################################################### -->
</div>
</center>
<!-- Bootstrap core JavaScript
================================================== -->
<!-- Placed at the end of the document so the pages load faster -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<script src="js/bootstrap.min.js"></script>
</body>
</html>
You do not need a while loop:
Change
<?php while ($row_settings = mysql_fetch_array($rs_settings)) ?>
with
<?php $row_settings = mysql_fetch_array($rs_settings); ?>

Categories