I want to make Login page with PHP.
And want to use button but it didn't works.
and it looks like just refresh the page.
I tried button tag in the form.
How can I make this works??
<?php
include "login.php";
?>
<form method="post" id="sign">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="email" name="user_mail" id="user_mail" value="<?php echo addslashes($_POST['user_mail'] ?? '') ?>">
<label class="mdl-textfield__label" for="user_mail">Email</label>
</div>
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="password" name="passcode" id="passcode" value="<?php echo addslashes($_POST['passcode'] ?? '') ?>">
<label class="mdl-textfield__label" for="passcode">Password</label>
</div>
</form>
//this <input> works
<input type="submit" name="signup" form="sign"/>
//I want to use this <button>
<button type="submit" name"signup" form "sign" formmethod="post"></button>
<?php
if ($error ?? '') {
echo addslashes($error);
}
login.php
if ($_POST['signup'] ?? '') {
$error = '';
if (!$_POST['user_mail']) $error .= "<br />Please enter email";
else if (!filter_var($_POST['user_mail'], FILTER_VALIDATE_EMAIL)) $error .= "<br />Please enter valid email";
if (!$_POST['passcode']) $error .= "<br />Please enter password";
else {
if (strlen($_POST['passcode']) < 8) $error .= "<br />Please enter a password more than eight";
if (!preg_match('`[A-Z]`', $_POST['passcode'])) $error .= "<br />please least one capital letter";
}
if ($error) $error = "there were errors:" . $error;
<button> means put a button on the page and execute whatever is in the onclick method. <submit> submits a form.
If you want a button to sumbit your form, use the onclick method of the button to do it. Why can't you use submit, though?
See here, they use a link <a onclick='...' but you can do the same for your button: How to submit a form with JavaScript by clicking a link?
As #Arun says below, you can use:
<button type='submit'> inside your form, too. There are lots of ways to do things, so my only advice on top of this is to be consistent. I use input out of habit, and that way I don't have a bunch of mixed conventions throughout my code.
If you want to submit a form on button click, add click event of button using jquery and submit a form like:
Html:
<button type="submit" name"signup" id="btn_submit" value="submit" >Submit</button>
Jquery:
$("#btn_submit").click(function() {
$("#sign").submit(); // submit a form
});
You need to make 2 changes:
Add action attribute
Move your button element inside the form. You can't expect any button on the page to submit your form. It must be inside the form, to which it is associated.
<form method="post" id="sign" action="form-destination.php">
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="email" name="user_mail" id="user_mail" value="<?php echo addslashes($_POST['user_mail'] ?? '') ?>">
<label class="mdl-textfield__label" for="user_mail">Email</label>
</div>
<div class="mdl-textfield mdl-js-textfield">
<input class="mdl-textfield__input" type="password" name="passcode" id="passcode" value="<?php echo addslashes($_POST['passcode'] ?? '') ?>">
<label class="mdl-textfield__label" for="passcode">Password</label>
</div>
<button type="submit" name"signup" form "sign" formmethod="post"></button>
</form>
<?php
if ($error ?? '') {
echo addslashes($error);
}
?>
I think you need to put a action on the form element:
<form method="post" id="sign" action="login.php">
i don't know PHP so i might be wrong.
Related
I'm doing a form validation in my php script, take one column as an example, if the username is not filled, an alert window will pop up and say "please enter your username", after user click "ok", the whole page refresh but the information on the form will be reset too.
So I would like to keep what the user has input after refreshing the page, how can I embed the code in php using AJAX?
//username validation
if (empty($username)) {
$error = true;
echo '<script language="javascript">';
echo 'alert("Please enter your username")';
echo '</script>';
//refresh the page
header("Refresh:0; url=register.php");
the website is in php file, html code is embedded under the php stuff, and this is the form in the html
<div id="account">
<form method="POST">
<p><span class="error">* required field.</span></p>
Username:
<input type="text" name="Username">
<span class="error">* </span><br>
<!--other fields..-->
<input type="reset" value="Reset">
<input type="submit" value="Submit" name="signup_button">
</form>
</div>
<?php
if(isset($_POST['signup_button'])){
$Username = $_POST['Username'];
}
?>
or...
if (empty($username)) {
$error = true;
echo '<script language="javascript">';
/* save the value in the browser */
echo 'window.'+VarYouWantToKeep = $_POST['VarYouWantToKeep'];
echo 'alert("Please enter your username")';
echo '</script>';
//refresh the page
header("Refresh:0; url=register.php");
( or use localStorage, instead of window. https://developer.mozilla.org/en/docs/Web/API/Window/localStorage )
Then, when the page loads, check if('window.'+VarYouWantToKeep)
and if it's there, set it as the value="" of the corresponding form field
try this (This is taking into account you set $username to $_POST["Username"];)
<input type="text" name="Username" value="<?php if(isset($_POST["signup_button"]) && $_POST["signup_button"]=="Submit") {echo $username; ?>"
To store variable data, you will need to use $_SESSION variables in PHP. Make sure that session_start() is at the top of the PHP page.
Here's a basic example:
//this PHP page contains the HTML form
<form>
<input type="text" value="<?php echo $_SESSION['email']; ?>" />
</form>
//ajax
$.ajax({
url:'validate.php',
type:'POST',
data:{name:inputName}
}).done(function(data){
alert(data);
});
//php page
session_start();
if(!isset($_POST['name'])){
//set session variable
$_SESSION['email'] = $_POST['email'];
//this will be sent back to PHP page with HTML
echo 'Please enter username';
}
I coded here, a super cool login page with bootstrap as you expect. Link bootstarp cdn in your html file. This will show the error under the button instead of showing a windows classic alert box. I included ajax request and php response also with some validation.
login.html
<div class="container">
<div class="col-lg-offset-8 col-md-offset-6 col-lg-4 col-md-4 login-bg">
<form class="form-horizontal" role="form" action="#" method="">
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-user"></i></span>
<input id="username" type="text" class="form-control" name="username" value="" placeholder="User Name" required tabindex="1" autocomplete="off">
</div>
<br>
<div class="input-group">
<span class="input-group-addon"><i class="glyphicon glyphicon-pencil"></i></span>
<input id="password" type="password" class="form-control" name="password" value="" placeholder="Password" required tabindex="2" autocomplete="off">
</div>
<br>
<div class="form-group">
<div class="col-lg-6">
<button class="btn btn-primary-outline btn-block" type="submit" id="login">Login</button>
</div>
<div class="col-lg-6">
<button class="btn btn-success-outline btn-block" type="reset">Clear</button>
</div>
</div>
<br>
<div id="login-feedback" class="btn-block"></div>
</form>
</div>
</div>
myStyle.js
<script type="text/javascript">
$(document).ready(function()
{
$('#login').click(function()
{
var uname=$('#username').val();
var pword=$('#password').val();
if(uname!='' && pword!='')
{
$('#login-feedback').text('validating....');
$.post("login-check.php",{username:uname,password:pword},function(data)
{
if(data=="success")
{
$('#login-feedback').fadeTo(200,0.1,function()
{
$(this).html(data).css('color','green').fadeTo(1000,1,function()
{
document.location='index.php';
});
});
}
else
{
$('#login-feedback').fadeTo(200,0.1,function()
{
$(this).html(data).css('color','red').fadeTo(900,1);
//reset form
$('#login').trigger("reset");
});
}
});
return false;
}
else
{
$('#login-feedback').text("Please enter all fields").css('color','purple');
}
});
});
</script>
login-check.php
<?php
//include connextion file;
if(!isset($_SESSION))
session_start();
$username=trim($_POST['username']);
$password=$_POST['password'];
$username=mysqli_real_escape_string($con,$username);
$password=mysqli_real_escape_string($con,md5($password));
if(($username) && ($password))
{
$query = mysqli_query($con,"select * from login where password='$password' AND username='$username'");
$rows = mysqli_num_rows($query);
if ($rows>= 1)
{
$fetch_result = mysqli_fetch_array($query);
session_regenerate_id(true);
$_SESSION['username']=$fetch_result['username'];
$_SESSION['status']=$fetch_result['status'];
// Close session variable assigns
session_write_close();
echo "success";
}
else
{
echo 'Login failed';
}
mysqli_close($con);
}
?>
I need one help.I need to totally remove the submit button after submit the form and when it will be submitted the button will display to user.I am explaining my code below.
<form name="billdata" id="billdata" enctype="multipart/form-data" method="POST" onSubmit="javascript:return checkForm();" action="complain.php">
<div class="input-group bmargindiv1 col-md-12">
<span class="input-group-addon ndrftextwidth text-right" style="width:180px"> Name :</span>
<input type="text" name="u_name" id="name" class="form-control" placeholder="Add Name" onKeyPress="clearField('name');">
</div>
<input type="submit" class="btn btn-success" name="complainSubmit" id="addProfileData" value="Submit"/>
</form>
complain.php:
require_once("./include/dbconfig.php");
if(isset($_REQUEST['complainSubmit']))
{
// ......data is collecting here....
}
when data are submitted successfully the below part is executing.
<script type="text/javascript">
var phpVar = "<?php echo $_GET['success'];?>";
//console.log('php',phpVar=='');
if(phpVar == 1 && phpVar!=''){
alert('Submitted successfully.');
//var subButton=document.getElementById('addProfileData');
//subButton.disabled=false;
}
else if(phpVar == 0 && phpVar!=''){
alert('Unable to add.\\nTry again.');
}
else{
// nothing
}
</script>
<script>
function checkForm(){
var s=document.billdata;
if(s.u_name.value==''){
alert('Please enter name');
s.u_name.focus();
s.u_name.style.borderColor = "red";
return false;
}
}
</script>
Here i need to button hide when the data is going to submit and it will again display after the submit.Please help me.
A javascript code such as:
document.getElementById("your_div").innerHTML = "";
will erase the content of your div.
So, byt tagging the entire form, then erasing its contents, you can "hide" it.
Why you dont add a hide CSS-Selector or remove it by checking via if-statement?
CSS-Version:
<input type="submit" class="btn btn-success <?php ($isSubmitted ? ' hideme' : '')?>" name="complainSubmit" id="addProfileData" value="Submit">
Except a new CSS-Selector: .hideme { display:none }
Via PHP/Template:
html...
<?php if(!$isSubmitted) : ?>
<input type="submit" class="btn btn-success" name="complainSubmit" id="addProfileData" value="Submit">
<?php endif; ?>
html...
Dont forget: You dont need close input html-tag: <input/> just <input>
And what is wrong to hide the button via JS?
document.getElementById("addProfileData").style.display = "none";
UPDATE:
Prompt hiding after clicking:
<button onclick="javascript:this.style.display='none'">
Submit Button
</button>
in your example:
<input onclick="javascript:this.style.display='none'" type="submit" class="btn btn-success" name="complainSubmit" id="addProfileData" value="Submit"/>
I'm trying to disable a submit button when I get some trigger from the database that tells me I should disable it, I added some code in the echo line in PHP but it didn't work, what am I doing wrong?
PHP CODE
$tries= CCL::Triescount($userip)->NumofTries;
if ($tries > 2 ) //Check wheter they have tried more than 2 times then block them
{
$msg = "More than 2 attempts, block user";
echo '<input type="submit" disabled="disabled" />';
}
else
{
$tries++;
$msg = "Less than 2 attempts";
CCL::Updatetries($userip,$tries,0);
//insert into the DB
}
HTML FORM
<div class="ui-body ui-body-c ui-corner-all">
<h1>Forgot Password</h1>
<form>
<label for="emailpassdlbl"> Please enter the e-mail associated with your account, and a new auto-generated password will be sent to this e-mail account.</label>
<input type="text" id="email"><BR>
<div class="right">
<input type="submit" data-inline="true" value="Submit" disabled="disabled">
</div>
</form>
<br/>
<div data-role="popup" class="ui-body ui-body-c ui-corner-all">
<h2 id="result"></h2>
OK
</div>
If you're changing the entire code with PHP to disable it, why not remove the submit functionality altogether?
For example:
if ($tries > 2 ) //Check wheter they have tried more than 2 times then block them
{
$msg = "More than 2 attempts, block user";
echo '<button type="button" disabled" />';
}
As you can see we have actually removed the type="submit" and replaced it with type="button" it should still look like the same button however it wont submit the form (in addition to the disabled attribute).
I am new with php, but I have already made a registration script that works fine. But the problem is every time I press the submit button to check my error, I'm going to a new page.
My question is how I make that error comes on the same page?
The code I am useing for the html form.
I want the error display in the error div box that I made Any idea ?
<div id="RegistrationFormLayout">
<h1>Registration Page</h1>
<div id="ErrorMessage"></div>
<form action="script/registration.php" method="post">
<label for="Username">Username</label>
<input type="text" name="Regi_username">
<label for="FirstName">FirstName</label>
<input type="text" name="Regi_Firstname">
<label for="LastName">LastName</label>
<input type="text" name="Regi_Lastname">
<label for="EamilAddress">Regi_EmailAddres</label>
<input type="text" name="Regi_EmailAddres">
<label for="Password">Password</label>
<input type="password" name="Regi_password">
<button type="submit" value="Submit" class="Login_button">Login</button>
</form>
</div>
If I understand correctly, you want form validation errors there. This is a very common pattern, and the simple solution is to always set a form's action attribute to the same page that displays the form. This allows you to do the form processing before trying to display the form (if there are $_POST values). If the validation is successful, send a redirect header to the "next step" page (with header()).
The basic pattern looks like this (in very very simplified PHP)
<?php
if(count($_POST)) {
$errors = array();
$username = trim($_POST['Regi_username']);
if(empty($username)) {
$errors[] = 'username is required';
}
if(count($errors) == 0) {
header('Location: success.php');
die();
}
}
<ul class="errors">
<?php foreach($errors as $error) { ?>
<li><?php echo $error;?></li>
<?php } ?>
</ul>
My form is working fine with the validations being done by PHP.
I have three fields: Name, EMail and Message.
Form and PHP code is within the same pgae, same page is called for validations when user submits the form.
When a user submits the form, same page is called and it checks whether the form is submitted or not.
If the form is submitted it then does the validations for blank entries and throws error message below the fields to inform user that field is left blank. It also shows error icon next to field.
Till this, it is working fine.
However, the problem, is if the user has filled any field, for example name filed and left the other two fields(EMail and Message) blank, then on submittion, it throws error messages for blank fields which is ok, but for name field which was filled by user it empty the content and shows blank name field and does not show error(as earlier user had filled it).
My only concern is that when it relods the form after submission, it should also reload the earlier values in the respective fields which user input before submitting.
Below is the PHP validation code.
<?php
error_reporting(E_ALL & ~E_NOTICE);
if(isset($_POST['nameField_Name']) AND isset($_POST['nameField_EMail']) AND isset($_POST['nameField_Message']) AND isset($_POST['nameSubmit'])){
// Form Submited
if ($_POST['nameField_Name']) {
$phpVarNameField = mysql_escape_string($_POST['nameField_Name']);
} else {
$errormsgNameField = "Name field is required, Please enter your Name.";
}
if ($_POST['nameField_EMail']) {
$phpVarEMailField = mysql_escape_string($_POST['nameField_EMail']);
} else {
$errormsgEMailField = "E-Mail field is required, Please enter your E-Mail ID.";
}
if ($_POST['nameField_Message']) {
$phpVarMessageField = mysql_escape_string($_POST['nameField_Message']);
} else {
$errormsgMessageField = "Message field is required, Please enter your Message.";
}
}
?>
Below is the form code.
<form name="myform" action="contactus.php" method="post"">
<div id="r1">
<div id="r1c1">
<input type="text" name="nameField_Name" id="idField_Name" placeholder="Enter your name here"/>
</div>
<div id="r1c2">
<?php
if(isset($errormsgNameField)){ // Check if $msg is not empty
echo '<img src="error.png" width="45" height="45" style="margin: 5px 0px" alt="">';
}
?>
</div>
</div>
<div id="afterr1">
<?php
if(isset($errormsgNameField)){ // Check if $msg is not empty
echo '<div class="statusmsg" id="idErrorMsgNameField">'.$errormsgNameField.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
</div>
<div id="r2">
<div id="r2c1">
<input name="nameField_EMail" type="text" id="idField_EMail" placeholder="Enter your E-Mail address here" />
</div>
<div id="r2c2">
<?php
if(isset($errormsgEMailField)){ // Check if $msg is not empty
echo '<img src="error.png" width="45" height="45" style="margin: 5px 0px" alt="">';
}
?>
</div>
</div>
<div id="afterr2">
<?php
if(isset($errormsgEMailField)){ // Check if $msg is not empty
echo '<div class="statusmsg" id="idErrorMsgEMailField">'.$errormsgEMailField.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
</div>
<div id="r3">
<div id="r3c1">
<textarea name="nameField_Message" id="idField_Message" placeholder="Enter your message for us here"></textarea>
</div>
<div id="r3c2">
<?php
if(isset($errormsgMessageField)){ // Check if $msg is not empty
echo '<img src="error.png" width="45" height="45" style="margin: 115px 0px" alt="">';
}
?>
</div>
</div>
<div id="afterr3">
<?php
if(isset($errormsgMessageField)){ // Check if $msg is not empty
echo '<div class="statusmsg" id="idErrorMsgMessageField">'.$errormsgMessageField.'</div>'; // Display our message and wrap it with a div with the class "statusmsg".
}
?>
</div>
<div id="r4">
<div id="r4c">
<input type="Submit" name="nameSubmit" id="idButton_Submit" value="Submit" alt="Submit Button"/>
</div>
</div>
</form>
Any help will be great on this.
Thank You.
You will need to add a value attribute on your <input> elements:
<input type="text"
name="whatever"
value="<?php echo htmlspecialchars($_POST['whatever']); ?>"
>
It may be easier to read if PHP outputs the field:
<?php
printf('<input type="text" name="%s" value="%s">',
'whatever',
htmlspecialchars($_POST['whatever']));
?>
This can even be wrapped in a function so you don't need to retype it for every single form field.
Note the call to htmlspecialchars. It is needed so that < and > and quotes don't destroy your HTML document.
Try changing your tag like :
<input type="text"
name="nameField_Name"
id="idField_Name"
placeholder="Enter your name here"
value ="<?php
if (isset($phpVarNameField))
echo $phpVarNameField;
?>"
/>
.......
<input
name="nameField_EMail"
type="text"
id="idField_EMail"
placeholder="Enter your E-Mail address here"
value ="<?php if (isset($phpVarEMailField)) echo $phpVarEMailField; ?>"
/>
.......
<textarea name="nameField_Message" id="idField_Message" placeholder="Enter your message for us
here" value ="<?php if (isset($phpVarMessageField)) echo $phpVarMessageField; ?>" ></textarea>
Good Luck !
Well, You could do validation with jQuery validation plugin - easy and good. jQuery plugin
Or with PHP store POST data in array, check for errors and fields that are not empty set as value to input text.
if (isset($_POST)) {
$data = $_POST;
}
foreach ($data as $row) {
if ($row == "")
$error = true; // do what ever you want
}
and then in form
<input type="text" name="name" value="<?php ($data['name'] != "")? $data['name'] : '' ?>" />
something like this.