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>
Related
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})$/;
My task is to make a div visible after submitting a form. The problem is: after submitting the form, the div appears for 0.5 sec, then it disappears again.
This is the relevant code part. I want to show the div with id="data".
<form action="" method="post" onsubmit="show_div()">
<div class="request">
<center>
<img id="logo" src="/img/n1_red.png" alt="">
<h1 id="t_request" class="item">Account Name</h1>
<br/>
<input type="text" id="request" name="Request" value="<?php echo $cloud; ?>" class="item"><br/>
<input type="submit" class="bttn" class="item" onclick="show_div()" value="Send" /><br/>
</center>
</div>
<div id="data" style="display:none">
<h2 id="t_mail">Mail</h2>
<p class="result"><?php echo $Email; ?></p>
<h2 id="t_password">Password</h2>
<input type="checkbox" id="pass_visibility" onclick="unhide_password()" value="Unhide pass"/>
<label for="pass_visibility" id="pass_visibility_label">(Unhide pass)</label>
<p class="pass_result" id="text_hidden_pass">Password is hidden.</p>
<p class="result" id="text_pass" style="display:none"><?php echo $Password; ?></p>
<h2 id="t_total_gb">Total GB</h2>
<p class="result"><?php echo $Total_GB; ?></p>
<h2 id="t_gb_used">Used GB</h2>
<p class="result"><?php echo $GB_Used; ?></p>
<h2 id="t_about">About</h2>
<p class="result"><?php echo $About; ?></p>
<h2 id="t_key">KEY</h2>
<p class="result"><?php echo $Decryption; ?></p>
<h2 id="t_authy">Authy</h2>
<p class="result"><?php echo $Authy; ?></p>
<h2 id="t_nr_acc">Acc name</h2>
<p class="result"><?php echo $Name; ?></p>
</div>
</form>
and this is the JavaScript code:
var div = document.getElementById("data");
function show_div() {
div.style.display = "block";
}
I tried to do this in 2 different methods:
First one was to add onclick="show_div() to the submit button.
<input type="submit" class="bttn" class="item" onclick="show_div()" value="Send" /><br/>
Then I added onsubmit="show_div()" to the submit form.
<form action="" method="post" onsubmit="show_div()">
As I said, with this method (after submitting the form/clicking the button) the result is not as expected. The div appears for 0.5 sec, then it disappears again.
Not sure if you need, but here is the CSS for id="data":
#data {
border-top: dashed 3px rebeccapurple;
border-left: dashed 3px rebeccapurple;
padding-left: 20px;
display: block;
}
And here the PHP code:
$cloud = "";
$Email = "";
$Password = "";
$Name = "";
$Total_GB = "";
$GB_Used = "";
$About = "";
$Decryption = "";
$Authy = "";
if($_SERVER["REQUEST_METHOD"] == "POST") {
$servername = "localhost";
$username = "root";
$password = "";
$db = "xxx";
$con = mysql_connect($servername,$username,$password);
if (!$con) {
die('Could not connect: ' . mysql_error());
}
mysql_select_db("xxx", $con);
$cloud = $_POST["Request"];
// Query
$query = "SELECT * FROM Clouds WHERE Name = '$cloud' LIMIT 1";
$result = mysql_query($query) or die(mysql_error());
if ($result >= 1) {
while($row = mysql_fetch_assoc($result)) {
$Email = $row['Email'];
$Password = $row['Password'];
$Name = $row['Name'];
$Total_GB = $row['Total_GB'];
$GB_Used = $row['GB_Used'];
$About = $row['About'];
$Decryption = $row['Decryption'];
$Authy = $row['Authy'];
}
} else {
//$error_not_found = "Account not found!";
}
}
I am missing something? Any advice for me? Thanks
Another Stack Overflow question:
I checked everything. I followed her tips too. No result. Well... The same result
This is a snippet you may use. It is not possible to show a div and send the form together, see the comment of esque above.
<form id="form1" action="..." method="post">
<!-- here your form fileds -->
</form>
// true = show div --- false = send form
var showDiv = true;
// form id selector
var myForm = document.querySelector("#form1");
// bind submit event to form
myForm.addEventListener("submit", function(event) {
if (showDiv == false) {
console.log('send form');
return;
}
event.preventDefault();
console.log('Show div, form not send');
var div = document.getElementById("data");
div.style.display = "block";
});
When I'm using PHP in JavaScript, then all scripts don't work...
Even if I use php in comment.
<script>
//var variable = <?php echo json_encode($_SESSION['abc']); ?>;
</script>
This comment above destroy all scripts in <script></script> tags.
When I'll delete this line with the comment, then every script will work.
The same thing is when I just want to use PHP in JavaScript (without comment).
Could You help me ?
Here is code which was cut by me (to give You only necessary part of code), please help :) :
<?php
session_start();
if (isset($_POST['login']) && isset($_POST['password']) && isset($_POST['email']))
{
$validation = true;
$firstName = $_SESSION['firstName'];
$lastName = $_SESSION['lastName'];
$street = $_SESSION['street'];
$phone = $_SESSION['phone'];
$login = $_POST['login'];
$password = $_POST['password'];
$email = $_POST['email'];
require_once "connect.php";
mysqli_report(MYSQLI_REPORT_STRICT);
try
{
$connection = new mysqli($host, $db_user, $db_password, $db_name);
if($connection->connect_errno!=0)
{
throw new Exception(mysqli_connect_errno());
}
else
{
if ($validation == true) // when validation process will be successfuly done - i cut validation process
{
if($connection->query("INSERT INTO users values (NULL, '$firstName', '$lastName', '$street', '$phone', '$login', '$password', '$email')"))
{
$_SESSION['abc'] = "done";
//here is also header(location) to login page
}
else
{
throw new Exception($connection->error);
}
}
$connection->close();
}
}
catch(Exception $e)
{
echo '<div class="error">error. sorry, please to register in other term</div>';
}
}
?>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" />
<script>
//there are other functions for local/session storage
function deleteSessionData()
{
var variable = "<?php echo $_SESSION['abc']; ?>";
if(variable == "done")
{
sessionStorage.removeItem('firstName');
sessionStorage.removeItem('lastName');
sessionStorage.removeItem('street');
sessionStorage.removeItem('phone');
sessionStorage.removeItem('login');
sessionStorage.removeItem('password');
sessionStorage.removeItem('email');
}
}
</script>
</head>
<body>
<form id="myForm" method="post">
<label for="login">Login: </label>
<input type="text" id="login" name="login">
<label for="password">Password: </label>
<input type="text" id="password" name="password">
<label for="email">E-mail:</label>
<input type="email" id="email" name="email">
<button onclick="java script: document.getElementById('myForm').submit();deleteSessionData();">Register</button>
</form>
</div>
</body>
</html>
you need to comment the php too
//var variable = <?php // echo json_encode($_SESSION['abc']); ?>;
I wouldn't inject PHP into javascript like this without sanitation though.
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;
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.