alert box in PHP and navigation to another page - javascript

I am using javascript to check whether username and password are not empty. If one of these is empty, javascript alert is displayed and PHP script should not work, that is username and password validation should not occur and login page should be displayed once again. Is there any simple code to do this?
Nobody need to build whole form. I have already build login form and PHP script for its validation, I just want to know is there any method or function in PHP to stop script on entering empty username/password and submitting

Try This
Php Code :
<p>
<label for="first">User Name:</label>
<input type="text" name="First Name" id="first" />
</p>
<p>
<label for="last">Password:</label>
<input type="text" name="Last Name" id="last" />
</p>
<input type="submit" name="Submit" id="button2" value="Submit" onClick="javascript:verify()"/>
JavaScript Code :
function verify() {
if (document.getElementById('first').value=="") {
alert("Please Enter Your Name");
return false;
}
else if (document.getElementById('last').value=="") {
alert("Please Enter Your Password");
return false;
}
else {
document.form.submit();
}
}
Working Model : http://jsfiddle.net/NWWL4/24/

It took me awhile to get this right. I have my form in my html index
page. On a closed question here, I read this couldn't be done.
This php works VERY well with my form.
It generates a Javascript alert for good and bad results and
links back to the index page in either instance.
If you look at the 2nd echo, you'll see where you can redirect to
another page. I just loaded same page to clear form.
If you want to see the ccs, just ask.
PHP:
<?php
if(isset($_POST['submit'])) {
$to = "admin#blahblah.com";
$name_field = $_POST['name'];
$email_field = $_POST['email'];
$subject_field = $_POST['subject'];
$message = $_POST['message'];
$body = "From: $name_field\n E-Mail: $email_field:\n Subject: $subject_field\n Message: $message\n";
}
if(empty($name_field) || empty($email_field) || empty($subject_field) || empty($message)) {
echo '<script type="text/javascript">alert("There is a problem, please check the fields");window.history.go(-1);</script>';
}
else {
if(mail($to, $subject_field, $body)) {
echo '<script type="text/javascript">alert("Message successfully sent");window.location = "https://www.blahblah.com/";</script>';
}}
exit;
?>
html:
<div class="clear"></div>
<div class="container">
<div class="row">
<div class="col-md-3">
<form role="form" action="php\mailer.php" method="post" id="form">
<div class="form-group">
<input name="name" type="text" class="form-control" id="name" placeholder="Your Name" maxlength="30">
</div>
<div class="form-group">
<input name="email" type="text" class="form-control" id="email" placeholder="Your Email" maxlength="30">
</div>
<div class="form-group">
<input name="subject" type="text" class="form-control" id="subject" placeholder="Your Subject" maxlength="40">
</div>
<div><input type="submit" name="submit" class="btn btn-primary" value="Send Message"></input></div>
</div>
<div class="col-md-9">
<div class="txtarea">
<textarea name="message" rows="10" class="form-control" id="message"></textarea>
</form>
<div class="clear"></div>
<div class="col-lg-12" style="text-align:center">
<a class="btn btn-large btn-contact-link" href="#blahblah_home">Home</a>

Related

Stop the page to refresh after the form button is clicked and error is shown

I have seen other questions too but i want to stop my page from refreshing after signup form is filled and with validation from php it shows an error in a span. or not refreshing the form data or not clearing the form data will also work. I just want the form data to be exact as it is but the error to be shown. please find the code
<form action="signup.php" id="form" method="POST" onsubmit="">
<a style="text-decoration:none ;" href="index.php"><h1 >Mero <span>Notes</span></h1></a>
<h3>Register Your Account</h3>
<?php
echo '<p style="margin-top:10px;color:red;">'.$message.'</p>';
?>
<p id="validationSpan"></p>
<input placeholder="Full Name" type="text" required="required" name="fullName" value=""/>
<input placeholder="Email" type="text" required="required" name="email" />
<input placeholder="Password" type="password" name="password" required="required" id="id_password" minlength="8" onkeyup="passValidation();"/>
<input placeholder="Confirm Password" type="password" name="conPassword" required="required" id="id_conPassword" onkeyup="passValidation();"/>
<input placeholder="Contact" type="number" required="required" name="contactNum" />
<button type="submit" class="regButton" type="submit" value="Sign Up" id="regBtn" onclick="return passValidationAlert()">SignUp </button>
<h4 style="text-align: right; color:black;font-size:12px;">
Already Have an Account ?
<a class="buttomLogin" href="index.php">Login here</a>
</h4>
</form>
The php code looks like this
if(mysqli_num_rows($result)>0){
$_SESSION['error']=true;
$message='The Entered Email is Already Taken';
}
elseif($password!=$confirmPassword){
$message='Password did not match';
}
{
$epassword=password_hash($password,PASSWORD_BCRYPT);
$sql = "INSERT INTO signupdatabasemn (fullName, email, password, phoneNumber)
VALUES ( '$fullName', '$email', '$epassword', $phoneNumber) ";
$result2= mysqli_query($conn, $sql);
if ($result2>0) {
header('Location: /demosite3fnl/index.php');
} else {
}
}
?>
The simplest solution would be to put the post data in the input value so that when page get refreshed, it stays where it should be. In example:
<input placeholder="Email" type="text" required="required" name="email" value="<?= $_POST['email'] ?>"/>
Updated. Just seen your updated code. Looks like form is sending request to different php file. In this case, try return posted data using get. See more here

Javascript doesn't run in PHP

I tried to look in other similar posts but apparently, I did something wrong somewhere without me noticing it as my PHP, HTML and JavaScript skills are very outdated. Last I touched these things was last year, so a lot of my fault detection skills are rusty.
That being said, the piece of code I'm trying to do is structured like this
<?PHP //If?>
JS //Script to check if input is empty and prevents submission
HTML <!--Input Forms-->
<?PHP //DB actions ?>
As far as I can do, the syntax of the PHP seems correct (used php formatter to check if my syntax is wrong). The problem here is the javascript portion does not even run. And if it runs, the remainder of the UI (login form) disappears for no reason (when input is supplied).
Below is the code I'm using.
<?php
if(empty($_POST["username"]) && empty($_POST["password"])){
?>
<script type="text/javacsript">
function checkField()
{
if((login-form.username.value == "") || (login-form.password.value == ""))
{
alert("Please fill in both Username and Password fields");
return false;
}
else
return true;
}
</script>
<div class="panel-body">
<form role="form" id="login-form" action="login.php" method="post" onsubmit="return checkField();">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" id="username" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" id="password" type="password" value="">
</div>
<!-- Change this to a button or input when using this as a form -->
<!--Login-->
<div class="form-group">
<button class="btn btn-lg btn-success btn-block" type="submit">Login</button>
</div>
</fieldset>
</form>
</div>
<?php
}else {
$message = "wrong answer";
echo "1<script type='text/javascript'>alert('$message');</script>";
}
?>
JavaScript for onsubmit is the main concern here. It does not even run when the supposed true condition is triggered (when either of the inputs are empty or both are empty). And the secondary script below, is just my initial test run before supplying the database portion.
Edit 1
Alt code for checkField() using getElementById
<script type="text/javacsript">
function checkField()
{
if((document.getElementById("username").value == "") || (document.getElementById("password").value == ""))
{
alert("Please fill in both Username and Password fields");
return false;
}
else
return true;
}
</script>
Edit 2
After resolving the typo, the PHP portion which is triggered when both login and password fields are not empty does not run at all. The action attribute might have a hand
<form role="form" id="login_form" action="" method="post" onsubmit="return checkField();">
The code above is to test if the action attribute is the culprit. Still the result is the same. The page will reload with empty fields.
Latest code
<?php
if(empty($_POST["username"]) && empty($_POST["password"])){
?>
<script type="text/javascript">
function checkField()
{
if((document.getElementById("username").value == "") || (document.getElementById("password").value == ""))
{
alert("Please fill in both Username and Password fields");
return false;
}
else
return true;
}
</script>
<div class="panel-body">
<form role="form" id="login_form" action="" method="post" onsubmit="return checkField();">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" id="username" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" id="password" type="password" value="">
</div>
<!-- Change this to a button or input when using this as a form -->
<!--Login-->
<div class="form-group">
<button class="btn btn-lg btn-success btn-block" type="submit">Login</button>
</div>
</fieldset>
</form>
</div>
<?php
}else {
$conn = mysqli_connect("localhost","root","rootacc","test");
if($conn)
{
echo "success";
header("LOCATION:tables.html");
}
}
?>
Edit 3
All problems resolved. Sorry for the newbie question, thank you for all who contributed. Here's the corrected code
<?php
if(empty($_POST["username"]) && empty($_POST["password"])){
?>
<script type="text/javascript">
function checkField()
{
if((document.getElementById("username").value == "") || (document.getElementById("password").value == ""))
{
alert("Please fill in both Username and Password fields");
return false;
}
else
return true;
}
</script>
<div class="panel-body">
<form role="form" id="login_form" action="" method="post" onsubmit="return checkField();">
<fieldset>
<div class="form-group">
<input class="form-control" placeholder="Username" id="username" name="username" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" id="password" name="password" type="password" value="">
</div>
<!-- Change this to a button or input when using this as a form -->
<!--Login-->
<div class="form-group">
<button class="btn btn-lg btn-success btn-block" type="submit">Login</button>
</div>
</fieldset>
</form>
</div>
<?php
}else {
$conn = mysqli_connect("localhost","root","rootacc","test");
if($conn)
{
echo "success";
header("LOCATION:tables.html");
}
}
?>
Issue 1 is due to my own programming sloppiness (using dash instead of other styles of variable referencing) as well as the lack of knowledge on getElementById
Issue 2 is due to my own typo which wasn't spotted.
Issue 3 is due to the lack of understanding on id and name (seems the same)
All recommendation to fix the issues are implemented.
The post parameters are not set, that may be the reason it's not going to ELSE condition.
<div class="form-group">
<input class="form-control" placeholder="Username" id="username" name="username" type="text" autofocus>
</div>
<div class="form-group">
<input class="form-control" placeholder="Password" id="password" name="password" type="password" value="">
</div>
Use, "name" attribute to set the POST parameters.

How do you prevent an input type=submit from closing a modal?

I have a modal that contains a form
<form method="post">
<div class="form-group">
<label for="name">Your Name:</label>
<input type="text" name="name" class="form-control" placeholder="Your Name"
value="<?php echo $_SESSION['post-data']['name']; ?>" />
</div>
<div class="form-group">
<label for="email">Your Email:</label>
<input type="email" name="email" class="form-control" placeholder="Your Email"
value="<?php echo $_SESSION['post-data']['email']; ?>" />
</div>
<div class="form-group">
<label for="comment">Your Comment:</label>
<textarea class="form-control" name="comment"><?php echo $_SESSION['post-data']['comment']; ?></textarea>
</div>
<div class="modal-footer">
<input type="submit" name="submit" class="btn" value="Submit"/>
</div>
</form>
The PHP runs fine when the submit button is pressed and emails are sending.
The PHP
<?php
$_SESSION['post-data'] = $_POST;
if ($_POST["submit"]) {
if (!$_POST['name']) {
$error="<br />Please enter your name";
}
if (!$_POST['email']) {
$error.="<br />Please enter your email address";
}
if (!$_POST['comment']) {
$error.="<br />Please enter a comment";
}
if ($_POST['email']!="" AND !filter_var($_POST['email'],
FILTER_VALIDATE_EMAIL)) {
$error.="<br />Please enter a valid email address";
}
if ($error) {
$result='<div class="alert alert-danger"><strong>There were error(s)
in your form:</strong>'.$error.'</div>';
} else {
if (mail("myemail", "Comment from website", "Name: ".
$_POST['name']."
Email: ".$_POST['email']."
Comment: ".$_POST['comment']))
{
$result='<div class="alert alert-success"><strong>Thank
you!</strong> I\'ll be in touch.</div>';
unset($_SESSION['post-data']['name']);
unset($_SESSION['post-data']['email']);
unset($_SESSION['post-data']['comment']);
} else {
$result='<div class="alert alert-danger">Sorry, there was
an error sending your message. Please try again later.</div>';
}
}
}
?>
however I would like the Modal to remain open after the submit button is clicked. I have searched all over SO and most related questions suggest using
**data-backdrop="static"**
but that has not worked. I believe it may be because it is an input and not a button but I am not sure.
you could either use ajax, then you submit without redirecting, and get the result data and do whatever you want with it.
http://www.w3schools.com/ajax/
the other thing you could do is to use javascript to open the modal if a post is there on the file. basically echo a javascript command that would open the modal again.

problems resetting a form using php

I have a contact form which sends an email once submitted and displays an alert successfully when sent. My problem was 1) after its sent the email form still has content. 2) If I refresh the page the email is sent again with the previous details. In order to solve this I used the below code in php which is doing the job of refreshing with out sending an email.
header("Location: contact.php");
exit;
Now my problem is The alert is not displayed anymore which is true because the alert is in my HTML and header refreshes the page and it never reaches the alert in HTML(displayed using php echo). Here is the HTML Code :
<div class="container">
<div class="row">
<div class="col-md-6 col-md-offset-3" id="emailForm">
<h1 class="center">Email Form</h1>
<?php echo $result; //header( "Location: contact.php"); //exit; ?>
<p>Please get in touch ! I will get back to you as soon as I can !!</p>
<form method="post" id="contactForm">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" name="name" class="form-control" placeholder="Your Name" value="<?php echo $_POST['name'] ?>" />
</div>
<div class="form-group">
<label for="email">Your Email</label>
<input type="email" name="email" class="form-control" placeholder="Your Email" value="<?php echo $_POST['email'] ?>" />
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" name="message">
<?php echo $_POST[ 'message'] ?>
</textarea>
</div>
<input type="submit" name="submit" id="send" class="btn btn-success btn-lg center" value="Submit" />
</form>
</div>
</div>
</div>
Here is the PHP code:
<?php
if($_POST['submit']) {
if(!$_POST['name']){
$error.="<br>Please enter your name";
}
if(!$_POST['email']){
$error.="<br>Please enter your email address";
}
if(!$_POST['message']){
$error.="<br>Please enter a message";
}
if ($_POST['email']!= "" AND !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
$error.="<br>Please enter a valid email address";
}
if( $error )
{
$result='<div class="alert alert-danger"><strong>There were error(s):'.$error.'</strong></div>';
}
else {
if(mail("madistackcloud#gmail.com","Message from Deepak", "Name: ".$_POST['name']."Email: ".$_POST['email']."Message: ".$_POST['message'])) {
$result='<div class="alert alert-success alert-dismissible"><strong>Thank you! I\'ll be in touch.</strong></div>';
}
else
{
$result='<div class="alert alert-danger alert-dismissible"><strong>Oops! Something went wrong. Please try again !</strong></div>';
}
}
}
?>
Is there any workaround for this or any other method which can do the job. Kindly help.
Change your form to
<form method="post" id="contactForm">
<div class="form-group">
<label for="name">Your Name</label>
<input type="text" name="name" class="form-control" placeholder="Your Name" value="" />
</div>
<div class="form-group">
<label for="email">Your Email</label>
<input type="email" name="email" class="form-control" placeholder="Your Email" value="" />
</div>
<div class="form-group">
<label for="message">Message</label>
<textarea class="form-control" name="message"></textarea>
</div>
<input type="submit" name="submit" id="send" class="btn btn-success btn-lg center" value="Submit" />
</form>
If you don't want to show the content sent, dont use echo $POST on the value of the inputs.
You're always echoing the post data in the html section. You only want to echo data if there is an error.
value="<?php echo $_POST['name'] ?>"
in the control code above do something like
$name = cleanInput($_POST['name']);
$email = cleanInput($_POST['name']);
// etc...
Then in your
if( $error )
...
else
{
$name = "";
$email = "";
sendMail();
// etc...
and then back in your html:
value="<?php echo $name; ?>"
Why do you do this: value="<?php echo $_POST['email']? This sets the value of the input field to what the user inputted. This means next time you load your page this value is visible and thus will be emailed when transmitted.

Php/javascript email form and validation

So I have the JavaScript code which validates the first name field, I am adding more validation once I have worked this out.
So basically if the field is not filled in, return false.
If it is return true and continue to email.php to send the email. Only problem is its not sending the email to the set address. I am confused as to where I have gone wrong.
The JavaScript is working when the field is empty, and when it has an input. Help.
PS: I have removed email address for privacy purposes.
JavaScript on contact.html:
<script>
function validateForm() {
if (document.forms['email'].fname.value == ""){
alert("First name must be filled out");
return false;
}
else{
alert("Thank you! Your message was recieved!");
return true;
}
};
</script>
Html form on contact.html
<form id="email" name="email" onsubmit="return validateForm(this)" action="email.php" method="post" >
<div id="form_fname">
<label for="fname"><img src="images/firstname.png" width="94" height="17" alt="first name" /></label>
<input type="text" name="fname" id="fname" />
</div>
<div id="form_lname">
<label for="lname"><img src="images/lastname.png" width="89" height="17" alt="last name" /></label>
<input type="text" name="lname" id="lname" />
</div>
<div id="form_email">
<label for="email"><img src="images/email.png" width="53" height="17" alt="email" /></label>
<input type="text" name="email" id="email" />
</div>
<div id="form_message">
<label for="Message"><img src="images/message.png" width="77" height="17" alt="message" /></label>
<textarea name="message" id="message" cols="45" rows="5"></textarea>
</div>
<div id="form_submit">
<input type="submit" name="submit" id="submit" value=""/>
</div>
</form>
Php in email.php
<?php
if(isset($_POST['email'])) {
// Email and subject.
$email_to = "emailaddress";
$email_subject = "Mint Makeup & Beauty Enquiry";
$fname = $_POST['fname']; // required
$lname = $_POST['lname']; // required
$message = $_POST['message']; // required
$email_from = $_POST['email']; // required
// create email content
$email_content = "From:"." ".$fname." ".$lname."\n"."Email:"." ".$email_from."\n"."Message:"." ".$message;
//mail
mail($email_to, $email_subject, $email_content);
}
//return to contact page after submit.
header("location:contact.html");
?>
In your form id="email" is conflicting with input id="email"
You can use HTML5 attributes for form validation (in HTML5 supported browsers)
http://www.the-art-of-web.com/html/html5-form-validation/#.UnDpBHMW3eU
Code
<?php
if(isset($_POST['submit'])) {
print_r($_POST);
die;
$email_to = "emailaddress";
$email_subject = "Mint Makeup & Beauty Enquiry";
$fname = $_POST['fname']; // required
$lname = $_POST['lname']; // required
$message = $_POST['message']; // required
$email_from = $_POST['email']; // required
// create email content
$email_content = "From:"." ".$fname." ".$lname."\n"."Email:"." ".$email_from."\n"."Message:"." ".$message;
mail($email_to, $email_subject, $email_content);
}
?>
<!DOCTYPE html>
<html lang="en">
<head>
<script type="text/javascript">
function validateForm() {
var error = false;
var error_string = 'Please correct the following errors:\n\n';
if (document.getElementById('fname').value == ""){
error_string += "--> First name must be filled out.\n";
error = true;
}
if (document.getElementById('lname').value == ""){
error_string += "--> Last name must be filled out.\n";
error = true;
}
if (document.getElementById('email').value == ""){
error_string += "--> Email must be filled out.\n";
error = true;
}
if(error){
alert(error_string);
return false;
} else {
return true;
}
}
</script>
</head>
<body>
<form onsubmit="return validateForm(this)" action="" method="post" >
<div id="form_fname">
<label for="fname"><img src="images/firstname.png" width="94" height="17" alt="first name" /></label>
<input type="text" name="fname" id="fname" />
</div>
<div id="form_lname">
<label for="lname"><img src="images/lastname.png" width="89" height="17" alt="last name" /></label>
<input type="text" name="lname" id="lname" />
</div>
<div id="form_email">
<label for="email"><img src="images/email.png" width="53" height="17" alt="email" /></label>
<input type="text" name="email" id="email" />
</div>
<div id="form_message">
<label for="Message"><img src="images/message.png" width="77" height="17" alt="message" /></label>
<textarea name="message" id="message" cols="45" rows="5"></textarea>
</div>
<div id="form_submit">
<input type="submit" name="submit" id="submit" value="Submit" />
</div>
</form>
</body>
</html>
I just showed you how client side validation works and form is posting correctly.. You should always use server side validation..
Try
document.forms["email"]["fname"].value
instead
document.forms['email'].fname.value
Also you can get field this way:
document.getElementById('fname').value

Categories