I wrote a simple php script for a form, tested it out, and worked as expected. But when I actually added the script into the original project that I am working on, it suddenly stopped working? I am sure it has nothing to do with the php script as for it worked properly when I tested it; so basically what I am thinking about is that I probably wrote the action attribute wrong? I am pretty sure it is a rookie mistake. Eventually, I am really new to php.
Regards.
HTML code:
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel">
<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="exampleModalLabel">New message</h4>
</div>
<div class="modal-body">
<form action="contact.html" method="post">
<div class="form-group">
<label name="email" class="control-label">Email:</label>
<input type="text" class="form-control" id="recipient-name">
</div>
<div class="form-group">
<label name="phone" class="control-label">Phone:</label>
<input type="text" class="form-control" id="recipient-mobile">
</div>
<div class="form-group">
<label name="message" class="control-label">Message:</label>
<textarea class="form-control img-responsive" rows="5" id="messageText"></textarea>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
<button type="button" id="resetText" class="btn btn-default">Reset</button>
<input type="button" value="Send message" name="send" class="btn btn-danger colorbg"/>
</div>
</div>
</div>
</div>
PHP Code:
<?php
if(isset($_POST['send'])){
$to = 'domain#mail.com';
$subject = 'Solutions';
$mail = $_POST['email'];
$phone = $_POST['phone'];
$message = $_POST['message'];
$mailHeader = "From: $mail \r\n Phone: $phone";
$formcontent="Message: $message";
if (!filter_var($mail, FILTER_VALIDATE_EMAIL)) {
echo "<script language='javascript'>
alert('E-mail address is not valid');
var email = document.getElementById('recipient-name');
email.className += ' border-red';
</script>";
} else {
echo "<script language='javascript'>
var email = document.getElementById('recipient-name');
email.className = '';
email.className += ' form-control';
</script>";
if (mail($to , $subject, $formcontent, $mailHeader)) {
echo "<script>
window.setTimeout(function () {
window.location.href = 'test.html';
}, 3000);
</script>";
} else {
echo "<script language='javascript'>alert('There was an error. Please try again.')</script>";
}
}
}
?>
Please note that I uploaded the project on my website in order to actually test the script so the link is something like this: website.com/project/index.html. And I changed the action to action="script/contact.php", action="./script/contact.php, action="contact.php" none worked.
There are two things that makes this not work.
The "submit" button (or any of the other buttons for that matter) is not inside the form-tags. They can be outside, if you assign an ID to the form and assign inputs outside the form, to that form.
There isn't actually a submit-button. You have a regular button. It should be of type="submit", not type="button" (and type="reset" for reset buttons).
In HTML5, you can assign inputs to a form, even outside the actual form-tags. You can do that by assigning an ID to the form (in this example, "myform") and then specifying the form-attribute on your input, like this.
<form id="myform" method="get" action="something.php">
<input type="text" name="name" />
</form>
<input type="submit" form="myform" />
You also, as the other answer already pointed out, the action targets a .html file, which under normal configurations would not parse PHP, but display it as text instead.
I don't see any submit.
Or is that handled by JavaScript somewhere?
Also, the form action= is a html file, if you want the php to work in there, you'll need a .php file.
There is nothing being posted in the html you're showing that is named "send". ( if(isset($_POST['send'])) )
I found the solution here for a similar problem. I hope this is the right place for my answer.
I use buttons A-Z to filter last names in 'listContacts.php'.
Each button triggers a submit. The submit was working from the beginning on
var $char='';
var $characterfilter=function charfilter($char){;
$('#coll').prop('value', $char);
var val2=$('#coll').val();
$('#listcontacts').submit();
};
$('#a').click(function(){
$characterfilter('a');
});
The problem:
<form id='listcontacts' href='' title='use the tabulator to move in the form' style='position: relative; overflow:hidden; height:25em; width:95%' method='post' accept-charset='UTF-8' action='admin.php?listContacts'>
A switch-function in 'admin.php' as below controls the actions:
switch ($action){
case 'login':
login();
break;
case 'logout':
logout();
break;
case 'editService':
editService();
break;
case 'deleteService':
deleteService();
break;
case 'listContacts':
listContacts();
break;
case 'newContact':
newContact();
break;
case 'editContact':
editContact();
break;
case 'deleteContact':
deleteContact();
break;
default:
listServices();
}
When I submitted the form, the Switch in 'admin.php' always returned the default, so I saw the form 'listServices.php' instead after submitting 'listContacts' by using one of the filterbuttons.
The reason for this flaw was: the first call to 'listContacts.php' had been executed by a command:
<a href='admin.php?action=listContacts' >List Contacts</a>
so 'action' had already been set to 'listContacts'
After removing 'action=...' from the formcall as below the form was working.
<form id='listcontacts' href='' title='use the tabulator to move in the form' style='position: relative; overflow:hidden; height:25em; width:95%' method='post' accept-charset='UTF-8'>
It was a little puzzle, took me a few hours and I hope I can help others saving time by posting this.
Related
I have this code for search in my database, I use a barcode scanner (work like a keyboard), when I scan a barcode the input text shown perfectly, but I need to press MATCH to do the enter function, I want to submit it automatically after the barcode scanner scan a code and not to press MATCH.
<html>
<body>
<div class="container pt-5">
<div class="row">
<form method="POST" action="match.php" autocomplete="off">
<div class="form-group">
<label>Scan:</label>
<input type="text" id="no" name="no" class="form-control" required>
</div>
<div ></div>
<button class="btn btn-info" name="sub" type="submit">MATCH</button>
</form>
</div>
</div>
</body>
</html>
<?php
include 'includes/conn.php';
if (isset($_POST['sub'])) {
$sca=trim($_POST['no'],"");
$flag=0;
$credentials="";
$password="";
$firstname="";
$lastname="";
$new2 ="SELECT * FROM `voters`";
$res2=mysqli_query($conn, $new2);
while($row=mysqli_fetch_array($res2)){
//echo $row['number'].'<br>';
// if($row['number']){
if($row['credentials'] == $sca){
$flag=1;
$credentials=$row['credentials'];
$password=$row['password'];
$firstname=$row['firstname'];
$lastname=$row['lastname'];
}
}if ($flag==1) {
echo "<div class='container'><div class='row'><div class='col-sm-3'></div><div class='col-sm-6'><div class='alert alert-success d-flex justify-content-center mt-3'>".
'<br><b>Votante:</b>'.' '.$id.
'<br><b>Registro:</b>'.' '.$credentials.
'<br><b>Contraseña:</b>'.' '.$password.
'<br><b>Nombre:</b>'.' '.$firstname.
'<br><b>Apellidos:</b>'.' '.$lastname.
"</div></div></div><div class='row'><div class='col-sm-3'></div><div class='col-sm-6'>" ;
return;
}
else{
echo "<div class='alert alert-danger d-flex justify-content-center mt-3'>Product Not Found</div></div>";
return;
}
}
mysqli_close($conn);
?>
We had to work with barcode scanners a while ago, where we had a similar request, so I hope I can help here. Most simple barcode scanners just enter the scanned code and append a new line.
As stated in the comments you need some JavaScript in order to do that. We used the jquery library. Like CBroe said, you need to find the correct event, to use. We tried different events and found the "change" event to be the best suitable one for us.
Our case was a little more complex, because we had multiple fields and had to make ajax requests, so I tried to reduce our script to something that may be a good starting point for you:
$(document).ready(function() {
$('#no').change(function () { //if content of field with id #no changes do stuff
let value = $(this).val();
const minlength = 5;
if (value.length >= minlength) {
$( "#scanform" ).submit(); //submit form with id scanform
}
});
});
Pleas note, that this script assumes you add the id "scanform" to your form tag.
fairly new php user here.
I've been struggling to find the solution to a very simple problem.
I'm currently creating a feedback system for my school where people can submit a text with a title to certain students, yet after submitting the form it seems the $_Post of my fields are empty.
My html looks like this (The form to be submitted is in a bootstrap modal)
HTML
<div class="modal fade" id="modalWriteFeedback" tabindex="-1" role="dialog">
<div class="modal-dialog" role="document">
<form action="php/feedbackPHP.php" method="post">
<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>
<h3 class="modal-title" id="modalTitleWriteFeedback">Create New Feedback</h3>
</div>
<div class="modal-body" id="modalContentWriteFeedback">
<div class="form-group">
<label for="txtFeedback">Title:</label>
<input name="title" class="form-control required" type="text" id="txtFeedback">
</div>
<div class="form-group">
<label for="feedbackText">Description:</label>
<textarea class="form-control required" id="feedbackText" rows="15" name="content"></textarea>
</div>
<input type="submit" class="btn-success" name="btnSendFeedback" value="Send">
</div>
</div>
</form>
</div>
</div>
"title" and "content" are to be submitted, which I'm trying in my "feedbackPHP.php"
feedbackPHP.php
<?php
$servername = "*********";
$username = "**********";
$password = "***********";
// Create connection
$db = new mysqli($servername, $username, $password);
// Check connection
if ($db->connect_error) {
die("Connection failed: " . $db->connect_error);
}
$feedbackTitle = $_post['title'];
$feedbackContent = $_post['content'];
$query = /**inserting data in db**/;
echo $feedbackTitle . "<- supposed to not be empty";
mysqli_query($db, $query) or die('msg:' + $feedbackTitle);
//Step3
$result = mysqli_query($db, $query);
mysqli_close($db);
?>
The submit recognized the .php file, and only returns the "<- supposed to not be empty" part.
I have tried with a simple form:
<form action="php/feedbackPHP.php" method="POST">
<input type="text" name="title" id="txtText">
<input type="textarea" name="content" id="txtContent">
<input type="submit" value="go">
</form>
With this as .php
<?php
/**connect to db part**/
$feedbackTitle = $_POST['title'];
$feedbackContent = $_POST['content'];
echo $feedbackTitle . " " . $feedbackContent;
$query = /**insert into db**/;
mysqli_query($db, $query) or die('msg:' + $feedbackTitle);
//Step3
$result = mysqli_query($db, $query);
mysqli_close($db);
?>
And $feedbackTitle & $feedbackContent are working perfectly, even adding the right values in my database.
So according to this is it a problem with the bootstrap modal and the form in it?
I have tried with an Ajax request, the $_POST still seem to be empty.
I tried almost every answer on the forum (been busy for almost a day now), but none seem to be working either.
Thanks in advance.
Use $_POST, not $_post :-)
Php is case sensitive, and it will be the same with $_GET, $_SESSION, $_SERVER, [...]
http://php.net/language.variables.superglobals
Were searching for few hours answer on this but I'm completely stacked and brain freezes.
Have subscribe php form with bootstrap modal on successful submission. Everything works, emails passing through, modal showing just after one second or less blank page appear.
I guess that is loaded before form.php file is a separate file but is it there a way to stop loading blank page?
Here is Html code
<form action="form.php" method="post">
<div class="form-group label-floating">
<input name="email" class="control-label form-control text-center" type="text" placeholder="Enter your email address ...">
<button type="submit" class="btn btn-primary" data-toggle="modal" data-target="#myModal">Send</button>
</div>
</form>
<!-- Sart 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">
<i class="material-icons">clear</i>
</button>
<h4 class="modal-title">Thank you</h4>
</div>
<div class="modal-body">
<p>Thank you for registering, we have added you to the waiting list!
</p>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger btn-simple" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
<!-- End Modal -->
And here is php code
<?php
$to = "test#test.com";
$from = "no-reply#test.com";
$headers = "From: " . $from . "\r\n";
$subject = "New Beta Subscription";
$body = "New user interested in beta program: " . $_POST['email'];
if( filter_var($_POST['email'], FILTER_VALIDATE_EMAIL) )
{
if (mail($to, $subject, $body, $headers, "-f " . $from))
{
echo "<script type='text/javascript'>
$(document).ready(function(){
$('#myModal').modal('show');
window.stop();
});
</script>";
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
}
else
{
echo 'There was a problem with your e-mail (' . $_POST['email'] . ')';
}
Also want to change Error messages to show up over modals also, that have it generated just not sure if can call two modals from same index file?
Any help is highly welcome!
Thanks, K>
What you are trying to achieve seems different from what you actually coded.
Let's look at your HTML form. You have attached Bootstrap's data-toggle and data-target attributes on your submit button. This means that when you click that button, it will open the modal AND submit the form. So the user will briefly see a modal and see the page redirect to your PHP file. (This is why you are seeing a modal appear briefly.)
Next, let's look at your PHP file. First of all, when you submit a form from one page to another page, that latter page has no idea of the HTML elements in your former page. This means the code you have inside your echo'd <script> tag actually should not be working as it is looking for an HTML element on your former page.
Now, for your question as to why are you getting a blank page? Well... everything is working fine so your code echo's a <script> tag -- which has no visual indicator. But like I just said, what you have inside the <script> does not work -- so nothing shows up and nothing happens.
So recap of the order of events when you click your button: the modal shows up, the form submits, the form redirects to another page, and that other page echo's nothing.
Below is a poor/quick solution to what I think you are trying to achieve:
Change your HTML file to a PHP file.
Remove data-toggle and data-target attributes off your button, so that it doesn't open the modal right when you click the button
<form action="form.php" method="post">
<div class="form-group label-floating">
<input name="email" class="control-label form-control text-center" type="text" placeholder="Enter your email address ...">
<button type="submit" class="btn btn-primary">Send</button>
</div>
</form>
Move your echo'd script tag from your PHP submission page to your PHP form page and wrap it in a condition as shown below:
<?php if (!empty($_GET['success'])) : ?>
<script>
$(document).ready(function(){
$("#myModal").modal();
});
</script>
<?php endif ?>
Remove your echo'd script tag lines of code in your PHP submission page. Instead, add a code so that it redirects back to your PHP form page. The key part is that you will append a ?success=true at the end of your URL.
$email = filter_input(INPUT_POST, 'email', FILTER_VALIDATE_EMAIL); // valid email or null|false
if ($email) {
$to = "test#test.com";
$from = "no-reply#test.com";
$headers = "From: " . $from . "\r\n";
$subject = "New Beta Subscription";
$body = "New user interested in beta program: " . $email;
if (mail($to, $subject, $body, $headers, "-f " . $from)) {
header('Location: subscribe.php?success=true'); // replace `subscribe.php` with PHP form page
exit;
}
echo 'There was a problem with your e-mail (' . $email . ')';
} else {
echo 'There was a problem with your e-mail'; // no point in printing $email if it is null
}
Basically, passing ?success=true is for telling the PHP form page that everything went well to open the modal (3).
And that should be it.
A better approach is to learn and use AJAX.
I'm trying to disable a submit button when I get some trigger from the database that tells me I should disable it, I added some code in the echo line in PHP but it didn't work, what am I doing wrong?
PHP CODE
$tries= CCL::Triescount($userip)->NumofTries;
if ($tries > 2 ) //Check wheter they have tried more than 2 times then block them
{
$msg = "More than 2 attempts, block user";
echo '<input type="submit" disabled="disabled" />';
}
else
{
$tries++;
$msg = "Less than 2 attempts";
CCL::Updatetries($userip,$tries,0);
//insert into the DB
}
HTML FORM
<div class="ui-body ui-body-c ui-corner-all">
<h1>Forgot Password</h1>
<form>
<label for="emailpassdlbl"> Please enter the e-mail associated with your account, and a new auto-generated password will be sent to this e-mail account.</label>
<input type="text" id="email"><BR>
<div class="right">
<input type="submit" data-inline="true" value="Submit" disabled="disabled">
</div>
</form>
<br/>
<div data-role="popup" class="ui-body ui-body-c ui-corner-all">
<h2 id="result"></h2>
OK
</div>
If you're changing the entire code with PHP to disable it, why not remove the submit functionality altogether?
For example:
if ($tries > 2 ) //Check wheter they have tried more than 2 times then block them
{
$msg = "More than 2 attempts, block user";
echo '<button type="button" disabled" />';
}
As you can see we have actually removed the type="submit" and replaced it with type="button" it should still look like the same button however it wont submit the form (in addition to the disabled attribute).
I have a page called service.php that uses a modal window to open a form. The action on the form was service.php.
<div class="modal hide fade" id="myServiceModal" tabindex="-1" role="dialog" aria-labelleby="myModalLabel" aria-hidden="true">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h3 id="myModalLabel">Service Failure Form</h3>
</div>
<div class="modal-body">
<p>
<form class="well-small" action="service.php" method="POST" id="serviceModalForm" name="serviceModalForm">
<label>Container Selected</label>
<input type="text" name="containerNumber" id="containerNumber" />
<label>Bol Selected</label>
<input type="text" name="bolNumber" id="bolNumber" />
<input type="submit" id="modal-form-submit" name="submit" class="btn btn-success btn-small" href="#" value="Save" />
<?php
$bol = $_POST['bolNumber'];
$container = $_POST['containerNumber'];
if(isset($_POST['submit'])){
$sql_query_string =
"INSERT INTO import_view_svc_fail (bol, container_num) VALUES
('$bol', '$container');";
if(mysql_query($sql_query_string)){
echo ("<script language='javascript'>
window.alert('Added New Service Failure')
</script>");
}
?>
</form>
This form worked, and it saved to the appropriate table.
Here is my problem: I had to move that form to another page, called dispatch.php. All I did was copy the code, and put it on dispatch.php.
I changed the action of the form to dispatch.php, and that's where I think the problem starts. When I change the action back to service.php, it works for whatever reason.
When I remove the form completely from service.php, the form on dispatch.php no longer works.
I've tried everything to make this work. I removed all of the code from service.php. I even removed the whole file from the folder.
Any insight would be helpful.
You tell the script what to do but you don't tell it to do it.
In order to excecute a your SLQ-query you have to use mysql_query($sql_query_string);
You will also want to connect to your database. Take a look at http://php.net/manual/de/function.mysql-connect.php for more information.
so.. you change the action in service.php:
<form class="well-small" action="dispatch.php" method="POST" id="serviceModalForm" name="serviceModalForm">
Move to dispatch.php
<?php
if(isset($_POST['submit']))
{
$bol = (isset($_POST['bolNumber'])) ? $_POST['bolNumber'] : '';
$container = (isset($_POST['containerNumber'])) ? $_POST['containerNumber'] : '';
if (!empty($bol) && !empty($container))
{
$sql_query_string =
"INSERT INTO import_view_svc_fail (bol, container_num) VALUES
('$bol', '$container');";
// run the query here
print "<br/><br/>".$sql_query_string."<br/><br/>";
}
else { print "<br/><br/>empty values;<br/>"; }
}
else { print "<br/><br/>\$_POST info not received;<br/>"; }
?>
prints (after submit):
INSERT INTO import_view_svc_fail (bol, container_num) VALUES ('input one value', 'input two value');
you probably should check and make sure you got all your post values inside the if(isset($_POST['submit'])) statement, too. or re-work the logic as a whole... it depends if you want to allow blank values, too.
Also, read up on sql injection and why you should learn to use mysqli_ or pdo.