How to validate a form in a bootstrap modal using PHP? - javascript

As soon as the form is submitted, the form is not validated and the modal is closed because the page is refreshed. I want the modal to stay open on submitting the form. The php is given below:
<?php
$nameerror = $studentiderror = $emailerror = "";
$subject = "Thank you for voting!";
$body = "Dear $_POST["name"], Thank you for voting for this sustainable initiative. Your vote is appreciated! Lots of love from the Beefarm Committee of the Erasmus Sustainability Hub!";
if ($_SERVER["REQUEST_METHOD"] == "POST") {
if ($_POST["submit"]) {
if (empty(($_POST["name"])) {
$nameerror = "Please enter your name" }
if (empty($_POST["studentID"])) {
$studentiderror .= "Please enter your student ID";
} else {
$result = "Thank you for voting!";
mail($_POST["email"], $subject, $body);
}
};
}
Here is the HTML of the modal, the PHP is embedded in the HTML, where the error messages should be shown when the form is validated after submission:
<div class="container">
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button class="close" data-dismiss="modal">x</button>
<h4 class="modal-title">Vote!</h4>
</div>
<div class="modal-body">
<p>
Let us know what you think! <br/>
By voting, you as a student can have a say in the realisation of this project. Even if you vote
against having bees on campus, your vote is appreciated! <br/>
Thank you!
</p>
<form id="votingscreen" method="POST">
<?php echo $result ?>
<div class="form-group">
<label for="name">Name</label>
<?php echo $nameerror ?>
<input style="width: 180px" type="text" id="name" name="name" class="form-control" placeholder="Your name">
</div>
<div class="form-group">
<label for="studentID">Student ID</label>
<?php echo $studentiderror ?>
<input style="width: 180px" type="text" id="studentID" name="studentID" class="form-control" placeholder="123456AB">
</div>
<div class="form-group">
<label for="email">E-mail</label>
<?php echo $emailerror ?>
<input style="width: 180px" type="email" id="email" name="email" class="form-control" placeholder="E-mail">
</div>
<hr />
<div class="radiogroup">
<label for="radiogroup"> Bees on campus? </label>
<label class="radio-inline">
<input type="radio" name="vote" id="voteyesradio" value="yes" checked>
Yes
</label>
<label class="radio-inline">
<input type="radio" name="vote" id="votenoradio" value="no">
No
</label>
</div>
<div class="form-group">
<input type="submit" name="submit" id="submitButton" class="btn btn-success btn-block" value="Vote!"/>
</div>
</form>
</div>
</div>
</div>
</div>
</div>
This is the JS code:
$(".contentContainer").css("min-height", $(window).height());
$("#image").css("min-height", $("#beeweek").height());
$(document).ready(function () {
$("#submitButton").click(function () {
$("#myModal").modal('show');
})
});
$(".video-container").css("min-height", $(window).height());

If you don't want the page being refreshed, you should submit your form using Ajax, this link should help you, jQuery Ajax POST example with PHP

Related

Having problem submitting a form without reload using jquery ajax

When i submit form it doesnot update value in database mysql.Its a form written in php.
here is my php and html. I want that the form should not reload and it must submit the changes in database without reloading the page and show preloader for 1 sec on submitting form.
HTML,PHP AND ACTION of form: Here action is the current page where this form is avalilable
detail_customer.php
<?php
$server = "localhost";
$username = "root";
$pass = "";
$dbname = "stinkspolitics_pl";
$conn = mysqli_connect($server, $username, $pass, $dbname);
if (isset($_GET['detail_customer'])) {
$quest_id = $_GET['detail_customer'];
$get_quest = "SELECT * FROM questions WHERE quest_id = '$quest_id'";
$getting_quest = mysqli_query($conn, $get_quest);
while ($row = mysqli_fetch_assoc($getting_quest)) {
$quest_title = $row['quest_title'];
$category_id = $row['category_id'];
}
}
if (isset($_POST['submit'])) {
$quest_t = $_POST['quest_t'];
$update = "UPDATE questions SET quest_title = '$quest_t' WHERE quest_id = '$quest_id'";
$run_update = mysqli_query($conn, $update);
if ($run_update) {
echo 'hello';
}
}
?>
<div class="recent-orders cust_det ">
<h2> Customer Detail</h2>
<div class="customer_detail">
<form id="form-submit" action="./inc/detail_customer.php
" method="POST" class="c_form animate__animated animate__fadeIn">
<div class='alert alert-success'>
<strong>Success!</strong> Your question has been submitted.
</div>
<div class='alert alert-danger'>
<strong>Sorry!</strong> Your question has not been submitted.
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="cat_id" value="<?php echo $category_id ?>" id="cat_id">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="quest_t" value="<?php echo $quest_title ?>" id="quest_t">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<input name="submit" type="hidden" />
<input class="btn-primary submit-btn" type="submit" name="" value="Submit">
</div>
</form>
</div>
</div>
JS Code
index.js
$("#form-submit").on("submit", function () {
// e.preventDefault();
var form = $(this);
var formData = form.serialize();
$.ajax({
type: "POST",
url: form.attr("action"),
data: formData,
success: function (data) {
$(".alert-success").show();
$(".alert-success").fadeOut(4000);
console.log(data);
},
error: function (data) {
$(".alert-danger").show();
$(".alert-danger").fadeOut(4000);
console.log(data);
},
});
return false;
});
Ajax Success Response But not updating data in mySQL
<div class="recent-orders cust_det ">
<h2> Customer Detail</h2>
<div class="customer_detail">
<form id="form-submit" action="./inc/detail_customer.php" method="POST"
class="c_form animate__animated animate__fadeIn">
<div class='alert alert-success'>
<strong>Success!</strong> Your question has been submitted.
</div>
<div class='alert alert-danger'>
<strong>Sorry!</strong> Your question has not been submitted.
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="cat_id" value="<br />
<b>Warning</b>: Undefined variable $category_id in <b>C:\xampp\htdocs\admin_panel\inc\detail_customer.php</b> on line <b>62</b><br />
" id="cat_id">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="quest_t" value="<br />
<b>Warning</b>: Undefined variable $quest_title in <b>C:\xampp\htdocs\admin_panel\inc\detail_customer.php</b> on line <b>66</b><br />
" id="quest_t">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<div class="c_detail">
<label for="" class="form-labels">Name</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">Contact</label>
<input type="text" name="" id="">
</div>
<div class="c_detail">
<label for="" class="form-labels">City</label>
<input type="text" name="" id="">
</div>
</div>
<div class="row">
<input name="submit" type="hidden" />
<input class="btn-primary submit-btn" type="submit" name="" value="Submit">
</div>
</form>
</div>
</div>
The condition if (isset($_POST['submit'])) { will never evaluate to true, since there is no input element in the form with name="submit" (the button with name='submit' does not send the attribute by default).
Either change the condition:
if (isset($_POST['quest_t'])) { ...
Or, include an input element with name='submit', for example:
<input name="submit" type="hidden" />
Also, make sure to move the $_POST check at the beginning of the file and ensure that no other code will be evaluated in the PHP file (e.g. the rest of the HTML code) if a POST request has been received.
Just return false after at the end of the method.
jQuery has its own way of ensuring "preventDefault()" and it is just returning false from the submit handler.
Full background on this here:
event.preventDefault() vs. return false
Issue has been solved. By changing path and then putting path of js file again.

How to submit a contact form with Google recaptcha v2 and PHP with a Boostrap success alert

I have a contact form on a website, and I am trying to submit the form using Google recaptcha v2, (select the boxes which have a certain image in them). At the moment, the form successfully sends and is received exactly as I want it to; however, I want to create a 'success' alert using Bootstrap, but for some reason this is not working.
If you take a look at the last part of my PHP file I have the following code snippet:
if($responseKeys["success"]) {
mail($to,$email_subject,$email_body,$headers);
} else {
echo '<h2>This has been unsuccessful according to our security checks</h2>';
}
And the 'mail' command seems to work. But anything else I try to put in there, for example
echo '<h2>success!</h2>'
for example, it doesn't get rendered. Ideally, upon a success submit I would like the following to take place:
The form to refresh to blank
A success alert using Bootstrap show at the top of the page
But I am having trouble implementing these.
Here is the entire PHP file:
<?php
$Fname = $_POST['Fname'];
$Lname = $_POST['Lname'];
$email = $_POST['email'];
$number = $_POST['number'];
$company = $_POST['company'];
$message = $_POST['message'];
$email_from = "Your website";
$email_subject = "You have a new submission form from Your Website";
$email_body = "First Name: $Fname.\n".
"Last Name: $Lname.\n".
"Email Address: $email.\n".
"Telephone Number: $number.\n".
"Company Name: $company.\n".
"Message: $message.\n";
$to = "hello#yourwebsite.co.uk";
$headers = "From: $email_from \r\n";
$headers .= "Reply-To: $email \r\n";
$captcha;
if(isset($_POST['email'])){
$email=$_POST['email'];
}
if(isset($_POST['message'])){
$message=$_POST['message'];
}
if(isset($_POST['g-recaptcha-response'])){
$captcha=$_POST['g-recaptcha-response'];
}
if(!$captcha){
echo '<h2>Please check the "I am not a robot" checkbox"</h2>';
exit;
}
$secretKey = 'somesecretlettersandnumbers';
$ip = $_SERVER['REMOTE_ADDR'];
// post request to the server
$url = 'https://www.google.com/recaptcha/api/siteverify?secret=' . urlencode($secretKey) . '&response=' . urlencode($captcha);
$response = file_get_contents($url);
$responseKeys = json_decode($response, true);
// should return JSON with success as true
if($responseKeys["success"]) {
mail($to,$email_subject,$email_body,$headers);
} else {
echo '<h2>This has been unsuccessful according to our security checks</h2>';
}
?>
And here is the HTML form:
<form action="contact.php" id="contact-form" method="POST" role="form">
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_name">First Name*</label>
<input id="form_name" type="text" class="form-control" name="Fname" placeholder="David" required data-error='Please fill in your first name'>
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col">
<div class="form-group">
<label for="form_lastname">Last name*</label>
<input id="form_lastname" type="text" class="form-control" name="Lname" placeholder="Beckham" required data-error="Please fill in your last name">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_email">Email address*</label>
<input id="form_email" type="email" class="form-control" name="email" placeholder="becks#example.com" required data-error="Please provide your email address">
<div class="help-block with-errors"></div>
</div>
</div>
<div class="col">
<div class="form-group">
<label for="form_number">Contact number*</label>
<input id="form_number" type="number" class="form-control" name="number" placeholder="01234567890" required data-error="Please provide a contact number">
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_company">Your company name</label>
<input id="form_company" type="text" class="form-control" name="company" placeholder="Ex-footballers r us">
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="form-group">
<label for="form_message">Your message*</label>
<textarea id="form_message" class="form-control" name="message" cols="30" rows="10" placeholder="Here's my message" required></textarea>
<div class="help-block with-errors"></div>
</div>
</div>
</div>
<div class="row">
<div class="col">
<div class="g-recaptcha" data-sitekey="datasitekeynumbersandletters"></div>
</div>
</div>
<div class="row">
<div class="col">
<input type="submit" class="btn btn-outline-brand btn-block" name="submit" value="Send enquiry">
</div>
</div>
</form>
I have tried following this tutorial:
Bootstrap success alert upon form submition via javascript
Edited to add the only JS I have for this file:
<script src="https://www.google.com/recaptcha/api.js" async defer></script>
without success.
Thank you in advance

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.

keeping bootstrap modal active

hi how to keep bootstrap modal active after clicking submit button. In my case after clicking submit button it refresh the page so it close the modal. In my modal form i have a textboxes that when you click submit it will save the data in database. Now i have a php code that check the textboxes if their empty it will show/say the error and if not empty it will says success.
Thanks in advance who will help.
This is my code
<div class="modal fade" id="addtopic" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4>Add Topic</h4>
</div>
<form method="POST" action="index.php" role="form" id="saveform">
<div class="modal-body">
<div class="form-group">
<label for="cCategory">Category</label>
<input type="text" class="form-control" id="cCategory" name="category" value="<?php if (!empty($categ)) { echo $categ; } ?>">
</div>
<div class="form-group">
<label for="cTitle">Title</label>
<input type="text" class="form-control" id="cTitle" name="topicTitle" value="<?php if (!empty($topicTitle)) { echo $topicTitle; } ?>">
</div>
<div class="form-group">
<label for="cDesc">Description</label>
<textarea class="form-control custom-control" rows="3" style="resize:none" name="desc" value="<?php if (!empty($desc)) { echo $desc; } ?>"> </textarea>
</div>
<div class="form-group">
<label for="cDesc">Created By</label>
<input type="text" class="form-control" id="cDesc" name="createdby" value="<?php if (!empty($created)) { echo $created; } ?>">
</div>
</div>
<div class="modal-footer">
if($insert = $db->query("
INSERT INTO pncontent (category, title, description, createdby, dateadded)
VALUES ('$categ', '$topicTitle', '$desc', '$created', NOW() )
")) {
echo "<p class='pull-left'> Topic Save! </p>";
}else {
echo "<p class='pull-left'>Failed to Save</p>";
die($db->error);
}
}else {
echo "<p class='pull-left'>All Fields are required</p>";
$desc = $_POST['desc'];
$categ = $_POST['category'];
$topicTitle = $_POST['topicTitle'];
$created = $_POST['createdby'];
}
}
?>
<button type="submit" name="Sbt" class="btn btn-primary" >Save changes</button>
<button data-dismiss="modal" class="btn btn-danger">Close</button>
</div>
</form>
</div>
</div>
</div>
Where you return
echo "<p class='pull-left'>All Fields are required</p>";
Add this bit of code to open the modal on page load.
<script type="text/javascript">
$(window).load(function(){
$('#addtopic').modal('show');
});
</script>

alert box in PHP and navigation to another page

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>

Categories