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.
Related
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();".
I have created a news system on my web page where I use while loop to echo my news on a page. With news I created a form for news where I target it by name and I want to use jquery to process the results. When I use php it works fine but I want to avoid reloading page with submitting form and immediate post comment to page.
my form looks like this:
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
my php code looks like this:
if (isset($_POST['comments' . $row['news_id'] . '']) === true && empty($_POST['comment']) === false) {
global $user_data;
$user_id = $user_data['user_id'];
$connect_id = $_POST['news_id'];
$type = $_POST['type'];
$time = date('Y-m-d H:i:s');
$comment = $_POST['comment'];
$comment = sanitize($comment);
mysql_query("INSERT INTO `comments` (`user_id`, `connect_id`, `type`, `time`, `comment`) VALUES ('$user_id', '$connect_id', '$type', '$time', '$comment')");
}
If I try to do somethink like this:
$(".comment-btn").click(function(e) {
e.preventDefault();
var text = $('.comment-area').val();
console.log(text);
$('.comment-area').val('');
});
It targets only the form where is the first news and doesn't target all the forms.
Is there any way to do this differently???
Thanks for helping.
You could try something like the following:
$(".comment-btn").each(function(){
$(this).click(function(e) {
e.preventDefault();
var commentArea = $(this).siblings(".comment-area");
var text = commentArea.val();
console.log(text);
commentArea.val('');
});
});
The problem is that while this $(".comment-btn") returns an array of all the button in the forms you mentioned, this $(".comment-btn").click(... attaches a click event handler only for the first item of the array.
$(function(){
$(".comment-btn").each(function(){
$(this).click(function(e){
e.preventDefault();
var commentArea = $(this).siblings(".comment-area");
var text = commentArea.val();
console.log(text);
commentArea.val('');
});
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
You could use jQuery on function to bind "click" event to all buttons with comment-btn class. However, it'll be important to then identify which comment-area you want to refer to. If that is not done, it'll simply erase the values of all fields / textareas with class comment-area.
$(".comment-btn").on("click", function(e) {
e.preventDefault();
var text = $(this).parent().find('.comment-area').val();
console.log(text);
$(this).parent().find('.comment-area').val('');
});
Working example with the only change being that input type for buttons is changed from "submit" to "button":
https://jsfiddle.net/L87n4Ljo/
Likewise, if you'd like to submit a particular form when the button is clicked, you'll have to do so by specifically identifying that form by using parent() function.
Try this, here we are blocking the default form submit which i think you will need if you don't want to reload the page.
$(".comments").on("submit", function(e) {
e.preventDefault();
var text = $(this).find('.comment-area').val();
console.log(text);
$(this).find('.comment-area').val('');
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form action="" method="post" enctype="multipart/form-data" class="comments" id="comments">
<textarea id="comment_area" class="comment-area" name="comment" placeholder="Dodajte svoj komentar tukaj..."></textarea>
<input type="hidden" id="news_id" name="news_id" value="' . $row['news_id'] . '">
<input type="hidden" id="type" name="type" value="0">
<input type="submit" id="comment_btn" class="comment-btn" name="comments<php echo $row['news_id'] ?>" value="Objavi">
</form>'
I am not able to edit this 'contact us' form code work and deliver messages to my mail-box.
Say I wanted to get messages delivered to my email: doherty#noob.com, how do I edit this code do the task?
<div class="conatct-form">
<ul class="form">
<li>
<input type="text" class="text" value="Name*" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Name*';}" >
</li>
<li>
<input type="text" class="text" value="Email*" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Email*';}" >
</li>
<li>
<textarea value="Message*:" onfocus="this.value = '';" onblur="if (this.value == '') {this.value = 'Your Message*';}">Message*</textarea>
</li>
<div class="sub-button">
<input type="submit" value="SEND">
</div>
</ul>
</div>
I've optimized your code and added some PHP code
PHP code
<?php
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
if (isset($name, $email, $message)) {
// Insert into database
$query = mysql_query("INSERT INTO contacts ...");
if ($query) {
// send email using phpmailer, sendmail, ...
mail($mail, 'Subject', $message, '...');
}
}
?>
HTML
<form id="contact-form" method="post">
<ul>
<li>
<!--
Substituting the code below
<input type="text"
value="Name *"
onfocus="this.value=''"
onblur="if (this.value == '') {this.value = 'Name *'}" />
use the placeholder attribute instead
-->
<input type="text" name="name" placeholder="Name *" />
</li>
<li>
<input type="text" name="email" placeholder="Email *" />
</li>
<li>
<textarea name="message" placeholder="Message *"></textarea>
</li>
<li>
<input type="submit" value="Send" />
</li>
</ul>
</form>
You need to wrap your HTML inputs in a element in order for proper form to work.
Thus, you'll need the following tag:
<form action='url_to_submit_to' method='POST' enctype='application/x-www-form-urlencoded'>
<!-- Rest of your code here -->
</form>
See the Mozilla documentation for more details on the format and arguments of the <form> tag:
https://developer.mozilla.org/en-US/docs/Web/HTML/Element/form
Here submit is not happening because the content is not wrapped inside a form tag.
All the content should be wrapped inside tag which has action attribute to some php/java file which validate the data passed by user and commits to database.
Please check form tag on mdn for more information.
rather than you using
if (isset($name, $email, $message)) {...}
there HTML5 'required' will be better in your tags. e.g
Also, you submit type needs to have a name. the name will be used to process your form.
contact.php page. the form below processes itself since the method is its name, contact.php.
<form id="contact-form" method="post" action="contact.php" >
<input type="text" name="name" placeholder="Name" />
<input type="text" name="subject" placeholder="Subject *" />
<input type="text" name="email" placeholder="Email *" />
<textarea name="message" placeholder="Message *"></textarea>
<input type="submit" value="Send" name="send"/>
</form>
<?php
if (isset($_POST['send'])) {
$to = "youremail#something.com";
$subject = $_POST['subject'];
$message = $_POST['message'];
$from = $_POST['email'];
$headers = "From: $from $name";
$sent = mail($to,$subject,$message,$headers);
if ($sent) {
echo "<p style = 'color: #00ff00;'>Message was sent.</p>";
}
else {
echo "<p style = 'color: #ff0000;'>Message was not sent.</p>";
}
}
?>
User enters their name here as part of a form.
<p>Name <font color="red">(required) </font> <input name="flname" required="required" placeholder="Your Name" </p>
This solution currently provides a way of providing a sample text that can also be edited, and the PHP can run inside it, unlike <textarea>. However, my problem is that unlike <textarea>, I cannot seem to get the <div contenteditable... to submit its information to the email php file I have set up on the server. Anyone have any idea how I'd implement this.
<div contenteditable="true" name="message" required="" placeholder="Your Message" >Dear <?php echo "$mptitle $mpsecondname" ?>, <p> Please support us... </p>
<p> Kind Regards, </p>
<script type="text/javascript"> document.write(document.getElementById('flname').id);</script>
</div>
<div align="center">
# Update 2:
Hi,
Thank you both for your quick resposnes.
I tried to implement your solution here:
<div align="left">
<form action="form.php" method="post" enctype="multipart/form-data">
<p>Name <font color="red">(required) </font> <input name="flname" required="required" placeholder="Your Name" </p>
<p>Email <font color="red">(required) </font> <input name="emailfrom" type="email" required="required" placeholder="Your Email"> </p>
<p>Address <font color="red">(required) </font> <input name="address" type="name" required="required" placeholder="Address"> </p>
<p>City <font color="red">(required) </font> <input name="city" type="name" required="required" placeholder="City"> </p>
<p>Postcode <font color="red">(required) </font> <input name="postcode" type="name" required="required" placeholder="Postcode"> </p>
<p>What is 2+2? <font color="red">(required) </font> <input name="human" required placeholder="Type Here"> </p>
<p> <b> You can edit the text below as much or as little as you wish </b> </p>
<div contenteditable="true" required="" placeholder="Your Message" >Dear <?php echo "$mptitle $mpsecondname" ?>, <p> Please support us... </p> <p> Kind Regards, </p>
</div>
<input type=hidden name=userContent id=userContent>
<script>
var el=document.getElementById('userForm');
el.addEventListener('submit', function() {
var elInput=document.getElementById('userContent');
var elDiv=document.getElementById('divContent');
elInput.value = elDiv.innerHTML;
});
</script>
<div align="center">
<input id="cancel" name="cancel" type="submit" value="Cancel" />
<input id="submit" name="submit" type="submit" value="Submit">
</form>
</div>
</div>
PHP:
<?php
ini_set('display_errors',1); error_reporting(E_ALL);
include('mplookup.php');
$name = $_POST['flname'];
$email = $_POST['emailfrom'];
$message = $_POST['userContent'];
$address = $_POST['address'];
$city = $_POST['city'];
$postcode = $_POST['postcode'];
$human = $_POST['human'];
$to = "";
$body = $message;
$subject = 'From: $email \r\n : Sisi\'s visit to the UK: Sent using EG4DEMUK\'s Tool ';
?>
<?php
if ($_POST['submit']) {
if (mail ($to, $subject, $body, $email))
{
echo '<p>Thank you for your email!</p>';
} else {
echo '<p>Oops! An error occurred. Try sending your message again.</p>';
}
}
?>
However, the emails outputed look like this
From: Hassan Ismail
E-Mail:
Message
Thanks in advance
A <div> is not a form element, so it won't be submitted. You need to implement an event listener on the submit event of the form that picks up the content of the <div> and puts it in a form element. Add a hidden <input> to the form for the purpose.
Here's a simple example:
<div id=divContent style="width:400px; height=200px;overflow:auto" contenteditable>Some content</div>
<form id=userForm>
<input type=hidden name=userContent id=userContent>
<input type=submit name=submit value="Send!">
</form>
<script>
var el=document.getElementById('userForm');
el.addEventListener('submit', function() {
var elInput=document.getElementById('userContent');
var elDiv=document.getElementById('divContent');
elInput.value = elDiv.innerHTML;
});
</script>
var el=document.getElementById('userForm');
el.addEventListener('submit', function() {
var elInput=document.getElementById('userContent');
var elDiv=document.getElementById('divContent');
elInput.value = elDiv.innerHTML;
});
<div id=divContent style="width:400px; height=200px;overflow:auto" contenteditable>Some content</div>
<form id=userForm>
<input type=hidden name=userContent id=userContent>
<input type=submit name=submit value="Send!">
</form>
<script>
getElementById('flname') ... is it clearly written in the name of the method that themethod gets an element by its Id, but not by his name. Use getElementsByName or set an id to you input tag. your input tag is not closed too ... don't use font - it is obsolete. if you want to submit tag content, use ajax, or setup a hidden field somwhere in the code, then use submit handler to set it with the content of the div before the actual submit.
<div id="yourdivid">....</div>
<input id="submitarea" type="hiden" name="submitarea">
$(function() {
$('#yourformid').submit( function() {
$('#submitarea').val($('#yourdivid').html());
});
});
I have a problem with the submit button: it just won't work. It seems to work fine with my previous forms. I'm using the Spry Validation as well. It's a simple HTML with a PHP. I can't see where is my mistake (and I'm just starting to learn PHP). I've looked around the forum already and on the internet, but I couldn't find an answer for my problem. I'm trying to get a basic form e-mailed to me with an option to upload a file within the same form. Does the problem come from the form formatting or the PHP file? Here are the codes I have:
This is the HTML form located within a <body><div id="content">...</div></body>
<p><form action="upload.php" name="form1" id="form1" method="post" enctype="multipart/form-data">
<fieldset><legend><em>Please fill this form</em></legend>
First Name: <span id="sprytextfield1">
<input type="text" name="firstname" id="firstname" required="required" />
<span class="textfieldRequiredMsg">Please enter your first name.</span></span><br/><br/>
Last Name: <span id="sprytextfield2">
<input type="text" name="lastname" id="lastname" />
<span class="textfieldRequiredMsg">Please enter your last name.</span></span><br/><br/>
Job Title: <span id="sprytextfield3">
<input type="text" name="title" id="title" />
<span class="textfieldRequiredMsg">Please enter your desired title.</span></span><br/><br/>
Address: <span id="sprytextfield4">
<input type="text" name="address" id="address" />
<span class="textfieldRequiredMsg">Please enter your address.</span></span><br/><br/>
Postal Code: <span id="sprytextfield5">
<input type="text" name="postal" id="postal" />
<span class="textfieldRequiredMsg">(i.e.: A0A 0A0)</span><span class="textfieldInvalidFormatMsg"></span></span><br/>
<br/>
City: <span id="sprytextfield6">
<input type="text" name="city" id="city" />
<span class="textfieldRequiredMsg">Please enter the name of your city.</span></span><br/><br/>
Province: <span id="spryselect1">
<select name="province" id="province">
<option value="ontario">Ontario</option>
<option value="quebec">Quebec</option>
<option value="britishcolumbia">British Columbia</option>
<option value="alberta">Alberta</option>
<option value="manitoba">Manitoba</option>
<option value="saskatchewan">Saskatchewan</option>
</select>
</span><br/><br/>
Phone Number: <span id="sprytextfield7">
<input name="phone" type="text" id="phone" maxlength="13" />
<span class="textfieldRequiredMsg">(i.e.: XXX-XXX-XXXX)</span><span class="textfieldInvalidFormatMsg">(i.e.: XXX-XXX-XXXX)</span></span><br/>
<br/>
<hr />
Additional information:<br />
<textarea name="comments" id="comments" cols="50" rows="5"></textarea>
<br/><br/>
<label for="file">Resume/CV (PDF or Word format only):</label>
<input type="hidden" name="max" value="100000"/>
<input type="file" name="file" id="file"/><br><br />
E-mail:
<span id="sprytextfield8">
<input type="text" name="email" id="email" />
<span class="textfieldRequiredMsg">Your e-mail address is required.</span><span class="textfieldInvalidFormatMsg">(i.e.: aaa#aaaa.com)</span></span><br/>
<br/>
<br/>
<input name="submit" type="submit" value="Send" />
<input type="reset" name="reset" value="Clear" />
</fieldset>
</form></p>
</div>
</div>
This is the external PHP (upload.php) file located with the same bracket type of bracket as the previous HTML(same CSS and HTML body):
<?php
$allowedExts = array("pdf", "doc");
$temp = explode(".", $_FILES["file"]["name"]);
$extension = end($temp);
if ((($_FILES["file"]["type"] == "application/pdf")
|| ($_FILES["file"]["type"] == "aaplication/doc"))
&& ($_FILES["file"]["size"] < 20000)
&& in_array($extension, $allowedExts))
{
if ($_FILES["file"]["error"] > 0)
{
echo "Return Code: " . $_FILES["file"]["error"] . "<br>";
}
else
{
echo "Upload: " . $_FILES["file"]["name"] . "<br>";
echo "Type: " . $_FILES["file"]["type"] . "<br>";
echo "Size: " . ($_FILES["file"]["size"] / 1024) . " kB<br>";
echo "Temp file: " . $_FILES["file"]["tmp_name"] . "<br>";
if (file_exists("upload/" . $_FILES["file"]["name"]))
{
echo $_FILES["file"]["name"] . " already exists. ";
}
else
{
move_uploaded_file($_FILES["file"]["tmp_name"],
"upload/" . $_FILES["file"]["name"]);
echo "Stored in: " . "upload/" . $_FILES["file"]["name"];
}
}
}
else
{
echo "Invalid file";
}
$firstname=$_POST['firstname'];
$lastname=$_POST['lastname'];
$title=$_POST['title'];
$address=$_POST['address'];
$postal=$_POST['postal'];
$city=$_POST['city'];
$phone=$_POST['phone'];
$email=$_POST['email'];
$comments=$_POST['comments'];
$province=$_POST['province'];
$date=gmdate("M d Y");
print"<p><b>$date</b></p>";
print"<p>Thank you $firstname $lastname! We will get back to you.</p>";
$to="someuser#gmail.com";
$subject="Candidate Resume";
$body="Date:$date \n Subject:$subject \n First Name:$firstname \n Last Name:$lastname \n Title:$title \n Address:$address \n City:$city \n Province:$province \n Postal Code:$postal \n Telephone:$phone \n Email:$email \n Additional Information:$comments \n\n";
mail($to,$subject,$body);
?>
Your script works, just increase the filesize value in the if statement to something the will accommodate these types of files.
($_FILES["file"]["size"] < 500000)
Your were only allowing for 19k.
Check your PHP error log on your server to see if you can get some information on why its failing. That has helped me numerous times when debugging some code that wasn't working.