I am doing email validation for admin registration using JavaScript and save the data to database using PHP. Supposedly, the registration is done only if the email is valid. But when the email evaluates to invalid, the PHP code still run. How do I do it so that when the email is invalid, the PHP won't run.
Below is the PHP code to save data to database:
<?php
include('connection.php');
if(isset($_POST['saveBtn']))
{
$name = $_POST['name'];
$ic = $_POST['ic'];
$email = $_POST['email'];
$pass = $_POST['pass'];
$dob = $_POST['dob'];
$contact = $_POST['contact'];
$gender = $_POST['gender'];
$des = $_POST['des'];
$address = $_POST['address'];
// Check if data exist
$check = "SELECT * FROM admin WHERE admEmail = '".$email."' AND admPassword = '".$pass."'";
if(mysqli_num_rows(mysqli_query($connect,$check)) > 0)
{
?>
<script>
alert('This email and password already registered!');
</script>
<?php
}
else
{
$insert = "INSERT INTO admin (admName, admIC, admEmail, admPassword, admDOB, admContact, admGender, admDesignation, admAddress, admDateJoin) VALUES ('".$name."', '".$ic."', '".$email."', '".$pass."', '".$dob."', '".$contact."', '".$gender."', '".$des."', '".$address."', NOW())";
if(mysqli_query($connect, $insert))
{
?>
<script>
alert('Insertion Successful!');
window.close();
window.opener.location.reload();
</script>
<?php
}
else
{
?>
<script>
alert('Insertion Failed. Try Again!');
</script>
<?php
}
}
}
?>
Below is the JS:
function validateEmail() {
var email = document.addAdminForm.email.value;
var validRegex = /^[a-zA-Z0-9.!#$%&'*+/=?^_`{|}~-]+#[a-zA-Z0-9-]+(?:\.[a-zA-Z0-9-]+)*$/;
if (email.match(validRegex))
{
alert("Valid email address!");
return true;
}
else
{
document.getElementById("email_error").innerHTML = "Invalid email";
document.addAdminForm.email.focus();
return false;
}
}
Below is the partial HTML form:
<form class="w-100" name="addAdminForm" method="POST" onsubmit="validateEmail(this)" action="add_admin.php">
<div class="row">
<div class="col form-group">
<!-- <label for="email">Email</label> -->
<input type="text" class="form-control" name="email" placeholder="Email" required>
<span class="error email_error" id="email_error"></span>
</div>
<div class="float-right">
<input type="submit" class="btn button_primary" value="Save" name="saveBtn">
</div>
</form>
I expect PHP run when validation is true
add this:
onsubmit="return validateEmail(this)"
change your JS code to:
var validRegex = /^([a-zA-Z0-9_-])+#([a-zA-Z0-9_-])+((\.[a-zA-Z0-9_-]{2,3}){1,2})$/;
Related
Newbie here. I have a modal where staff can transfer fund to a client. Before transferring fund, the staff must input his/her password before proceeding to transaction. My goal is to have a WORKING FUNCTION about the password validation. I made a slightly working function. I have provided a video below for better explanation.
https://streamable.com/z4vgtv //Correct or wrong password, the result is the same. "Password not match"
Controller:
public function form_validation($userID)
{
$this->load->library('form_validation');
$this->form_validation->set_rules("amount","Amount", 'required|numeric');
$password = $this->input->post('password');
$exists = $this->networks->filename_exists($password);
$count = count($exists);
if($count >=1)
{
if($this->form_validation->run())
{
$ref= $this->session->userdata('uid') + time ();
$id = $this->input->post('userID');
$pData = array(
'userID' => $id,
'transactionSource' => 'FR',
'refNumber' => 'FI-0000' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"in",
);
$this->networks->fundin($pData);
$ref= $this->session->userdata('userID') + time ();
$data1 = array(
'userID' => $this->session->userdata('uid'),
"transactionSource" => 'FR',
"refNumber" => 'FO' . $ref,
"amount" =>$this->input->post("amount"),
"transType" =>"out",
);
?>
<script> alert("password match");</script>
<?php
$this->networks->insert_data($data1);
redirect(base_url() . "network/agents");
}
else
{
$this->index();
}
}
else
{
?>
<script> alert("Password not Match");</script>
<?php
}
}
Model:
function filename_exists($password)
{
$this->db->select('*');
$this->db->from('users');
$this->db->where('password', $password);
$query = $this->db->get();
$result = $query->result_array();
return $query->result();
}
Views:
<form id="doBetting" method="post" action="<?php echo base_url('network/form_validation');?>/<?php echo $rows->userID; ?>">
<div class="input-group input-group-sm" style="width: 100%" >
<input type="hidden" id="usertransferid" name="userID">
<div class="col-lg-12" >
<input type="number" placeholder="Enter Amount" name="amount" class="form-control" id="box" required>
<br>
<input type="password" placeholder="Enter Password" name="password" class="form-control" id="cpass" required onblur="check_if_exists();">
<br>
<!-- buttons -->
<input type="submit" class="btn btn-success text-bold" name="save" id="insert" value="Transfer">
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
Ajax:
<script>
<script>
function check_if_exists() {
var password = $("#cpass").val();
$.ajax(
{
type:"post",
url: "<?php echo site_url(); ?>network/form_validation",
data:{password:password},
success:function(response)
{
// remove alert();
}
});
}
check_if_exists();
</script>
User always saved password on database with encoded form,but in your case,firstly you need to encode your password(format md5 or which format you are using to encode) and then check with your user password.
public function form_validation($userID)
{
$this->load->library('form_validation');
$this->form_validation->set_rules("amount","Amount", 'required|numeric');
$password = md5(trim($this->input->post('password')));
$exists = $this->networks->filename_exists($password);
.........
}
i want to excecute php script with ajax or javascript from html form. I need receive result from php page to html page.
My changepsw.php
<?php
//Change a password for a User via command line, through the API.
//download the following file to the same directory:
//http://files.directadmin.com/services/all/httpsocket/httpsocket.php
$system = $_POST['system'];
$db = $_POST['db'];
$ftp = $_POST['ftp'];
$id = $_GET['id'];
$psw = $_POST['userpw'];
$queryda = "SELECT * FROM paugos where id = '$id'"; //You don't need a ; like you do in SQL
$resultda = mysql_query($queryda);
$rowda = mysql_fetch_array($resultda);
if($system == "" or $system == "no" or $system !== "yes"){
$system = "no";
}
if($db == "" or $db == "no" or $db !== "yes"){
$db = "no";
}
if($ftp == "" or $ftp == "no" or $ftp !== "yes"){
$ftp = "no";
}
$server_ip="127.0.0.1";
$server_login="admin";
$server_pass="kandon";
$server_ssl="N";
$username = $rowda['luser'];
$pass= $psw;
echo "changing password for user $username\n";
include 'httpsocket.php';
$sock = new HTTPSocket;
if ($server_ssl == 'Y')
{
$sock->connect("ssl://".$server_ip, 2222);
}
else
{
$sock->connect($server_ip, 2222);
}
$sock->set_login($server_login,$server_pass);
$sock->set_method('POST');
$sock->query('/CMD_API_USER_PASSWD',
array(
'username' => $username,
'passwd' => $pass,
'passwd2' => $pass,
'options' => 'yes',
'system' => $system,
'ftp' => $ftp,
'database' => $db,
));
$result = $sock->fetch_parsed_body();
if ($result['error'] != "0")
{
echo "\n*****\n";
echo "Error setting password for $username:\n";
echo " ".$result['text']."\n";
echo " ".$result['details']."\n";
}
else
{
mysql_query("UPDATE paugos SET lpass='$pass' WHERE id='$id'");
//echo "<script type='text/javascript'> document.location = 'control?id=$id&successpw=1'; </script>";
//header("Location: control?id=1&successpw=1");
echo "$user password set to $pass\n";
}
exit(0);
?>
if script fails, it returns
Error setting password for $username. If success then php script return $user password set to $pass.
So i want to return answer from php page to html page with jquery/ajax.
My html form, from where I post data to my php script
<form action="changepsw.php?id=<?=$id;?>" method="post" role="form">
<label for="disabledSelect">Directadmin account</label>
<input name="usern" class="form-control" style="width:220px;" type="text" placeholder="<?=$luser;?>" disabled>
<div class="form-group">
<label>New password</label>
<input name="userpw" class="form-control" style="width:220px;" placeholder="Enter new password">
</div>
<div class="form-group">
<label>Change password for:</label>
<div class="checkbox">
<label>
<input type="checkbox" name="system" value="yes">Directadmin
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="ftp" value="yes">FTP
</label>
</div>
<div class="checkbox">
<label>
<input type="checkbox" name="dabatase" value="yes">MySQL
</label>
</div>
</div>
<button type="submit" id="col" class="btn btn-default">Submit Button</button>
<button type="reset" class="btn btn-default">Reset Button</button>
</form>
In your HTML page you can user AJAX post request and in php you must use the die method as follows:
$.post('url',{parameters},function(data){
if(data==='1'){
alert('Done');
}else if(data==='0'){
alert('Error');
}else{
alert(data);
}
});
In PHP code use as follows:
die('1'); or die('0'); or
echo 'error occurs';
die;
My page is main.php it was made like this code
<?php
include_once('createtables.php');
include('function.php');
?>
<!DOCTYPE html>
<html lang="en">
<head>
<title></title>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="../includes/css/bootstrap.min.css">
<link rel="stylesheet" href="../includes/css/main.css">
<script src="../includes/js/jQuery.js"></script>
<script src="../includes/js/login.js"></script>
<script src="../includes/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container-fluid">
<form id="lgform" action="checklogin.php" method="post">
<h4 class="text-primary" id="llc"><img src="../includes/img/chatballoon.png"> Network Chat </h4>
<div class="input-group" id="firstone">
<span class="input-group-addon">
<span class="glyphicon glyphicon-user"></span>
</span>
<input type="text" class="form-control" placeholder="Enter Account name" id="username" name="username" autofocus>
</div>
<div class="input-group" id="secondtwo">
<span class="input-group-addon" id="password-addon">
<span class="glyphicon glyphicon-lock"></span>
</span>
<input type="password" class="form-control" placeholder="Enter your password" aria-decribedby="password-addon" id="password" name="password" autofocus>
</div>
Create Account
<input type="submit" class="pull-right btn btn-primary btn-sm" name="submit" id="submit" value="Enter now">
</form>
</div>
</body>
</html>
This is my checklogin php was like this:
<?php
ob_start();
session_start();
include("function.php");
$conn = new Functions();
$conn = $conn->db;
//define username and password
$username = $_POST['username'];
$password = $_POST['password'];
$username = stripslashes($username);
$password = stripcslashes($password);
$salt = "dctech2015ABcRXd";
$password = md5($password) . $salt;
$password = sha1($password);
//SELECT QUERY TO FIND IF INPUT INFORMATION WAS ON DATABASE
$stmt = $conn->query("SELECT * FROM users WHERE username ='$username' AND password='$password'");
//LOOP ENTIRE DATABASE ROW
$count = $stmt->rowCount();
//IF INFORMATION FOUND SELECT STATUS IF ALREADY ONLINE OR NOT
if($count == 1){
$status;
$stmt = $conn->prepare("SELECT status FROM users WHERE username='$username'");
$stmt->execute();
while($checkstatus = $stmt->fetch(PDO::FETCH_OBJ)){
$status = $checkstatus->status;
}
if($status == 'Online'){
echo "online";
}else{
echo "success";
$_SESSION['username'] = $username;
$_SESSION['password'] = $password;
$stmt = $conn->prepare("UPDATE users SET status='Online' WHERE username='$username'");
$stmt->execute();
}
}
ob_end_flush();
?>
ajax here:
$(document).ready(function(){
$("#submit").click(function(e){
e.preventDefault();
var username = document.getElementById("username").value;
var password = document.getElementById("password").value;
if(username==""){
alert("Please enter your account name");
}else if(password == ""){
alert("Please enter your password");
}else{
$.ajax({
type: "POST",
url: "checklogin.php",
data: "username="+username+"&password="+password,
success: function(data){
if(data == "success"){
window.location.href="chat.php";
}
else if(data == "online"){
alert("account is already online");
}else{
alert("Invalid Account name/Account password");
}
},error:function(data){
alert("an error occured through data");
}
});
}
document.getElementById("username").value = "";
document.getElementById("password").value = "";
});
return false;
});
problem that checklogin.php file is accessible to browser. what i want is to avoid unauthorized users to go to this page cause even login users if they type on browser register.php it will go to it and says username error etc.
This type of error:
You should respond with the standard http status code: 401, so the browser knows it has failed to load the page:
if($count == 1){
...
} else {
header("HTTP/1.1 401 Unauthorized");
// or for php 5.4:
http_response_code(401);
}
Update:
For the errors you added later:
Before you access the values in $_POST, check if they are present:
if (isset($_POST['username']) && isset($_POST['password'])) {
$username = $_POST['username'];
$password = $_POST['password'];
// ... all the rest of your code that depends on $_POST comes here
}
You can add some checking to your check_login script to see if the URL matches and kick it back. if(strpos($_SERVER['REQUEST_URI'], 'register.php')) exit() or something to that affect.
I am trying to make a simple price match contact form on my product page in Magento. I have a separate php file but it doesn't seem to receive the commands from the view.phtml file.
this is the form code which is located inside /app/design/frontend/default/my_design/template/catalog/product/view.phtml
<div class="pricematcher">
<body class="body">
<div id="pricematch" style="display:none;">
<!-- Popup Div Starts Here -->
<div id="popupContact">
<!-- Contact Us Form -->
<form action="send_contact.php" id="form" method="post" name="form">
<img id="close" src="<?php echo $this->getSkinUrl(); ?>images/close.png" onclick="div_hide()"</img>
<h2 class="h2price">Price Match</h2>
<hr id="hrprice">
<input id="name" name="name" placeholder="Name" type="text">
<input id="email" name="email" placeholder="Email" type="text">
<input id="productname" name="productname" placeholder="<?php echo $_helper->productAttribute($_product, $_product->getName(), 'name') ?><?php echo $this->__(' PART #: ');?><?php echo $_helper->productAttribute($_product, nl2br($_product->getSku()), 'sku') ?>" type="text" readonly>
<input id="competitor" name="competitor" placeholder="Competitor Product Link" type="text">
<textarea id="msg" name="msg" placeholder="Message"></textarea>
Submit
</form>
</div>
<!-- Popup Div Ends Here -->
</div>
<!-- Display Popup Button -->
</body>
</div>
<img id="popup" src="<?php echo $this->getSkinUrl(); ?>images/price-match.png" onclick="div_show()"</img>
this is the javascript which makes the form pop up and display
// Validating Empty Field
function check_empty() {
if (document.getElementById('name').value == "" || document.getElementById('email').value == "" || document.getElementById('msg').value == "") {
alert("Fill All Fields !");
} else {
document.getElementById('form').submit();
alert("Thank You for submitting a Price Match inquiry");
}
}
//Function to Hide Price Match
function div_hide(){
document.getElementById('pricematch').style.display = "none";
}
//Function To Display Price Match
function div_show() {
document.getElementById('pricematch').style.display = "block";
}
this is the php file that the form action should send to send_contact.php file located in the same directory as view.phtml
<?php
$subject = "Price Match";
$message = $_POST['msg'];
$name = $_POST['name'];
$product = $_POST['productname'];
$competitor = $_POST['competitor'];
$mail_from = $_POST['email'];
// Enter Your email Adress
$to = "myemail#email.com";
$body = "$message, $competitor, $product";
$send_contact = mail($to,$subject,$body, "From: " . $mail_from);
//Check if message sent
if ($send_contact){
echo "we recieved";
}
else {
echo "error";
}
?>
Every thing works when I make this in a seperate folder on my server and execute outside of magento.
You should put send_contact.php at magento's root directory.
I think you can create an action in ProductController.php,for example,postEmailAction, then in the postEmailAction,you can get the data from the form:
$message = $_POST['msg'];
$name = $_POST['name'];
$product = $_POST['productname'];
$competitor = $_POST['competitor'];
$mail_from = $_POST['email'];
, flow the code:
`
$mail = Mage::getModel('core/email');
$mail->setToName('YourStore Admin');
$mail->setToEmail($toEmail);
$mail->setBody($body);
$mail->setSubject('YourStore: New Product Review');
$mail->setFromEmail('donotreply#yourstore.com');
$mail->setFromName("YourStore");
$mail->setType('html');
try {
$mail->send();
}
catch (Exception $e) {
Mage::logException($e);
}
`
the action url will be the product controller + the action name;
Hope this will help you.
I have the following box that contains a sign upform:
<!-- sign up form -->
<div id="cd-signup">
<form class="cd-form" action = "signup.php" > <?php echo "$error" ?>
<p class="fieldset">
<label class="image-replace cd-username" for="signup-username">Username</label>
<input class="full-width has-padding has-border" id="signup-username" type="text" placeholder="Username" name = "user" <?php echo "value='$user'"?>>
</p>
<p class="fieldset">
<label class="image-replace cd-password" for="signup-password">Password</label>
<input name = "pass" class="full-width has-padding has-border" <?php echo "value='$pass'" ?> id="signup-password" type="text" placeholder="Password">
<!-- <span class="cd-error-message">Password must be at least 6 characters long</span> -->
</p>
<p class="fieldset">
<input class="full-width has-padding" type="submit" value="Create account">
</p>
</form>
<!-- more text here -->
<span class="section-nav">
<ul>
<li><a id="signup" class="cd-signup" href="#0">Get Started</a></li>
<li><a id="learnmore" class="cd-learnmore" href="#section2">Learn More</a></li>
</ul>
</span>
<span class="section-nav">
<ul>
<li><a id="signup" class="cd-signup" href="#0">Get Started</a></li>
</ul>
These were implemented as a button shape.
I included at the head of my html file (index.php) the following php code:
<?php
require_once 'functions.php';
require_once 'signup.php';
$userstr = '';
if (isset($_SESSION['user'])) {
$user = $_SESSION['user'];
$loggedin = TRUE;
$userstr = " ($user)";
}
else $loggedin = FALSE;
if ($loggedin) {
header(home.php);
}
else {
?>
signup.php:
session_start();
<?php
$error = $user = $pass = "";
if (isset($_SESSION['user'])) destroySession();
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "")
$error = "Not all fields were entered<br><br>";
else
{
$result = queryMysql("SELECT * FROM members WHERE user='$user'");
if ($result->num_rows)
$error = "That username already exists<br><br>";
else
{
queryMysql("INSERT INTO members VALUES('$user', '$pass')");
die("<h4>Account created</h4>Please Log in.<br><br>");
}
}
}
?>
functions.php:
<?php
$dbhost = 'localhost'; // Unlikely to require changing
$dbname = 'socialmedia'; // Modify these...
$dbuser = 'root'; // ...variables according
$dbpass = 'mysql'; // ...to your installation
$appname = "Social Media"; // ...and preference
$connection = new mysqli($dbhost, $dbuser, $dbpass, $dbname);
if ($connection->connect_error) die($connection->connect_error);
function queryMysql($query)
{
global $connection;
$result = $connection->query($query);
if (!$result) die($connection->error);
return $result;
}
function destroySession()
{
$_SESSION=array();
if (session_id() != "" || isset($_COOKIE[session_name()]))
setcookie(session_name(), '', time()-2592000, '/');
session_destroy();
}
function sanitizeString($var)
{
global $connection;
$var = strip_tags($var);
$var = htmlentities($var);
$var = stripslashes($var);
return $connection->real_escape_string($var);
}
function showProfile($user)
{
if (file_exists("$user.jpg"))
echo "<img src='$user.jpg' style='float:left;'>";
$result = queryMysql("SELECT * FROM profiles WHERE user='$user'");
if ($result->num_rows)
{
$row = $result->fetch_array(MYSQLI_ASSOC);
echo stripslashes($row['text']) . "<br style='clear:left;'><br>";
}
}
?>
The code works perfectly from where I got it (source: Learn Php, MySql, & Javascript), so I decided to apply it to me own website.
However, When I click on the create account button, nothing happens. The database is correctly set along with the appropriate tables (tested on original code) along with the proper Ajax Requests.
I think the problem is somewhere in index.php, maybe something I missed ?
Thank you for your help ! :)
EDIT:
here is the javascript of the button implementation
jQuery(document).ready(function ($) {
var formModal = $('.cd-user-modal'),
formSignup = formModal.find('#cd-signup'),
tabSignup = formModalTab.children('li').eq(1).children('a'),
,
backToLoginLink = formForgotPassword.find('.cd-form-bottom-message a'),
mainNav = $('.main-nav'),
sectionNav = $(".section-nav");
//open modal
mainNav.on('click', function (event) {
$(event.target).is(mainNav) && mainNav.children('ul').toggleClass('is-visible');
});
//open sign-up form
sectionNav.on('click', '.cd-signup', signup_selected);
//open login-form form
mainNav.on('click', '.cd-signin', login_selected);
//close modal
formModal.on('click', function (event) {
if ($(event.target).is(formModal) || $(event.target).is('.cd-close-form')) {
formModal.removeClass('is-visible');
}
});
//close modal when clicking the esc keyboard button
$(document).keyup(function (event) {
if (event.which == '27') {
formModal.removeClass('is-visible');
}
});
//switch from a tab to another
formModalTab.on('click', function (event) {
event.preventDefault();
($(event.target).is(tabLogin)) ? login_selected() : signup_selected();
});
function signup_selected() {
mainNav.children('ul').removeClass('is-visible');
formModal.addClass('is-visible');
formLogin.removeClass('is-selected');
formSignup.addClass('is-selected');
formForgotPassword.removeClass('is-selected');
tabLogin.removeClass('selected');
tabSignup.addClass('selected');
}
Take a look at this line:
<p class="fieldset">
<input class="full-width has-padding" type="submit" value="Create account">
</p>
Your submit button should have a name of user.
<p class="fieldset">
<input class="full-width has-padding" name="user" type="submit" value="Create account">
</p>