Reload Bootstrap Modal on PHP variable not valid - php

Having some problems with the error handling of a bootstrap modal. In the modal I have two inputs (both are required). I want to be able to display a simple "required" message if the form is submitted without one of the fields populated.
I tried doing this with PHP and it works in a page by itself, but when I put it in a modal the modal closes on submit and then if you re-open the modal you see the error messages. I really want the modal to stay open or re-open if the input fields are not valid when the user submits.
Any help would be appreciated! Thanks!
HTML (Start of the modal):
<div class="modal fade" id="createModal" tabindex="-1" role="dialog" aria-labelledby="createModal" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myModalLabel">Add a vCenter</h4>
</div>
<div class="modal-body">
PHP (To graph the input and report any errors):
if ( !empty($_POST)) {
// keep track validation errors
$vcenternameError = null;
$vcenterownerError = null;
// keep track post values
$vcentername = $_POST['vcentername'];
$vcenterowner = $_POST['vcenterowner'];
// validate input
$valid = true;
if (empty($vcentername)) {
$vcenternameError = 'Please enter vCenter Name';
$valid = false;
}
if (empty($vcenterowner)) {
$vcenterownerError = 'Please select vCenter Owner';
$valid = false;
}
// insert data
if ($valid) {
$sql = "INSERT INTO ";
$stmt = sqlsrv_query( $conn, $sql );
if( $stmt === false) {
die( print_r( sqlsrv_errors(), true) );
}
header("Location: index.php");
}
}
?>
HTML (the rest of the modal):
<div class="panel-body">
<form class="form-horizontal" action="index.php" method="post">
<div class="<?php echo !empty($vcenternameError)?'error':'';?> form-group">
<div class="alert alert-warning">
Please input the FQDN of the vCenter and select an owner.
</div>
<label class="control-label">vCenter Name</label>
<div class="controls">
<input name="vcentername" type="text" placeholder="vCenter Name" value="<?php echo !empty($vcentername)?$vcentername:'';?>" class="form-control">
<?php if (!empty($vcenternameError)): ?>
<div class="alert alert-warning alert-dismissable">
<?php echo $vcenternameError;?>
</div>
<?php endif; ?>
</div>
</div>
<div class="<?php echo !empty($vcenterownerError)?'error':'';?> form-group">
<label class="control-label">vCenter Owner</label>
<div class="controls">
<div class="btn-group" data-toggle="button" role="group" aria-label="...">
<label class="btn btn-default">
<input type="radio" name="vcenterowner" value="Team1"> Team1
</label>
<label class="btn btn-default">
<input type="radio" name="vcenterowner" value="Team2"> Team2
</label>
<label class="btn btn-default">
<input type="radio" name="vcenterowner" value="Team3"> Team3
</label>
</div>
<?php if (!empty($vcenterownerError)): ?>
<div class="alert alert-warning alert-dismissable">
<?php echo $vcenterownerError;?>
</div>
<?php endif; ?>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<div class="form-actions">
<button type="submit" class="btn btn-success">Add</button>
<a class="btn btn-default" href="index.php">Back</a>
</div>
</form>
</div>
</div>
</div>
</div>

You can use jQuery to open the modal again if the modal contains errors when the page loads:
var modal = $('#createModal');
if(modal.find('div.alert-warning').length)
modal.modal();
But for the best user experience, you should call your PHP script with an ajax request: http://api.jquery.com/jquery.ajax/

Related

I want to call php inserting query when i am clicking the bootstrap button

My problem is I am trying to call the PHP file while clicking the button on my bootstrap but it is not working for me here by I paste my code of bootstrap and PHP kindly guide me for the solution
Thanks in advance
I am tired of changing button to form and all of these but not working I am working on PHP 7 and Bootstrap 4
<?php include "includes/db.php"; ?>
<?php
// echo "<h1> Testing </h1>";
// $db = mysql_select_db("cateory", $connection); // Selecting Database from Server
function(){
if (isset($POST['submit'])){
// $connect=mysqli_query($connection,)
$cat_title=$POST['cat_title'];
if($cat_title==""||empty($cat_title)){
echo "The field should not empty";
}
else{
$query="INSERT INTO category (cat_title)";
$query .=" VALUE ('{$cat_title}')";
$create_category_query = mysqli_query ($connection,$query);
if(!$create_category_query){
die ('QUERY FAILED'.mysqli_error($connection));
}
}
}
}
?>```
<!-- ADD CATEGORY MODAL -->
<div class="modal fade" id="addCategoryModal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-success text-white">
<h5 class="modal-title">Add Category</h5>
<button class="close" data-dismiss="modal">
<span>×</span>
</button>
</div>
<div class="modal-body">
<form action="" method="post">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="title">
</div>
</div>
<div class="modal-footer">
<?php insert_categories(); ?>
<button class="btn btn-success" type="submit" data-dismiss="modal">Save Changes</button>```
</div>
</form>
</div>
</div>
Do change your code like:
<?php
if ( isset( $_POST['submit']) ) {
// $connect=mysqli_query($connection,)
$cat_title = $_POST['cat_title'];
if($cat_title==""||empty($cat_title)){
echo "The field should not empty";
} else {
$query="INSERT INTO category (cat_title)";
$query .= " VALUE ('{$cat_title}')";
$create_category_query = mysqli_query ($connection,$query);
if(!$create_category_query){
die ('QUERY FAILED'.mysqli_error($connection));
}
}
}
?>
<!-- ADD CATEGORY MODAL -->
<div class="modal fade" id="addCategoryModal">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header bg-success text-white">
<h5 class="modal-title">Add Category</h5>
<button class="close" data-dismiss="modal">
<span>×</span>
</button>
</div>
<div class="modal-body">
<form action="" method="post">
<div class="form-group">
<label for="title">Title</label>
<input type="text" class="form-control" name="cat_title">
</div>
<div class="modal-footer">
<?php insert_categories(); ?>
<button class="btn btn-success" type="submit" data-dismiss="modal">Save Changes</button>```
</div>
</form>
</div>
</div>
</div>
</div>
Problems with your code:
Your HTML formatting itself is wrong. you have broken your form tag with div of modal-body. You have to reconsider your HTML design.
No need to wrap PHP code in a function with no name.
You just have to use the code only.
You have named your input as title while saving/checking data as cat_title.
Check your whole codebase again.

How to display a modal window, when validation is complete?

I made a form for newsletter subscription in my footer website. The code for this is:
<h4>Newsletter Subscribe:</h4>
<form method="POST" action="<?php URL::show("Newsletter", "create") ?>">
<div class="col-md-12">
<div class="input-group">
<input type="text" class="form-control" name="subscriber" placeholder="john.doe#domain.com">
<input type="submit" class="btn btn-primary" value="Subscribe">
</div>
</div>
</form>
When I click on the submit button will call the createAction method from NewsletterController that looks like this:
public function createAction(){
if($_SERVER["REQUEST_METHOD"] == "POST"){
$validation = true;
$error = "";
if(trim($_POST["subscriber"]) == ""){
$validation = false;
$error = "The field 'subscriber' is required!";
}
if(trim($_POST["subscriber"]) != ""){
if(!preg_match('/^([a-z0-9]+([_\.\-]{1}[a-z0-9]+)*){1}([#]){1}([a-z0-9]+([_\-]{1}[a-z0-9]+)*)+(([\.]{1}[a-z]{2,6}){0,3}){1}$/i', $_POST["subscriber"])){
$validation = false;
$error = "The field 'subscriber' must contain a valid input!";
}
}
if($validation){
$checkSubscriber = $this->newsletterRepository->checkSubscriber($_POST["subscriber"]);
if(!$checkSubscriber){
$newsletter = new Newsletter();
$newsletter->setEmail($_POST["subscriber"]);
$result = $this->newsletterRepository->insert($newsletter);
if(!$result){
$error = "There was an error in the newsletter
}
}else{
$error = "The e-mail already registered for newsletter!";
}
}
}else{
URL::redirect("Restaurants", "listAll");
}
}
Now, after I made all the validations and inserting the data in database, I don't want to go to another webpage, I want to display a popup with confirmation message if everything was ok or an error message if there was an error. Something like this:
<div class="modal fade bd-example-modal-lg" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Newsletter Subscription</h5>
<button type="button" class="close" data-dismiss="modal" aria-label="Close">
<span aria-hidden="true">×</span>
</button>
</div>
<div class="modal-body">
<div class="container-fluid">
<?php if($result): ?>
<p style="color:green">Newsletter subscription successfuly!</p>
<?php elseif($error): ?>
<p style="color:red"><?php echo $error; ?></p>
<?php endif; ?>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
But I don't know how to trigger the modal after all the operations and validation are done. Can anyone help please?
One of the easiest ways I can think is using javascript. After the validation is done successfully you can call a javascript function like this:
echo "<script type="text/javascript">the_function_you_want_to_call_from_javascript_file();
</script>";
Than in your javascript file you can call the modal and make your own customization.
Hope it helps :)

HTML Bootstrap PHP connection error

I want to write log in code for my index.html ' s form and i wrote a giris-yap.php file which is at below. i cant access my php file browser get alert only like localhost is waiting .
i tried to put action method in my form's submit button but it was not usefull.
giris-yap.php
<?php
require "connect.inc.php";
require "core.inc.php";
if(isset($_POST['exampleInputEmail1']) && isset($_POST['exampleInputPassword1']) ){
$mail=$_POST['exampleInputEmail1'];
$pass=$_POST['exampleInputPassword1'];
$password=md5($pass);
if($query_run=mysql_query("SELECT * FROM `users` WHERE `e-mail`= '".mysql_real_escape_string($mail)."' AND `sifre`='".mysql_real_escape_string($password)." ' ")){
$query_num_rows = mysql_num_rows($query_run);
if($query_num_rows==0){
echo 'Invalid';
}
else if($query_num_rows!=0){
$ad=mysql_result($query_run,0,'Ad');
$_SESSION['ad']=$ad;
$usersurname=mysql_result($query_run,0,'SoyAd');
$_SESSION['usersurname']=$usersurname;
$username=mysql_result($query_run,0,'e-mail');
$_SESSION['username']=$username;
header('Location: index.html');
}
}
else{
echo mysql_error();
}
}
else{echo 'error';}
/**
* Created by PhpStorm.
* User: bilsay
* Date: 21.05.2015
* Time: 10:35
*/
?>
index.html :
<div class="modal fade" id="login-modal-box" role="dialog" aria-labelledby="gridSystemModalLabel" aria-hidden="true">
<form action="#giris-kontrol" method="POST">
<div class="modal-dialog user-login-box-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="gridSystemModalLabel">Kullanıcı Giriş Paneli</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="form-group">
<label for="exampleInputEmail1">Eposta Adresiniz</label>
<input type="email" class="form-control" id="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Şifre</label>
<input type="password" class="form-control" id="exampleInputPassword1" placeholder="Password">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Beni hatırla
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-default" value="Giriş">Giriş</button>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</form>
</div><!-- /.modal -->
cant access my php file
You need to update your action as described in the other answer: https://stackoverflow.com/a/30377560/482256.
Then, note that this code here:
require connect.inc.php;
require core.inc.php;
Is the equivalent of doing this:
require 'connectincphp';
require 'coreincphp';
When you don't use quotes, PHP looks for constants, and when it doesn't find those it will assume the string, so connect becomes "connect". The period concatenates, so it combines "connect" with "inc" and you get "connectinc", etc.
The require should be causing a 500 error...and possibly an empty page depending on what your error output settings are.
Your code translated to PDO and BCrypt, because I just can't "fix" code and leave it insecure:
if(isset($_POST['exampleInputEmail1']) && isset($_POST['exampleInputPassword1']) ){
$pdo = new \PDO('mysql:dbname=dbName;host=localhost','username','password');
$mail = $_POST['exampleInputEmail1'];
$pass = $_POST['exampleInputPassword1'];
$userSql = $pdo->prepare("SELECT * FROM `users` WHERE `e-mail`=:email");
$userSql->execute(array('email'=>$mail));
$userData = $userSql->fetch(\PDO::FETCH_ASSOC);
if( $userData !== false && BCrypt::isValidPassword($pass, $userData['sifre']) ) {
$_SESSION['ad'] = $userData;
$_SESSION['usersurname'] = $userData['SoyAd'];
$_SESSION['username'] = $userData['username'];
header('Location: index.html');
}
else {
die("You have entered an invalid username or password");
}
}
else{
die("Username and Password must be submitted");
}
And your modified HTML. I fixed the action, turned your button into a real submit button, and added the name= attributes to your inputs:
<div class="modal fade" id="login-modal-box" role="dialog" aria-labelledby="gridSystemModalLabel" aria-hidden="true">
<form action="giris-yap.php" method="POST">
<div class="modal-dialog user-login-box-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-label="Close"><span aria-hidden="true">×</span></button>
<h4 class="modal-title" id="gridSystemModalLabel">Kullanıcı Giriş Paneli</h4>
</div>
<div class="modal-body">
<div class="container-fluid">
<div class="row">
<div class="form-group">
<label for="exampleInputEmail1">Eposta Adresiniz</label>
<input type="email" class="form-control" id="exampleInputEmail1" name="exampleInputEmail1" placeholder="Enter email">
</div>
<div class="form-group">
<label for="exampleInputPassword1">Şifre</label>
<input type="password" class="form-control" id="exampleInputPassword1" name="exampleInputPassword1" placeholder="Password">
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Beni hatırla
</label>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="submit" value="1" class="btn btn-primary" id="submit"> Giriş Yap</button>
</div>
</div>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
</form>
</div><!-- /.modal -->
And the BCrypt class you will need. However, use password_hash and password_verify if you have PHP >= 5.5.
class BCrypt {
public static function hash( $password, $cost=12 ) {
$base64 = base64_encode(openssl_random_pseudo_bytes(17));
$salt = str_replace('+','.',substr($base64,0,22));
$cost = str_pad($cost,2,'0',STR_PAD_LEFT);
$algo = version_compare(phpversion(),'5.3.7') >= 0 ? '2y' : '2a';
$prefix = "\${$algo}\${$cost}\${$salt}";
return crypt($password, $prefix);
}
public static function isValidPassword( $password, $storedHash ) {
$newHash = crypt( $password, $storedHash );
return self::areHashesEqual($newHash,$storedHash);
}
private static function areHashesEqual( $hash1, $hash2 ) {
$length1 = strlen($hash1);
$length2 = strlen($hash2);
$diff = $length1 ^ $length2;
for($i = 0; $i < $length1 && $i < $length2; $i++) {
$diff |= ord($hash1[$i]) ^ ord($hash2[$i]);
}
return $diff === 0;
}
}
change action..
<form action="giris-yap.php" method="POST">
then change a link in your modal-footer
<button type="submit" value="Giriş Yap" class="btn btn-primary" id="submit" />

Why can't I POST data from a Modal to PHP?

Using the following code, a modal within a form with method="POST" but in the php-part the submitted value is not read. Can anyone tell me how to accomplish this?
<?php
if ($error) {
echo '<div class="alert alert-danger">'.$error.'</div>';
}
if ($message) {
echo '<div class="alert alert-success">'.$message.'</div>';
}
?>
<div class="container">
<button class="btn btn-success" data-toggle="modal" data-target="#myModal">
Launch modal
</button>
<form method="post">
<div class="modal" id="myModal">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title">You will receive an Access Code at your new email-address</h4>
</div>
<div class="modal-body">
<label for="text">Fill in your Access Code right here</label>
<input type="text" name="AccessCode" class="form-control"/>
</div>
<div class="modal-footer">
<input type="submit" name="submit" value="Confirm" data-dismiss="modal" class="btn btn-success btn-lg marginTop" />
</div>
</div>
</div>
</div>
</form>
</div>
The php part looks like this:
<?php
if ($_POST['submit']=='Confirm') {
print_r($_POST);
$error="No errors";
$message="Approved!";
} else {
$error="Error!";
$message="Nothing received";
}
?>
Form needs an action ..
<form method="post">
Has no idea where it is supposed to post the information to.
<form method="post" action="phpPageToSendTo.php">
will work..
To test, at the top of your page in the php section add in
$testValue = "";
if(isset($_POST["AccessCode"]))
{
$testValue = $_POST["AccessCode"] ;
echo "<h1> BIG LETTERS WITH THE ACCESS CODE :" . $testValue . "</h1>";
}
?>
Now in your form HTML item use the action="" Run the page and test the form.
Resolution :
And it seems you cannot have another event attached to your submit.. data-dismiss="modal".

PHP login form within Bootstrap modal not working

I have created a login form within a Bootstrap modal but when the correct information is entered the user is shown the same page but with the modal closed i.e. not redirected to viewDashboard.php.
Code
<!-- Modal -->
<div class="modal fade" id="Modal" tabindex="-1" role="dialog" aria-labelledby="ModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="ModalLabel">Login to Portal</h4>
</div>
<div class="modal-body">
<form class="form-horizontal" action="" method="post">
<fieldset>
<div class="form-group">
<label for="inputID" class="col-lg-2 control-label">Username</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="inputID" name="user" placeholder="Username">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" class="form-control" id="inputPassword" placeholder="Password">
</div>
</div>
<div class="modal-footer">
<button type="submit" class="btn btn-primary">Submit</button>
</div>
</fieldset>
</form>
</div>
</div>
</div>
<?php
include("core/connection.php");
if($conn AND !empty($_POST)){
$stid = oci_parse($conn, "SELECT * FROM Customers WHERE Customers.CustomerNo = ".$_POST['user']."");
oci_execute($stid);
$count = oci_fetch_all($stid, $res);
if ($count > 0) {
session_start();
$_SESSION['account'] = $_POST['account'];
header("Location: viewDashboard.php");
}
oci_free_statement($stid);
oci_close($conn);
}
?>
</div>
If your user is correctly authenticated you should create a new session for him
session_start();
$_SESSION['user'] = array('id' => '...', name => '...', ...);
The information in the session can then be used in your secured section to check if the user is connected
session_start();
if (!isset($_SESSION['user']) {
// redirect to login page
}
Finally the redirection should be made before any information is sent to the client using:
// once logged
header('location:viewDashboard.php');
// on logout or if trying to access secured section
header('location:login.php');
EDIT to reflect the first 2 comments :
Your page should be structured like this:
//login.php
<?php
if (isset($_POST)) {
// login check
if ($isLogged) {
// session creation
header('location:...');
}
}
?>
<html>
<head>...</head>
<body>
...
<!-- Your modal box -->
</body>
</html>
If you want to re-open your modal box upon unsuccessful login, you should use your PHP to set the value of a flag (like !$isLogged you set a flag in your JS). If the flag is set to true, you trigger the modal box with Twitter's boostrap js.
References :
Sessions
Headers

Categories