I have a Bootstrap template, anyhow I am creating a modal [popup] on my page where the user can submit a form. Although The form works fine but on my PHP code I orignally have that after submitting, it'll show a message either if it worked it would say something like 'Your message has been posted' or if it was an error it would show the error.
But unfortunately once I click 'Post' it posts, but when I click 'Open modal' button again to show the modal popup it shows the message then saying it was submitted, meaning I cant post again without reloading the page.
How would I be able to make it show the message without closing the modal, and also when I close, then open it back up [without reloading] it'll return back to my form instead of having a message.
Thanks.
My code: [Might not be exact as I cut a few un-needed things out]
<?php
echo '
<div style="float:left;margin-top:-51px;margin-left:141px;"> <!-- Button trigger modal -->
<button class="btn btn-primary btn-sml" data-toggle="modal" data-target="#myModal">
Send private message
</button>
<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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">Send a message to '.$row["username"].'</h4>
</div>
<div class="modal-body"> ';
if($_POST[add2]){
$subject = strip_tags($_POST['title']);
$content = $_POST['content'];
$date = date("F jS, Y g:i a");
$receiver = $row["id"];
$sender = $member["id"];
if(!$content){
echo 'All fields are required';
}else{
$sql = $dbh->prepare("INSERT INTO `inbox` (`receiver`, `sender`, `subject`, `content`, `date`, `status`) VALUES ('$receiver', '$sender', '$subject', '$content', '$date', 'unread')");
$sql->execute();
$q = $sql->fetch(PDO::FETCH_ASSOC);
if($sql){
echo '<center>Message sent!</center>';
}else{
echo '<strong>Error:</strong> '.mysql_error();
}
}
}else{
echo '
<div style="overflow:auto;"><form method="post">
<div style="float:left;width:550px;">Subject<br>
<input type="text" name="title" id="title" class="form-control" value="" size="50" maxlength="40">
<br>Message<br>
<textarea style="height:85px;max-width: 550px;" class="form-control" name="content" placeholder="Enter your message here..." ></textarea></div>
<br><hr></div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" style="margin-left:10px;" class="btn btn-primary" name="add2" value="Post">
</form>
</div> '; }
?>
Related
i've tried looking at the source code and changing this but still have no luck! Hope someone can spot the mistake i've made.
Im basically just trying to submit a form with just 1 input field for now using AJAX and PHP to post using PDO method.
Here is my code:
Connection to database
<?php
define('HOST', 'localhost');
define('DB_NAME','test');
define('USER','root');
define('PASS','');
$dsn = 'mysql:host='.HOST.'; port='.PORT.'; dbname='.DB_NAME;
try {
$bd = new PDO($dsn, USER, PASS);
// $bd->setAttribute(PDO::ATT_ERRMODE, PDO::ERRMODE_EXCEPTION);
} catch (PDOException $e) {
echo 'Problem connecting to database, contact admin';
}
?>
Bootstrap Form
<div class="modal fade" id="add_new_record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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="myModalLabel">Add New Record</h4>
</div>
<div class="modal-body">
<div class="form-group">
<form id ="myform">
<label for="name">Name</label>
<input type="text" id="name" placeholder="Name" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default" id="submit" value="submit">Submit</button>
</form>
</div>
</div>
</div>
</div>
AJAX Script
$(document).ready(function(){
$('#myform').submit(function(){
var data = $(this).serialize();
$.ajax({
url: "insert.php",
type: "POST",
data: data,
success: function( data )
{
alert( data );
},
error: function(){
alert('ERROR');
}
});
return false;
});
});
insert.php Script
<?php
require_once('config.php');
if(isset($_POST['submit'])){
$name = $_POST['name'];
$sql = 'INSERT INTO people(name) ';
$sql .= ' VALUES (:name)';
try {
$query = $bd->prepare($sql);
$query->bindValue(':name', $name, PDO::PARAM_STR);
if($query->execute()){
echo "recorded added sucessfully";
}else{
echo "Problem adding new record";
}
} catch (Exception $e) {
echo $e->getMessage();
}
}
?>
In your html code, you don't have any form. So you can't directly use .submit() or .serialize()
Consider closing you form elements within <form>
Change your html to this:
<div class="modal fade" id="add_new_record_modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel">
<div class="modal-dialog" role="document">
<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="myModalLabel">Add New Record</h4>
</div>
<div class="modal-body">
<div class="form-group">
<form id ="myform">
<label for="name">Name</label>
<input type="text" name="name" placeholder="Name" class="form-control" />
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Cancel</button>
<button type="submit" class="btn btn-default" id="submit" value="submit">Submit</button>
</form>
</div>
</div>
</div>
</div>
Update:
Add name attribute in input tag.
Serialize labels items by its name attribute.
Try to read about submit() to fully understand how it works: https://api.jquery.com/submit/
You are not using the <form> tag, so submit() doesn't catch any event.
Try wrapping your input and buttons in the same form tag, with id=myform and try again.
Also you are not using event.preventDefault(), without which the page will be refreshed.
Can someone please help me understand, why my code is not inserting data into my database from this form? I can get it to Select and Echo the same info from the same database to the page but when I go to add new data through the form it never makes it to the db.
I'm not getting any errors at all and I have error reporting set at the top of my page. I even set a javascript alert to capture the values of the input when clicking the submit button and they return the true values. They just won't insert into the database.
What am I doing wrong here?
<?php
if(isset($_POST['addContent'])) {
$addTitle = $_POST['title'];
$addEntry = $_POST['entry'];
$sql = mysqli_query($conn, "INSERT INTO `basic` (`title, entry`) VALUES ('$addTitle', '$addEntry')") or die(mysqli_error($conn));
$result = mysqli_query($sql);
if(!$result) {
echo mysql_error($sql);
}
}
?>
<!-- Modal -->
<div class="modal fade" id="addContentModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-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="myModalLabel">Add Data</h4>
</div>
<div class="modal-body">
<form method="POST" action="">
<input type="hidden" name="addContent" id="addContent" value="1">
<div class="form-group">
<label for="title">Title</label>
<input id="addTitle" name="addTitle" type="text" class="form-control">
</div>
<div class="form-group">
<label for="entry">Entry</label>
<textarea id="addEntry" name="addEntry" class="form-control" ></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="submit" id="saveAddBtn" class="btn btn-primary" data-dismiss="modal">Save changes</button>
</div>
</div>
</div>
</div>
UPDATE:
Ok so here's my attempt at addressing some of the issues you all have enlightened me to. Still same result...any other ideas?
<?php
if(isset($_POST['addContent'])) {
$addTitle = $_POST['title'];
$addEntry = $_POST['entry'];
if($addTitle != "" && $addEntry != "")
{
$sql = $conn->prepare("INSERT INTO basic VALUES ('',?,?)");
$sql->bind_param('sss', $addTitle, $addEntry);
$result = mysqli_query($sql);
if(!$result) {
echo mysqli_error($sql);
}
}
}
?>
<!-- Modal -->
<div class="modal fade" id="addContentModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-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="myModalLabel">Add Data</h4>
</div>
<div class="modal-body">
<form method="POST" action="">
<input type="hidden" name="addContent" id="addContent" value="1">
<div class="form-group">
<label for="title">Title</label>
<input id="addTitle" name="title" type="text" class="form-control">
</div>
<div class="form-group">
<label for="entry">Entry</label>
<textarea id="addEntry" name="entry" class="form-control" ></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<input type="submit" id="saveAddBtn" class="btn btn-primary" data-dismiss="modal" value="Save changes">
</div>
</div>
</div>
</div>
The problem are these lines:
$sql = mysqli_query($conn, "INSERT INTO `basic` (`title`, `entry`) VALUES ('$addTitle', '$addEntry')") or die(mysqli_error($conn));
$result = mysqli_query($sql);
Remove the first mysqli_query and set $sql to equal just the string, this will give you the result and not the result of the result (it'll return boolean false when using the result as a query) and also, backtick each column name singularly, not as a whole :)
change your query to:
$sql = mysqli_query($conn, "INSERT INTO `basic` (`title`, `entry`) VALUES ('$addTitle', '$addEntry')") or die(mysqli_error($conn));
The backticks are affecting the query. Note that the back ticks are around each column individualy not around all of them. The way you have it would suggest you have a column called title, entry. You should also remove the $result line because the query has been executed already. Now you also have to change the if statement to if (! $sql).
Update
<?php
if(isset($_POST['addContent'])) {
$addTitle = $conn->real_escape_string($_POST['title']);
$addEntry = $conn->real_escape_string($_POST['entry']);
if(!empty($addTitle) && !empty($addEntry)) // There is a function for this
{
// Because you are only inserting 2 values there only need to be 2 `?` and 2 parameters
$sql = $conn->prepare("INSERT INTO `basic` (`title`, `entry`) VALUES (?,?)"); // Added column names just to be sure values are inserted on correct columns
$sql->bind_param('ss', $addTitle, $addEntry); // Note the 2 "s" not 3
$sql->execute();
if($sql->affected_rows < 1 ) {
echo $sql->error(); // Don't know for shure what this should be `error` or `error()`
}
}
}
?>
I can't believe none of us caught this sooner. But my submit button was not even inside the form tag! My buddy pointed this out and it fixed the issue. Thanks for trying everyone!
change your query to:
$sql = mysqli_query($conn, "INSERT INTO `basic` (title, entry) VALUES ('$addTitle', '$addEntry')") or die(mysqli_error($conn));
The backticks are affecting the query.
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/
I will try to be as clear as I can.
I'm creating a simple example page where employee can review there age.
On the page user have the choice to click on a button to change there age.
The page load the age from a use in a Database.
So I select from the table employee the age matching the $name value.
<?php
$query = "SELECT * FROM employee";
$rs = mysql_query($query);
while ($row = mysql_fetch_assoc($rs)) {
echo "Name " . $row['name'] . "<br/>Age " . $row['age'] . "<br/>";
}
?>
Under that I have a bootstrap modal button so the employee can click and update there age.
<div id="myModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" 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">x</button>
<h4 class="modal-title" id="myModalLabel">Change your age</h4>
</div>
<div class="modal-body">
<?php
$name = "Mathieu";
$query = sprintf("SELECT age From employee Where name = '%s'",
mysql_real_escape_string($name));
$rs = mysql_query($query);
while ($row = mysql_fetch_object($rs)) {
$age = $row->age;
}
?>
<form action="update.php" method="post"class="form-inline">
<input class="form-control" id="disabledInput" type="text" placeholder="<?php echo $name; ?>" disabled>
<br/><br/>
<input type="text" class="form-control" placeholder="<?php echo $age; ?>" value="<?php echo $age; ?>">
<br/><br/>
<button type="submit" class="processing btn">Update</button>
</form>
</div>
</div><!-- /.modal-content -->
</div><!-- /.modal-dialog -->
</div>
<div class="bs-example" style="padding-bottom: 24px;">
<a data-toggle="modal" href="#myModal" class="btn btn-primary btn-large">Update your age</a>
</div>
I have 2 problem.
1. What is the best way to update the value in my database then close the modal.
2. How do I refresh my page without a reload.
I did some trial and error but nothing work at all.
The best way for me to update the value from the database without reloading is
that you should be using a Live Edit Using Jquery & ajax hope this helps.
use
header("Location: index.php");
I'm using twitter's bootstrap to make a WebApp, on one of the features of the App I need to have some modals with form's inside. Those forms will be filled with data through some PHP scripts. I'm having problems using the modal feature with forms, the data for edition is correctly displayed in the fields, but I'can't seem to submit the form.
This is my code:
<a href="#edit_user_<?php echo $row['id_user'] ?>" role='button' data-toggle='modal' data-original-title='Edit User' class='btn btn-small btn-info time-link'><i class='icon-pencil icon-white'></i></a>
<button data-toggle='tooltip' data-original-title='Delete User' class='btn btn-small btn-danger time-link'><i class='icon-trash icon-white'></i></button>
<?php
echo "</td>";
echo "</tr>";?>
<div id="edit_user_<?php echo $row['id_user']; ?>" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Modal header</h3>
</div>
<div class="modal-body">
<form action="" method="POST">
<label for="name">Name</label>
<input type="text" name="name" value="<?php echo $row['name']?>"/>
<label for="email">Email</label>
<input type="text" name="email" value="<?php echo $row['email']?>">
<button type="submit" name="update_btn">Submit</button>
<?php
if (isset($_POST['update_btn'])) {
if (isset($_POST['name']) && $_POST['name'] !="") {
if (isset($_POST['email']) && $_POST['email'] !="") {
$qstr_updateuser = "UPDATE `host_register`.`users` SET `name`=".$_POST['name'].", `email`= ".$_POST['email']." WHERE `users`.`id_user` = ".$row['id_user']."";
echo $qstr_updateuser;
$update_user = mysqli_query($dbc,$qstr_updateuser);
}
}
}?>
</form>
</div>
<div class="modal-footer">
<button class="btn" data-dismiss="modal" aria-hidden="true">Close</button>
<button class="btn btn-primary">Save changes</button>
</div>
</div>
And for some reason I can't understand, the browser output's this:
<div class="modal-body">
<form method="POST" action=""></form>
<label for="name">Name</label>
<input type="text" value="Pedro Oliveira" name="name">
<label for="email">Email</label>
<input type="text" value="pedro.oliveira#est.pt" name="email">
<button name="update_btn" type="submit">Submit</button>
</div>
I'm kind of clueless here! Is it a problem with bootstrap or with my code?
Fortunately, I found out that, since the Modal was inside a tag because of a while loop was causing this disturbance, but I could quite understand why that was happening. Fortunately I restarted my work from scratch and decided to create a different while loop to do the same Job, as it seems the problem was really the table tag.
If browser output's is that, you can't submit because submit button is not inside the form tag, even the inputs. Unless that your problem is really that.