I have a form to be filled in and a popup javascript alert will be displayed if the Password and Re-Confirm Password does not match. However, once I click "OK"on the popup alert, the whole form is reset. But I just want the password to be blank again, not the whole form.
I tried this way:
if($pwd != $pwd2) {
echo("<script type='text/javascript'>alert('Password does not match!')</script>");
}
I also tried the one below but still the same thing happened:
if($pwd != $pwd2) {
?>
<script type="text/javascript">
alert("Password does not match!");
</script>
<?php
}
Your validation is on server side, once you hit the server the form gets reset everytime, for showing validation error from server you need to pass the values to the form again with errors.
If you want to show the alert on validation error, use client side validation with jQuery or simple JS. In this way your form's values remain the same and the alert will be popped up.
if you really need using php
<?php
$pwd = isset($_REQUEST['pwd']) ? $_REQUEST['pwd'] : "";
$pwd2 = isset($_REQUEST['pwd2']) ? $_REQUEST['pwd2'] : "";
if($pwd != $pwd2) {
echo("<script type='text/javascript'>alert('Password does not match!')</script>");
}
>
<input name"pwd" value="<?php echo $pwd; ?>">
<input name"pwd2" value="<?php echo $pwd2; ?>">
If you want other input fields not to be empty after submission you should try this using php.
Let's say your input field is username.
$username = $_POST['username'];
<input type="text" name="username" value="<?php echo htmlentities($username); ?>">
When you use this, after you clicked ok and get the alert, your username field will not be empty. The value you entered will appear in the text field.
Try this code to solve your problem.
$username = $_POST['username'];
$password = $_POST['password'];
<input type="text" name="username" value="<?php echo htmlentities($username);
?>">
<input type="password" name="password">
Related
Here's my code. Now here what happens is when I fill that specific form with just 1 input the data gets submitted and the alert is shown after that, but if I don't fill anything in the form and just click on submit button, the alert is shown even if the form is empty, and after the alert, it shows that please fill out this field.. so what went wrong? tried searching for this solution and tried so many things but nothing works... :(
<div class="newsletter">
<p>Sign Up for the <strong>NEWSLETTER</strong></p>
<form method="post">
<?php
if(isset($_POST['subscribe']))
{
$e_mail = $_POST['e_mail'];
$conn = new mysqli('localhost','root','','purrfect_whiskers');
if($conn->connect_error)
{
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
}
else
{
$stmt = $conn->prepare("insert into newsletter(e_mail) values(?)");
$stmt->bind_param("s", $e_mail);
$stmt->execute();
$stmt->close();
$conn->close();
}
}
?>
<input class="input" type="email" name="e_mail" text-transform="lowercase" placeholder="Enter Your Email" autocomplete="off" required="required">
<button class="subscribe" onclick="submit_email()" type="submit" name="subscribe"><i class="fa fa-envelope"></i> Subscribe</button>
<script type="text/javascript">function submit_email(){alert("You've been subscribed to our newsletter!");}</script>
</form>
</div>
It looks like you should validate that the user did put in a value for email before allowing the submission. If they did not, present an error. If they did, allow the submission and on page refresh, present the success alert
There are a couple ways to prevent automatic form submission, one of them is to put an onsubmit handler in the form tag and have it return true (to allow the submission or false to prevent it. You can do all your validating in that handler:
<form method="POST" onsubmit="return submit_email()">
Then in your function, check that the value is there before allowing it to continue:
<script type="text/javascript">
function submit_email(){
let email_input = document.querySelector("input[name='e_mail']");
if (email_input.value=="") {
alert("Please type in your email first");
return false; // this prevents the form from submitting
}
return true; // this allows the submission
}
</script>
The form will submit, the page will refresh and your PHP code will do it's thing. At the end of which, just hardcode your alert, like this:
<?php
if(isset($_POST['subscribe'])){
// do all your code as you are, then end with:
?>
<script>
alert("You've been subscribed to our newsletter!");
</script>
<?php
}
?>
The alert code executes no matter what. You must therefore display it only if there is nothing in your form.
For that, I added an id in your input and I made a check to know if your form is empty or not.
The best would be to check with regex if it is indeed an email address but here is the code just to verify if it is just not empty
Here is the code:
<div class="newsletter">
<p>Sign Up for the <strong>NEWSLETTER</strong></p>
<form method="post">
<?php
if(isset($_POST['subscribe'])) {
$e_mail = $_POST['e_mail'];
$conn = new mysqli('localhost','root','','purrfect_whiskers');
if($conn->connect_error) {
echo "$conn->connect_error";
die("Connection Failed : ". $conn->connect_error);
} else {
$stmt = $conn->prepare("insert into newsletter(e_mail) values(?)");
$stmt->bind_param("s", $e_mail);
$stmt->execute();
$stmt->close();
$conn->close();
}
}
?>
<input id="id_input" class="input" type="email" name="e_mail" text-transform="lowercase"
placeholder="Enter Your Email"
autocomplete="off" required="required">
<button class="subscribe" onclick="submit_email()" type="submit" name="subscribe"><i class="fa fa-envelope"></i>
Subscribe
</button>
<script type="text/javascript">function submit_email() {
if (document.getElementById("id_input").value !== "") {
alert("You've been subscribed to our newsletter!");
}
}</script>
</form>
</div>
developers i create one page where it fetches data from the registration page. Each data row I put add and unfriend button (disabled). Once the user clicks add, the prompt box appears to ask the user to enter a subject and click ok. After click ok,it insert in another database table.while the unfriend button will be able to click. Here my problem is once click add button the prompt appears and after click ok, the data does not insert into the database. If I click unfriend button it inserts into the database. I want the data submitted whenever the user clicks the add button. I think it's because this form has two submit buttons but I don't know how to distinguish between the buttons.Moreover,in javascript i put return false and true follow some tutorials.may i know when i should use return false and true?. Here is the code:
<?php
session_start();
$mysqli=new MySQLi('127.0.0.1','root','','learning_malaysia');
$sql = "SELECT * FROM tutor_register INNER JOIN tutorskill ON tutor_register.register_ID = tutorskill.register_ID";
$result= mysqli_query($mysqli,$sql);
?>
<html>
<script>
function myFunction(form){
var subject = prompt("Please enter Subject that want to study");
form['add'].value="request sent";
if (subject != null){
form['subject'].value= subject;
form['btn'].disabled=false;
form['add'].disabled=true;
return false;
form.submit();
}
return true;
form['add'].submit();
}
function unfriend(form){
form["add"].disabled=false;
form["btn"].disabled=true;
form["add"].value="Add friend";
return true;
form.submit();
}
</script>
<body>
<?php
if(mysqli_num_rows($result)>0)
{
while($row = mysqli_fetch_array($result))
{
$register_ID=$row["register_ID"];
?>
<form method="post" id="form" enctype="multipart/form-data" autocomplete="off">
<input type="hidden" name="id" value="<?php echo $row['register_ID'];?>" />
<input type="hidden" id="subject" name="subject" data-uid=<?php echo $_SESSION['sid'] ;?>/>
<td><input type="submit" onclick="return myFunction(this.form);" name="addfriend" data-type='addfriend' id="add" class="btn" value="add" />
<input type="submit" value="unfriend" id="btn" onclick="return unfriend(this.form);" disabled /> </td> </form>
<?php
}
}
?>
<?php
if(isset($_POST['subject']) and $_POST['id']) {
$user_id = $_SESSION['sid'];
$friend_id = $_POST['id'];
$status = "yes";
$subject=$_POST['subject'];
$sql="INSERT INTO friends(user_id,status,subject,friend_id)" ."VALUES('$user_id','yes','$subject','$friend_id') ";
if($mysqli->query($sql)=== true) {
$_SESSION['status']="yes";
$_SESSION['friend_id']=$friend_id;
$_SESSION['user_id'] = $user_id;
} else {
}
}?>
</body>
</html>
Your return statements terminate the function; no code after the return will execute, so your form.submit() calls never happen. In your friend function, because you're returning false and your onclick has return friend(...), you're cancelling form submission, and the form is never submitted (not by your code, and not by the browser), In unfriend, though, you're returning true, so although your code doesn't submit the form, the browser does.
If you want to submit the form programatically, put those form.submit calls before the return, and return false so the browser doesn't also submit the form.
I'm trying to make a website that automatically uses this script to get amount of bitcoin in an wallet :
<?php
$address = $_GET["address"];
$satbalance = file_get_contents('https://blockchain.info/q/addressbalance/'.$address.'');
$btcbal = ($satbalance) / 100000000;
echo $btcbal;
?>
and I'm trying to make page that has my clients username and password in textarea box and when I enter the bitcoin wallet address from my user to check the balance from multiple input boxes and show the value in the box in front of address box.
Image of the page that needs this job done
How can I get the response from the form and display in another box or variable.
Thanks.
Wrap the fields in a form tag and submit to the same page.
Using your code example, this example show a simple form and handling the POST with PHP. This hasn't been tested but is an example of how to handle a post using the $_POST super global.
<?php
$btcbal = null;
// Check if there is POST data
if (!empty($_POST)) {
$address = $_POST['address'];
$satbalance = file_get_contents('https://blockchain.info/q/addressbalance/'.$address.'');
$btcbal = ($satbalance) / 100000000;
}
?>
<form method="post">
<input type="text" name="username">
<input type="password" name="password">
<input type="text" name="btc_address">
<button type="submit">Submit</button>
</form>
<p>Balance: <?php echo $btcbal ? $btcbal : 'N/A'; ?></p>
So far i have such code
<form action="register.php" target="login" type=post>
<label for="name">Account </label><br><br>
<input type=text id="name" name="account" size=20 maxlength=<?php Echo MaxNameLength; ?> /><br><br>
<label for="name">Password</label><br><br>
<input type=text id="name" name="password" size=20 maxlength=<?php Echo MaxNameLength; ?> /><br><br>
<button type=submit>Register</button>
</form>
I placed it inside an IFrame but when i try to use php with such code:
<?php
If (IsSet($_GET["account"]["password"])) { $Account = $_GET["account"]; $Password = $_GET["password"];
$AllRight = True;
For ($I=0; $I<StrLen(WrongChars); $I++) {
If (StrPos($Account, SubStr(WrongChars,$I,1))) {
Echo "<p>Your Name musn't contain the char \"".SubStr(WrongChars,$I,1)."\"</p>";
$AllRight = False;
}
}
If (file_exists(AccountFilesPath.$Account.AccountFilesEnding)) {
Echo "<p>This Account already exists!</p>";
$AllRight = False;
}
If ($AllRight) {
$Text .= "$Password ";
File_Put_Contents (AccountFilesPath.$Account.AccountFilesEnding, $Text);
if(!file_exists(AccountFilesPath.$Account.AccountFilesEnding)) {
echo "<p>Error during account cration!</p>";
}
Echo "<p>This Account is created succesfully!</p>";
}
}
?>
yet the responce im getting is a fresh registration page with no work done...
i want my iframe to individually register text files like (user1.txt) with ($Password) inside. Along with having a link to the login, and upon login have a User Control Panel.
I don't understand why you are using an iframe for this but I can see that you use $_GET in your php when your form submits $_POST (type="post")
Try changing that in your PHP code and see if it works
Edit*
As stated in the comments this is not a $_GET index $_GET["account"]["password"]
Let's say you stick with POST since your html form submits a POST,you must use something like this:
if(isset($_POST["account"]) && isset($_POST["password"]))
And to be sure what variables you get from your form, I recommend you to print your Post array before any manipulation.
print_r($_POST);
I have a form.php file that redirects to a sendformdata.php file when I submit the form. However, I can't get the sendformdata.php file to display an error message within the form when the proper fields aren't filled out.
I am simply redirected to the include file, db_connect.php, which shows up as a blank page. How can I get the page to stay on form.php and display an error message in html? This is my current sendformdata.php file:
<?php
include_once('db_connect.php');
$lokotitle = $description = $category = $showyourname = $yourname = $lat = $lng = "";
if($_SERVER['REQUEST_METHOD'] == 'POST'){
$lokotitle=$_POST['lokotitle'];
$description=$_POST['description'];
$category=$_POST['category'];
$showyourname=$_POST['showyourname'];
$yourname=$_POST['yourname'];
$lat=$_POST['lat'];
$lng=$_POST['lng'];
// Validation will be added here
if(empty($lokotitle)) {
$error_message = "Please input a Loko title.";
?><script>$('#notitle'.text($error_message));</script><?php
exit;
}
if(!isset($error_message)){
//Inserting record in table using INSERT query
$insqDbtb="INSERT INTO `new`.`web_form`
(`lokotitle`, `description`, `category`, `showyourname`, `yourname`, `lat`, `lng`) VALUES ('$lokotitle', '$description', '$category', '$showyourname', '$yourname', '$lat', '$lng')";
mysqli_query($link,$insqDbtb) or die(mysqli_error($link));
?><script>window.location.href = "../index.php"; </script> <?php
exit;
}
}
?>
This is a section of form.php that I am trying to display an error message in:
<form class="form-horizontal" role="form" action="handleform/sendformdata.php" method="POST">
<legend></legend>
<div class="form-group">
<label for="lokotitle" class="col-sm-2">Loko Title</label>
<div class="col-sm-4">
<input type="text" class="form-control" name="lokotitle" id="lokotitle" placeholder="Title">
<span id="notitle"></span>
</div>
Thanks in advance for the help!
I recommend you to use both html5 required attribute which will force the user to enter the data. But remember the user can bypass front end validation (by means of inspect element), hence back end validation is also necessary.
Use required attribute like:
<input type="text" required />
You can try this
if(empty($lokotitle)) {
$error_message = "Please input a Loko title.";
echo "<script>
document.getElementById('#notitle').value='".$error_message."';".
"</script>";
exit;
}
Let me know if this solves your problem