I created a form where you upload an image like this
<form class="form" method="post" action="recipeUpload.php" enctype="multipart/form-data" autocomplete="off" onSubmit="window.location.reload();">
<fieldset style="margin-bottom: 70px;padding-top: 70px;">
<legend style="font-size: 36px;">פרטים אישיים</legend>
<input class="inForm" type="text" name="name" placeholder="שם" required/>
<input class="inForm" type="text" name="sur-name" placeholder="שם משפחה" required/>
</fieldset>
<fieldset style="margin-bottom: 70px;padding-top: 70px;">
<legend style="font-size: 36px; ">פרטי המתכון</legend>
<fieldset class="inForm" style="width:max-content;">
<legend style="font-size: 36px">העלו תמונה של המתכון</legend>
<label class="action" id="bb">בחרו תמונה
<input id="file" class="inForm" type="file" name="myfile" accept="image/*" required>
</label>
<div id="name"></div>
</fieldset>
<input class="inForm" type="text" name="time" placeholder="זמן הכנה" required/>
<input class="inForm" type="text" name="meal" placeholder="שם המנה" required/>
<label class="inForm">בחרו קטגוריה מתאימה</label>
<select class="inForm" name="category" required/>
<option value="מנות ראשונות">מנות ראשונות</option>
<option value="בשר">בשר</option>
<option value="פחמימות">פחמימות</option>
<option value="דברי חלב">דברי חלב</option>
<option value="צמחוני">צמחוני</option>
<option value="סלטים">סלטים</option>
<option value="קינוחים">קינוחים</option>
<option value="אחר">אחר</option>
</select>
</fieldset>
<fieldset style="margin-bottom: 70px;padding-top: 70px;">
<legend style="font-size: 36px;">המתכון עצמו</legend>
<textarea id="ingredients" name="ingredients" class="inForm long-text" placeholder="רכיבים" required>רכיבים:</textarea>
<textarea id="directions" name="directions" class="inForm long-text" placeholder="אופן ההכנה" required>אופן ההכנה:</textarea>
</fieldset>
<input class="inForm action" id="submit" type="submit" name="submit" value="שלחו את המתכון שלכם">
</form>
Now the php for uploading the images:
if(isset($_POST['submit'])){
echo "<label class='inForm'> Your messege has been sent. Thank You!</label>";
$errors = []; // Store all foreseen and unforseen errors here
$fileName = $_FILES['myfile']['name'];
$fileSize = $_FILES['myfile']['size'];
$fileTmpName = $_FILES['myfile']['tmp_name'];
$fileType = $_FILES['myfile']['type'];
$tmp =explode('.',$fileName);
$fileExtension = strtolower(end($tmp));
$directory = getcwd(). "/uploads/"; $files = scandir($directory);
$num_files=count($files)-2;
if ($fileSize > 2000000) {
$errors[] = "This file is more than 2MB. Sorry, it has to be less than or equal to 2MB";
}
if (empty($errors)) {
$uploadPath = getcwd() ."/uploads/img[" .$num_files. "].". $fileExtension;
if(move_uploaded_file($_FILES['myfile']['tmp_name'], $uploadPath)) {
} else{
echo "There was an error uploading the file, please try again!";
}
} else {
foreach ($errors as $error) {
echo $error . "These are the errors" . "\n";
}
}
}
I tested this many times, and every time I submit the form it uploads the same image under 2 different numbers. let's say there where 0 images in the directory and I would submit the form once it would upload the same image twice under img[0].png and img[1].png where the image is again the same. Why is the code running twice? can sombody help me? Thank you.
You are reloading the page on form submit: onSubmit="window.location.reload();", this is submitting the form again on reload. Try removing onSubmit="window.location.reload();".
Related
The question I've got in my test goes like so.
You have 1 select with 2 options(item number1 and item number2) and 2 input fields(price,weight). How would you make the input fields change without writing in them?
So after a long time of searching and trying stuff out (without much luck) I've learned that I need to use ajax for this to work. so I have tried a bunch and this is the code I've tried edit so it would work.
getAllproduct is just a select that fetches all the data inside my table with products. this is id, name, item_number, price, weight. anyhow here is my code
<?php
$sth = $db->prepare("SELECT `price`,`weight` FROM product");
$sth->execute();
$row = $sth->fetch(PDO::FETCH_ASSOC);
$row = array();
json_encode($row);
?>
product.php
<div class="form-group col-2">
<label for="product">Item number</label>
<?=#$error['product']?>
<select class="form-control" name="product" id="product" onChange="getproduct(this.value)">
<?php foreach ($csv->getAllproduct() as $csv) { ?>
<option value="<?= #$csv->id ?>" selected><?= #$csv->product?></option>
<?php } ?>
</select>
</div>
<div class="form-group col-2">
<label for="weight">weight</label>
<?=#$error['weight']?>
<input type="text" name="weight" id="weight" class="form-control">
</div>
<div class="form-group col-2">
<label for="price">price</label>
<?=#$error['price']?>
<input type="text" name="price" id="price" class="form-control">
</div>
<div class="input-group">
<button type="submit" style="margin-left:15px; margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Opret" name="btn_opret_maal">Submit</button>
</div>
<script>
function getproduct(val){
$.ajax({
type:"POST",
url:"pages\call.php",
data: 'product='+val,
success: function(response){
var result = JSON.parse(response);
if (result.response == true) {
var data = result.rows;
$("#weight").val(data[0].weight);
$("#price").val(data[0].price);
}else if (result.response == false) {
$('#product').append('<option>No products were found!</option>');
}
}
});
}
</script>
What I expect to be able to do is select an item number and it will automatically populate the inputfields price and weight with the data inside the database from the item number.
I haven't learned a lot of Ajax/js so Any help is appreciated.
Attempt: on other project using this code. havent gotten it to work yet.
<form class="row" method="POST" >
<div style="border-color:#dddddd;" class="dropdown-divider col-12"></div>
<script>$('#Varenummer').on('change', function() {
var selectedOption = $(this).find('option:selected');
$('#Tolminus').val(selectedOption[0].dataset.Tolminus);
$('#Tolplus').val(selectedOption[0].dataset.Tolplus);
});
</script>
<div class="form-group col-2">
<label for="Varenummer">Varenummer</label>
<?= #$error['Varenummer'] ?>
<select class="form-control" name="Varenummer" id="Varenummer">
<?php
foreach ($csv->getAllVarenummer() as $csv) {?>
<option value="<?= #$csv->id ?>" data-Tolminus="<?= #$csv->Tolminus ?>"
data-Tolplus="<?= #$csv->Tolplus ?>"><?= #$csv->Varenummer ?></option>
<?php }?>
</select>
</div>
<div class="form-group col-2">
<label for="Tolminus">Tol -</label>
<?= #$error['Tolminus'] ?>
<input type="text" name="Tolminus" id="Tolminus" class="form-control" value="">
</div>
<div class="form-group col-2">
<label for="Tolplus">Tol +</label>
<?= #$error['Tolplus'] ?>
<input type="text" name="Tolplus" id="Tolplus" class="form-control" value="">
</div>
<div class="input-group">
<button type="submit" style="margin-left:15px; margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Opret" name="btn_opret_maal">Submit</button>
</div>
the jquery scrips and others are added in the footer.
As you asked above in comments: i need it to the input to change when i select an option. can i still only use php?...
Yes.
You might not need ajax at all. For your task I'd recommend to preload weight and price values into data- attributes of corresponding option elements. Then, on the select change, just get those values and paste them to inputs.
$('#product').on('change', function() {
var selectedOption = $(this).find('option:selected');
$('#weight').val(selectedOption[0].dataset.weight);
$('#price').val(selectedOption[0].dataset.price);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="form-group col-2">
<label for="product">Item number</label>
<select class="form-control" name="product" id="product">
<option disabled selected>Choose product...</option>
<option value="1" data-weight="100" data-price="1000">Product 1</option>
<option value="2" data-weight="50" data-price="200">Product 2</option>
<option value="3" data-weight="25" data-price="115">Product 3</option>
</select>
</div>
<div class="form-group col-2">
<label for="weight">weight</label>
<input type="text" name="weight" id="weight" class="form-control">
</div>
<div class="form-group col-2">
<label for="price">price</label>
<input type="text" name="price" id="price" class="form-control">
</div>
<div class="input-group">
<button type="submit" style="margin-left:15px; margin-bottom: 15px; z-index: 5" class="btn btn-success" value="Opret" name="btn_opret_maal">Submit</button>
</div>
For the PHP generated select (assuming the getAllproduct method returns weight and price properties):
...
<div class="form-group col-2">
<label for="product">Item number</label>
<?=#$error['product']?>
<select class="form-control" name="product" id="product">
<?php foreach ($csv->getAllproduct() as $csv) { ?>
<option value="<?= #$csv->id ?>" data-weight="<?= #$csv->weight ?>" data-price="<?= #$csv->price ?>"><?= #$csv->product?></option>
<?php } ?>
</select>
</div>
...
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
i am facing a problem in this code actually i want form details on email id when when submitted the form and its redirect to select option . i am trying below file name contactttry.php for form details is working file but ths code is not working for redirect.
i received form details on my email id but page not redirect to select tag so help me in this code or suggest a new code.
i am facing a problem in this code actually i want form details on email id when when submitted the form and its redirect to select option . i am trying below file name contactttry.php for form details is working file but ths code is not working for redirect.
i received form details on my email id but page not redirect to select tag so help me in this code or suggest a new code.
Thank you in advance
this is my Form code:
<form role="form" action="contactttry.php" class="contact-form" id="contact-form" method="post">
<div class="form-group">
<select class="form-control" id="se1" NAME="section" onChange="SelectRedirect();">
<Option value="">Select Section</option>
<Option value="PHP">PHP</option>
<Option value="ASP">ASP</option>
<Option value="MySQL">MySQL</option>
<Option value="JS">JavaScript</option>
<Option value="HTML">HTML</option>
</select>
</div>
<div class="form-group">
<div class="controls">
<input type="text" placeholder="Name" name="name" id="name" required>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="email" class="email" placeholder="Email" name="email" id="email" required >
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="text" class="requiredField" placeholder="Mobile No." name="phone" id="phone" required>
</div>
</div>
<button type="submit" id="submit" class="btn-system btn-large" >Submit</button>
<div id="success" style="color:#34495e;"></div>
</form>
<!-- End Contact Form -->
contactttry.php File:
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$sub = $_POST['subject'];
$phone = $_POST['phone'];
$intrest = $_POST['message'];
$from = $txtemail;
$from_name = $txtname;
$to = "xyz#gmail.com";
$to_name = $name; `enter code here`
$subject = "Contact From IJLTEMAS";
$body ="
Name : ". $name."
Email: ".$email."
Phone: ".$phone."
Subject: ".$sub."
Message: ".$intrest."";
if (filter_var($email, FILTER_VALIDATE_EMAIL))
mail($to, $subject, $body);
?>
<script>
function SelectRedirect(){
// ON selection of section this function will work
//alert( document.getElementById('s1').value);
switch(document.getElementById('s1').value)
{
case "PHP":
window.location="url1/";
break;
case "ASP":
window.location="url2/";
break;
case "MySQL":
window.location="url3/";
break;
case "JS":
window.location="url4/";
break;
case "HTML":
window.location="url/";
break;
/// Can be extended to other different selections of SubCategory //////
default:
window.location="homeurl/"; // if no selection matches then redirected to home page
break;
}// end of switch
}
//////////////////
</script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script>
$(document).ready(function(){
alert("hi");
$("#se1").change(function(){
switch($("#se1").value())
{
case "PHP":
window.location="url1/";
break;
case "ASP":
window.location="url2/";
break;
case "MySQL":
window.location="url3/";
break;
case "JS":
window.location="url4/";
break;
case "HTML":
window.location="url/";
break;
/// Can be extended to other different selections of SubCategory //////
default:
window.location="homeurl/"; // if no selection matches then redirected to home page
break;
}// end of switch
});
});
//////////////////
</script>
<form role="form" action="contactttry.php" class="contact-form" id="contact-form" method="post">
<div class="form-group">
<select class="form-control" id="se1" NAME="section" onChange="SelectRedirect();">
<Option value="">Select Section</option>
<Option value="PHP">PHP</option>
<Option value="ASP">ASP</option>
<Option value="MySQL">MySQL</option>
<Option value="JS">JavaScript</option>
<Option value="HTML">HTML</option>
</select>
</div>
<div class="form-group">
<div class="controls">
<input type="text" placeholder="Name" name="name" id="name" required>
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="email" class="email" placeholder="Email" name="email" id="email" required >
</div>
</div>
<div class="form-group">
<div class="controls">
<input type="text" class="requiredField" placeholder="Mobile No." name="phone" id="phone" required>
</div>
</div>
<button type="submit" id="submit" class="btn-system btn-large" >Submit</button>
<div id="success" style="color:#34495e;"></div>
</form>
<!-- End Contact Form -->
form action="samepage.php"
if(isset($_POST['submit']))
{
//do email function here and then
switch ($_POST['section']) {
case "PHP":
header('Location:http://www.w3schools.com/js/js_switch.asp');
exit();
break;
}
}
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.
Stumped, var-dump($_POST) always returns array[0] {} PHP mail though always succeeds. Variables in html side are what I expect when viewed in the debugger. Fails with both register_globals on and off.
<!-- html code (in contact.php) -->
<form name="hhcform" method="POST" action="sendmail.php" onsubmit="return ValidateForm();" enctype="text/plain">
First Name: <input type="text" name="firstname" value="" size="25">
<span id="firstnameErr" style="color:red">*</span>
<br><br>
Last Name: <input type="text" name="lastname" value="" size="25">
<span id="lastnameErr" style="color:red">*</span>
<br><br>
Email Address: <input type="text" name="emailaddress" value="" size="25">
<span id="emailErr" style="color:red">*</span>
<br><br>
Select a Topic: <span id="topicErr" style="color:red">*</span><br>
<div class="radio-block">
<input type="radio" name="topic" value="Insurance"> Accepted Insurance<br><br>
<input type="radio" name="topic" value="Hours"> Office Hours<br><br>
<input type="radio" name="topic" value="Refills"> Prescription Refills<br><br>
<input type="radio" name="topic" value="Patients"> Accepting New Patients<br><br>
<input type="radio" name="topic" value="Website"> Website Issues<br><br>
<input type="radio" name="topic" value="Other"> Other<br><br>
</div>
Comments: <span id="commentErr" style="color:red">*</span><br>
<textarea name="comments" rows="10" cols="25"></textarea><br><br>
<input type="submit" value="Send">
<input type="reset" value="Reset" onclick="ClearErrors();"><br><br>
</form>
PHP code (in sendmail.php)
<?php
var_dump($_POST);
$firstname = $_POST['firstname'];
$lastname = $_POST['lastname'];
$email = $_POST['emailaddress'];
$topic = $_POST['topic'];
$comments = $_POST['comments'];
$recipient = "emailaddress#domainbame.com";
$mailheader = "From: " . $email . "\r\n";
if(mail($recipient, $topic, $comments, $mailheader))
{
echo "Email Sent, Thank You!" . " -" . "<a href='contact.php'
style='text-decoration:none;color:#ff0099;'> Return to Contact Us Form</a>";
}
else
{
echo "Email failed to send" . "-" . "<a href='contact.php'
style='text-decoration:none;color:#ff0099;'> Return to Contact Us Form</a>";
}
?>
Take out
enctype="text/plain" in the form, this should fix the issue.
The issue might be with your enctype
enctype="text/plain"
Try
enctype="multipart/form-data"
instead, unless you have a good reason for using text/plain.