PHP form handling- display error message using javascript - javascript

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

Related

Onclick alert works even if the form is empty? and after clicking on submit button alert shows 1st then it shows that the input field is required

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>

Getting response from sending form in textbox

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>

How to display javascript alert without reset form

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">

Handle HTML <input> Attribute [duplicate]

This question already has answers here:
How to get input field value using PHP
(7 answers)
Closed 6 years ago.
I am writing basic user register page,
My register page contain : usermail ,password, plan type.
There are three plans for plan type.
Three plans are: basic, sliver and gold.
The register_main.php is to store user information in Mysql.
I met issue that is when I click basic or sliver or gold plan, the page will go to register_main page .
I want sent user information only to server ,when they click sign in.
Can anyone help me to solve this issue?
HTML Code:
<html>
<head>
<title>Register</title>
<meta charset="UTF-8">
<!-- Include JS File Here -->
<script src="Script/register_validate.js">
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<script type="text/javascript"
src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.9.2/jquery-ui.min.js"></script>
</script>
</head>
<body>
<form name="registerform" action="register_main.php" method="post" onsubmit="return validate()">
<p id="benefits_text" class="white size_8">Benefits:</p>
<input id="type_basic" type ="image" name="basicPlan" " src="basic.png">
<input id="type_silver" type ="image" name="silverPlan" " src="silver.png">
<input id="type_gold" type ="image" name="goldPlan" " src="gold.png">
<div id="userinfo_content">
<p id="email_text" class="white size_8">Email Address</p>
<input id="email_input" name="userEmail" type="text"class="sign_input">
<p id="password_text" class="white size_8">Password</p>
<input id="password_input" name="password" type="password">
<p id="confirmPW_text" class="white size_8">Confirm Password</p>
<input id="confirmPW_input" name="confirm_password" type="password">
<input id="btn_signin" type ="image" alt ="submit" src="signin.png">
</div>
</form></body>
</html>
register_main.php
include ("config.php");
require ("encrypt.php");
session_start ();
if ($_SERVER ["REQUEST_METHOD"] == "POST") {
// Get userEmail from client side and create a legal SQL string that you can use in an SQL statement.
$user_emailaddress = mysqli_real_escape_string ( $db, $_POST ['userEmail'] );
// Get password from client side and create a legal SQL string that you can use in an SQL statement.
$user_password = mysqli_real_escape_string ( $db, $_POST ['password'] );
// Get planType from client side and create a legal SQL string that you can use in an SQL statement.
$user_planType = mysqli_real_escape_string ( $db, $_POST ['planType'] );
// Create user.
// Note user Id is generated when a new record is inserted into a table.
$sql = "INSERT INTO admin (emailAddress,passcode,planType) VALUES ('$user_emailaddress','$user_Newpassword','$user_planType')";
$result = mysqli_query ( $db, $sql );
// if create user a successfully, jump to welcome page.
// otherwise print error information
if ($result ) {
echo "New record created successfully";
$_SESSION ['login_user'] = $user_emailaddress;
header ( "location: welcome.php" );
} else {
echo "Error: " . $sql . "<br>" . mysqli_error ( $db );
}
// Close Database
mysqli_close ( $db );
}
?>
the problem with your form is that the input tag with type="image" acts as a submit button when clicked. Check out this link: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/input/image.
I guess that in your use case, you want these images to act as selection buttons for the available plan types. So I think you could replace then for an image tag with a radio button, or a select input with the three plans.

How to make a complete Iframe registration / login / userpanel

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);

Categories

Resources