I know this has been posted several times, but I just can't seem to figure it out. Here's an overview of what I'm trying to do:
I have an HTML form located in a PHP file. On form submit, the action calls the same PHP page where the form is located. In doing this, my server runs a bit of PHP code at the top of that page that gathers the information inserted into the form and sends it to me in an email. After the email is sent, I want to hide the DIV containing my form and replace it with a hidden one that will appear, thanking the user for submitted the form, etc.
My question is, how do I get the PHP script to run the Javascript function? My email sends just fine, I just can't get the DIV to replace.
Here's my code.
HTML
<form id="contact-form" name="contact-form" action="contact.php" method="post">
<table>
<tr>
<td width="79"><p><font style="color:#ebe775;">*</font>Name:</p></td>
<td width="309"><input type="text" name="name" id="name" placeholder="First Last" size="45" required></td>
</tr>
<tr>
<td><p><font style="color:#ebe775;">*</font>Email:</p></td>
<td><input type="email" name="email" id="email" size="45" required></td>
</tr>
<tr>
<td><p><font style="color:#ebe775;">*</font>Message:</p></td>
<td><textarea name="message" id="message" cols="42" rows="8" required></textarea></td>
</tr>
<tr>
<td style="text-align:center;" colspan="2"><input type="submit" value="Submit" name="submit" id="submit"><input type="hidden" name="parse_var" id="parse_var" value="contact-form"></td>
</tr>
</table>
</form>
</div>
<div id="hidden_div" style="display:none;">
<h2>Thank You!</h2>
<p>Your form was submitted. We'll review it and get back with you as soon as we can.</p>
</div>
</div>
</div>
PHP Script
<?php
if ($_POST['parse_var'] == "contact-form"){
$emailSubject = 'New CONTACT Form Submission';
$to = 'my.email#server.com';
$name = $_POST['name'];
$email = $_POST['email'];
$message = $_POST['message'];
$body = <<<EOD
The following information was submitted using the CONTACT form at JakesCreativeDesign.com.
Name: $name
Email: $email
Message: $message
EOD;
$headers = "From: contact#jakescreativedesign.com\r\n";
$headers .= "Content-type: text/html\r\n";
mail("$to", "$emailSubject", "$body", "$headers");
}
?>
Javascript Function
<script type="text/javascript">
function showHide() {
var div = document.getElementById("hidden_div");
if (div.style.display == 'none') {
div.style.display = '';
}
else {
div.style.display = 'none';
}
var div = document.getElementById("form");
if (div.style.display == '') {
div.style.display = 'none';
}
else {
div.style.display = '';
}
}
</script>
You don't. PHP runs on the server. Javascript runs on the client. At most PHP could do somethign like
<?php
echo <<<EOL
<script type="text/javascript">
yourFunction();
</script>
EOL;
?>
so that the function's called when the page is loaded by the browser. But otherwise, once the page is sent off to the client, there is NO WAY for PHP to reach out and tell that page to do something again.
You are looking at it backwards. PHP cannot run javascript because PHP runs on the server and javascript runs in the user's browser. You can call PHP from javascript (via AJAX) but you cannot call javascript from PHP.
Related
New to PHP-
ran through tutorials and several other threads regarding this issue and I'm struggling quite a bit. I am creating a single page application without a framework and currently running on localhost. Upon submitting the form, I am greeted with a message that says Cannot POST /mail.php
I figure I have the mail.php file in the wrong spot, so I moved it around in every single directory until I decided to just put a copy of it in EVERY directory to try and get something to work. I even posted it in the contact.js file.
contact.js
import AbstractView from "./AbstractView.js";
export default class extends AbstractView {
constructor() {
super();
}
async getHtml() {
return `
<div class="container">
<div class="contact">
<form action="mail.php" method="post">
<table>
<tr>
<td>
<input type="text" name="name" placeholder="Name"><br />
<input type="text" name="email" placeholder="Email"><br />
<input type="text" name="subject" placeholder="Subject"><br />
</td>
<td>
<textarea name="message" rows="5" cols="25" placeholder="Message"></textarea><br />
</td>
</tr>
</table>
<div style="float: right"><button type="submit" name="submit">Send</button> </div>
</form>
</div>
</div>
`;
}
}
mail.php
<?php
if(isset($_POST['submit'])){
$name = $_POST['name'];
$email = $_POST['email'];
$subject = $_POST['subject'];
$message = $_POST['message'];
$header = "From: ".$name."<".$email.">\r\n";
$recipient = "MYEMAIL#gmail.com";
mail($recipient, $subject, $message, $header)
or die("Error sending mail");
echo "messsage sent";
}
?>
file structure
Any help or guidance would be greatly appreciated
You need to use an HTTP server which can execute PHP programs.
You appear to have written your own server using Node.js then it won't support PHP unless you have designed it - explicitly - to do so (and you'd be better off using server-side JS instead of PHP if you were already in a Node.js ecosystem).
I have put together a simple contact form for my website. Using PHP to POST the data and send directly to my email address. But for some reason every time I visit the page on my website. I still get the test message Displaying under the Form. Then when I reload the website and visit the link again it still displays the thank you message. and automatically sends an email. Im still in testing mode 2 days before my launch and I need this figure out. Considering I am novice to php I dont know what goes where.... check out my website to get a live view https://trillumonopoly.com (click "Contact Us" link in menu) I would like for the contact form to disappear and echo the thank you message once sent. And reset after the page is reloaded. I am also using Jquery ajax to load all my pages into a div container. So I would like to keep the content inside that div without forwarding to the Echo message page, leaving my index page
Heres My ajax code
$(document).ready(function () {
loadMainContent('main');
$('body').delegate('.navMenu', 'click', function (event) {
event.preventDefault();
loadMainContent($(this).attr('href'));
});
});
function loadMainContent(page) {
$('#main').load('pages/' + page + '.php');
}
here is html for the form:
<div class="general row container-fluid"><br>
<center><img src="img/divider.png" class="img-fluid"></center>
<div class="col-lg-6 col-sm-12">
<img src="img/logo.png" class="img-fluid" height="540px" width="540px">
</div>
<div class="col-lg-6 col-sm-12 container"><center>
<br><h1 class="form-title">Contact Us</h1><br></center>
<div class="container">
<form action="pages/mail.php" method="GET" class="box2">
NAME:
<input type="text" name="name" placeholder="YOUR NAME HERE" required>
<br><br>
EMAIL:
<input type="email" name="email" placeholder="YOUR EMAIL HERE" required>
<br><br>
MESSAGE:<br>
<textarea name="message" rows=10 cols=23 placeholder="YOUR MESSAGE HERE" required></textarea>
<br><Br>
<button type="submit" value="Message Sent" class="btn btn-danger btn-lg" style="background-color:"red">SUBMIT</button
</form>
<center><?php include('mail.php'); ?></center>
</div>
</div>
</div>
Here is My simple PHP:
<?php
$name = $POST['name'];
$email = $POST['email'];
$message = $POST['message'];
mail("info#trillumonopoly.com","ILLUMONOPOLY WEB Contact", $message,"From: $email\r\n");
echo "Thank You For Contacting Us!";
?>
Better than check everything before send mail.
if(isset($_POST['name']) && isset($_POST['email']) && isset($_POST['message'])){
$name = $POST['name'];
$email = $POST['email'];
$message = $POST['message'];
mail("info#trillumonopoly.com","ILLUMONOPOLY WEB Contact", $message,"From: $email\r\n");
echo "Thank You For Contacting Us!";
}
And send POST request to the index, not mail.php.
<form action="" method="POST">
...
So the user can see your message at the end of contact form.
I have a mail form on my HTML that calls a PHP.
When I click Submit, It redirects to the PHP and shows various alerts about the form.
I want it not to redirect to the PHP and show alerts on HTML.
I tried to redirect back from PHP but in that case it didn't show any alerts.
I couldn't manage to do that. I've read may similar posts but they didn't help.
Can anyone help?
HTML Form:
<form method="post" action="sendmail.php">
<input name="id" type="hidden" value="1775">
<table cellpadding="10px" border="0">
<tr>
<td align="right"><iletisimmetni>ad soyad :</iletisimmetni></td>
<td><input class="yuvarlak" name="sender_name" type="text"></td>
</tr>
<tr>
<td align="right"><iletisimmetni>e-posta :</iletisimmetni></td>
<td><input class="yuvarlak" name="sender_email" type="email"></td>
</tr>
<tr>
<td align="right"><iletisimmetni>konu :</iletisimmetni></td>
<td><input class="yuvarlak" name="subject" type="text"></td>
</tr>
<tr>
<td align="right" valign="top"><iletisimmetni>mesaj :</iletisimmetni></td>
<td><textarea class="yuvarlak" rows="10" cols="40" name="message"
onkeyup="textLimit(this, 250);"></textarea></td>
</tr>
<tr>
<td colspan="2" align="right"><input class="urunbutton" value="Gönder" name="send"
type="submit" id="send"></td>
</tr>
</table>
</form>
Here is the PHP:
<?php
function spamcheck($field)
{
$field=filter_var($field, FILTER_SANITIZE_EMAIL);
if(filter_var($field, FILTER_VALIDATE_EMAIL))
{
return TRUE;
}
else
{
return FALSE;
}
}
if (isset($_REQUEST['sender_email']) && !empty($_REQUEST['sender_name']) &&
!empty($_REQUEST['subject']) && !empty($_REQUEST['message']))
{
$mailcheck = spamcheck($_REQUEST['sender_email']);
if ($mailcheck==FALSE)
{
echo "<script>alert('Lütfen geçerli bir e-posta adresi girin.')</script>";
// $URL="http://pantuff.com/testing/iletisim.html";
// header ("Location: $URL");
}
else
{//send email
$sender_name = $_REQUEST['sender_name'] ;
$sender_email = $_REQUEST['sender_email'] ;
$subject = $_REQUEST['subject'] ;
$message = $_REQUEST['message'] ;
$headers = "From: ".$sender_name." <".$sender_email.">\r\n";
$headers .= "MIME-Version: 1.0\r\n";
$headers .= "Content-Type: text/html; charset=utf-8\r\n";
mail("info#pantuff.com", "$subject", "$message" . " " . "$sender_name", $headers);
echo "<script>alert('Mesajınız alınmıştır. Teşekkür ederiz.')</script>";
// $URL="http://pantuff.com/testing/iletisim.html";
// header ("Location: $URL");
}
}
else
{
echo "<script>alert('Lütfen tüm alanları doldurun.')</script>";
// $URL="http://pantuff.com/testing/iletisim.html";
// header ("Location: $URL");
}
?>
Thanks.
It looks like you are trying to validate the form prior to sending it. To do this on the client side prior to actually submitting the form, you can use javascript. jQuery has a plugin that might save you some time:
http://bassistance.de/jquery-plugins/jquery-plugin-validation/
change your code as
<form method="post" action="">
and then write the php code in the same html page.
For validation of form use Javascript code on the same page.
I think what you're trying to do here (and what is common practice) is to embed your HTML code into the PHP file, instead of having 2 separate files.
It is perfectly valid to have HTML code outside of <?php ?> tags.
For example you would have a single file sendmail.php look something like this:
<?php
if(isset($_POST['id']))
{
// checks and alerts
// ...
}
?>
<form method="post" action="sendmail.php">
<input name="id" type="hidden" value="1775">
<table cellpadding="10px" border="0">
<!-- ... -->
</form>
And your client would access the from via the URL to the sendmail.php.
You can combine it into one file example index.php
<?php
//php code in here
?>
<form action="index.php">
<input type=text />
<!-- html code in here -->
</form>
when we access php file, php will be executed by server. HTML and javascript will be read by browser.
when you redirect, the script is never read by browser because the server give browser another page.
I have a contact form that I'm using Jquery .load to import a php file into any of the pages the nav will be on. Example below.
http://madaxedesign.co.uk/dev/index.html
I'm aware that the action form needs to be changed so it is connected to the right place. But how would I do that if it is on different pages and imported into a page. Because at the moment it is set to contact.php but after it is submitted it goes to that page and doesn't import the message into the pop up. So really I need it to be the file name depending on what page it is on.
So I suppose the question is how do I get the message after submit to appear inside the pop up instead of on a different page?
Code:
<?php
$your_email = "maxlynn#madaxedesign.co.uk";
$subject = "Email From Madaxe";
$empty_fields_message = "<p>Please go back and complete all the fields in the form.</p>";
$thankyou_message = "<p>Thank you. Your message has been sent. We Will reply as soon as possible.</p>";
$name = stripslashes($_POST['txtName']);
$email = stripslashes($_POST['txtEmail']);
$message = stripslashes($_POST['txtMessage']);
if (!isset($_POST['txtName'])) {
?>
<form method="post" action="contact.php">
<div id="NameEmail">
<div>
<label for="txtName">Name*</label>
<input type="text" title="Enter your name" name="txtName" />
</div>
<div>
<label for="txtEmail">Email*</label>
<input type="text" title="Enter your email address" name="txtEmail" />
</div>
</div>
<div id="MessageSubmit">
<div>
<textarea maxlength="1200" title="Enter your message" name="txtMessage"></textarea>
<label for="txtMessage">Message</label>
</div>
<div>
<input type="submit" value="Submit" /></label>
</div>
</div>
</form>
<?php
}
elseif (empty($name) || empty($email) || empty($message)) {
echo $empty_fields_message;
}
else {
$referer = $_SERVER['HTTP_REFERER'];
$this_url = "http://".$_SERVER['HTTP_HOST'].$_SERVER["REQUEST_URI"];
if ($referer != $this_url) {
echo "You do not have permission to use this script from another URL, nice hacking attempt ;p.";
exit;
}
mail($your_email, $subject, $message, "From: $name <$email>");
echo $thankyou_message;
}
?>
You should use ajax, send the email without refreshing page.
What you want to do is only possible in javascript, this is a language that gets executed by the browser. Javascript self is a nasty language but there are many extensions/plugins to make this very easy like jQuery. i suggest you to learn this language, you will find a new world opening in web development ;-). eg: http://learn.jquery.com/
give your form an id:
<form method="post" id="test-form" action="contact.php">
so you can reference to it with jquery
now you can catch the form submit action with jQuery:
$('#test-form').submit(function() {
//send your data to your server and get the html data
$.post('contact.php', $(this).serialize(), function (data){
//here you can add the (html)data returned by the action to your page.
$('body').append(data); //append data to body of html page
})
return false; //stop form from going to the next page
});
this code is based on a javascript plugin: jQuery, if you want to do anything dynamic on your page without reloading the page, you need to use javascript.
I've taken a few scripts from elsewhere on the Stack to create a contact form that emails me when the user submits.
HTML:
<form onsubmit="return getContent()">
<fieldset>
<input name="name" value="NAME" style="max-width:15%" type="text"/>
<input name="email" value="EMAIL" style="max-width: 30%" type="text"/>
<div id="message" contenteditable="true" name="message" value="expanding textarea">HELLO</div>
<textarea id="my-textarea" value="MESSAGE" style="display:none"></textarea>
<input type="submit" style="margin-right:0" value="Submit" />
</fieldset>
</form>
SCRIPTS:
function getContent(){
document.getElementById("my-textarea").value = document.getElementById("message").innerHTML;
}
$('form').submit( function() {
$.ajax({
type: "POST",
url: "email.php",
data: $(this).serialize(),
success: function() {
// Update page with success message
}
});
return false;
});
PHP:
<?php
$recipient = "my.email#whatever.com"; //recipient
$Name = ($_POST['name']); //senders name
$email = ($_POST['email']); //senders e-mail adress
$mail_body = ($_POST['message']); //mail body
$header = "From: ". $Name . " <" . $email . ">\r\n"; //optional headerfields
mail($recipient, $subject, $mail_body, $header); //mail command :)
?>
The script SHOULD get the content entered in the contenteditable div and pass it through to the hidden textarea, then submit to my email. However, it's currently only passing through the "name" and "email" fields and leaving the body of the email blank.
What have I missed here?
EDIT: Made a small error in the code hidden textarea above, value="MESSAGE" not "SUBJECT". Still, code not working.
Contenteditable content doesn't get passed through the form when submitted.
But, it looks like you're using some JS to get the content of the editable content div and put it into the textarea with a name of "subject".
Therefore, it will be accessible through $_POST['subject'] only.
Also, you're doing an onsubmit="" in the html and a on submit in the JS file. I don't think both will work, you'd be better combining the two (i.e. just use the JS file).
It also won't work without JS enabled, which I'd say is a bigger problem.