PHP form submission alert not working (no ajax) - javascript

This is my first question on StackOverflow - thanks in advance for your help!
I have an html form that emails me upon submission. The form submits successfully but I want it to display a submission confirmation message via pop up alert box before reloading the page. Any help is appreciated - though, I'll say now that I don't intend to use AJAX since I am not at all familiar yet. Thanks!
HTML:
<form method="post" action="php/contactForm.php">
<p class="formBox" id="nameBox">Name:</br><input type="text" id="contactName" name="contactName"></p>
<p class="formBox" id="emailBox">Email:</br><input type="email" id="contactEmail" name="contactEmail"></p>
<p>Message:</br><textarea id="contactMessage" name="contactMessage"></textarea></p>
<p><input type="submit" name="submit"></p>
</form>
PHP in "contactForm.php":
<?php
$name = $_POST['contactName'];
$email = $_POST['contactEmail'];
$message = $_POST['contactMessage'];
$body = $name . "\n" . $email . "\n\n" . wordwrap($message);
$alert = "<script>alert('Thank you for reaching out! Someone will be in touch soon.')</script>";
echo $alert;
mail('email#notmyactualemail.com', 'New Message from Website Contact Form!', $body);
header("Location: ../connect.html");
?>
p.s. If it helps to know, I am hosting on GoDaddy.

AJAX works to run code without having to refresh your page. The PHP code you have now will run after the page reloads. Therefore, there is no way without AJAX to send a genuine confirmation message before the page reloads.
You can, however, use the javascript onsubmit property to make a confirmation alert once the form is submitted, but that will not guarantee that the form was indeed submitted without error. Here's an example:
document.getElementById("myForm").onsubmit = function(){
window.alert("This is the confirmation message!\n\nThank you for submitting");
}
<form action="www.example.com" id="myForm" method="POST">
<input type="text">
<input type="submit">
</form>

Related

Success Message display on submit html form

I am trying to display a success message just above the submit button, but it’s directing me to a form page. Here it is.
I am trying to:
<!-- The form is on the deck.html page -->
<div class="row footer-newsletter justify-content-center">
<div class="col-lg-6">
<form action="forms/subscribe.php" method="post">
<input type="email" name="email" placeholder="Enter your Email"><input type="submit" value="Subscribe">
</form>
</div>
I am getting form inputs on my email, so where am I wrong in the below code?
// Create email headers
$headers = 'From: ' . $email_from . "\r\n" .
'Reply-To: ' . $email_from . "\r\n" .
'X-Mailer: PHP/' . phpversion();
#mail($email_to, $email_subject, $email_message, $headers);
?>
<!-- include your own success HTML here.
So I am getting form details to email, but the success
message below is appearing on /forms/subscribe.php
where actually I am looking to display just above
button
-->
Thank you for contacting us. We will be in touch with you very soon.
<?php
I tried on submit pop up, alert box, but it always took me to the subscribe page and I am looking to display just before the subscribe button.
We need to:
Capture and stop the submit event from continuing
Show the message
After some time (let's say 2 seconds), continue the submission.
Check the code below:
We attach an event listener to the form. When the 'submit' event happens, we want to execute our code. The e variable represents the event. We want to stop the event from doing its normal stuff (in this case, send the user to another page), so we say e.preventDefault().
I created a p element with the message on top of the form. This element is hidden by default, but if we add a class show to it, it appears. So, that's what we do. After preventing the event from continuing, we add this class to the message.
Finally, we use the setTimeout() function to count to 2 seconds (2000 ms) and then execute form.submit(), which sends the user to the subscribe page.
const form = document.querySelector('form');
const thankYouMessage = document.querySelector('#thank-you-message');
form.addEventListener('submit', (e) => {
e.preventDefault();
thankYouMessage.classList.add('show');
setTimeout(() => form.submit(), 2000);
});
#thank-you-message {
display: none;
}
#thank-you-message.show {
display: block;
}
<p id="thank-you-message">
Thank you for contacting us. We will be in touch with you very soon.
</p>
<form action="forms/subscribe.php" method="post">
<input type="email" name="email" placeholder="Enter your Email">
<input type="submit" value="Subscribe">
</form>

PHP link builder to avoid use of Java Script and hide the old URL

I'm creating a login page that accepts a username and then redirects the user to log in. This is currently done, and works with the following Java Script.
function process()
{
var url="https://example.com/users/profile" + document.getElementById("username").value;
location.href=url;
return false;
}
<p>Enter your username</p>
<form onsubmit="return process();">
<input type="text" name="username" id="username">
I'd prefer to do this without using Java Script to support users that disable it, older browsers and to hide this from the source code of the page. The subdirectories are protected anyway but I just want the added compatibility.
I'm attempting to do this with PHP instead;
<form action="/authenticate.php">
<input type="text" name="username" id="username">
I'm using the same form but have created a page called authenticate.php instead. All that authenticate.php contains is;
<p>Authenticating…</p>
<?php
$username = ["username"];
header("Location: https://example.com/users/profile/$username"); die();
?>
If steve was the input, I'd expect that to then redirect to https://example.com/users/profile/steve but it doesn't. I've set up redirects already to handle errors and the form translates text to lowercase anyway.
I'm just wondering why;
<?php
$username = ["username"];
header("Location: https://example.com/users/profile/$username"); die();
?>
won't work with the addition to the URL but does work without the $username so that's the only error. I also tried $username = $POST_["username"]; but that's not relevant and doesn't seem to work either. The current code takes me to https://example.com/users/profile/Array
If someone could advise on the correct way to do this I'd very much appreciate it.
By default form method is GET but the best practice is to mention it so you've to do:
<form action="/authenticate.php" method="get">
<input type="text" name="username" id="username">
</form>
And authenticate.php you need to get input value:
<p>Authenticating…</p>
<?php
$username = $_GET["username"];
header("Location: https://example.com/users/profile/$username");
die();
?>

Stop refreshing on submit button [duplicate]

This question already has answers here:
JavaScript code to stop form submission
(14 answers)
Closed 4 years ago.
Is there any way to stop refreshing the page on submit button if your if condition goes false and show all the input fields with values entered?
Since you mentioned PHP, then why not use it?
I assume your question has two parts like below.
Part one - you wrote:
show all the input fields with values entered
By above, you mean using $_SESSION to repopulate the fields with the submitted data?
Part two - you wrote:
Is there any way to stop refreshing the page on submit button if your if condition goes false
Note that submit and any on is an event within the client side processing scope. You can use jQuery or JS validations for that.
Here below are two files for your learning test.
The posting php:
<html>
<body>
<form action="action.php" method="POST">
<input type="text" name="feedback" value="" />
<input type="hidden" name="token" value="123456ABCDEF" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
<?
session_start();
$token = '123456ABCDEF';
if(isset($_SESSION)){
if($_SESSION['token'] == $token){
echo "Your feedback:<br />";
foreach($_SESSION as $field=>$value):
echo $field.": ".$value."<br />";
endforeach;
}else{
echo " Bad token! Cross-Site Request Forgery (CSRF)";
}
}else{
echo "Nothing!";
}
The posted to php:
<?php
session_start();
$_SESSION = $_POST;
$_SESSION['message'] = "Thank you for the feedback!";
header('Location: ' . $_SERVER['HTTP_REFERER']);
?>
Hope I got you right and above helps.
First off, this is a duplicate of JavaScript code to stop form submission
Now, when we got that out of the way, here is abrief explanation. You cannot prevent the browser itself from refreshing. But what you can do is prevent the form from being submitted (and in turn causing a refresh). And this is the usual solution when dealing with form validation in JS.
You can check the abode linked answer for more details.
You can use Post / Redirect / Get Pattern. If you have errors redirect to same page with form and show errors. You can't just "stop" the form during POST.
Other way if you don't want "showing" any redirect you can use ajax request. Form wont "blink".
You can also use javascript for checking field onchange event of input elements.

reload form on submit with latest post data

I have a form to post content into a database. The existing database content for the form is posted into the form as the value. enalbeing the form to show the existing database content.
On submit the database is updated and to view the newly updated content in the form the page must be reloaded.
I have produced a reload script in javascript to reload the page on submit. The page reloads but the php content doesn't update. The page still need to be reloaded manually for the new content to show up.
This is the code for my form.
<form method="POST" action="">
<input type="text" name="title" <?php echo "value=\"" .$row['title']."\">"?>
<textarea id="editor" name="content"><?php echo $row['content']; ?></textarea>
<input type="submit" name="save" value="Save" class="submit" onclick="reload();">
</form>
Javascript
function reload(){
document.location.reload(true);
}
I have also tried
window.location = window.location.href;
Both are relaoding the page but the php isn't being refreshed.
you should first update the db with submitted value before selecting the records to display in the form value.
use <?php $_SERVER['PHP_SELF'] ?> in form action.
mysql_query("UPDATE xyz SET title=$_request['title'],... WHERE id = 1") .
2.Then select query mysql_query("SELECT * from xxx where id =1").
These may solve your problem of reloading to get new values.
java script excecute only on the client side. php is Server side. you need to reload the PHP.
<form method="POST" action="<<NAME OF YOUR PHP>>.php">
<input type="text" name="title" <?php echo "value=\"" .$row['title']."\">"?>
<textarea id="editor" name="content"><?php echo $row['content']; ?></textarea>
<input type="submit" name="save" value="Save" class="submit" onclick="reload();">
</form>
Is there a reason it needs to be done with ajax? If you don't need ajax it's better to handle it with php. ajax is more work and doesn't have the same rate of success as submitting a form via php, sometimes weird things happen. You can just do a redirect after saving the form:
header("Location: /routeToYourPage&id=".$ID,TRUE,303);

Using HTML 5 / Javascript template to send contact e-mail form

I recently created a simple site for a friend's business using an HTML 5 template. It contained some cutesy Javascript elements too. The website URL is www.michianamemories.com
One of the elements is a Contact Form at the bottom of the page. It looks like the "Send Message" button is coded to do absolutely nothing. How simple is it to have this form forward the user-entered values (ie: their name, e-mail, and their message) to a dedicated e-mail inbox?
If it's not that simple, what other options are available to make the form functional but also integrated with the site's general theme?
I'm assuming the answer is very simple, but I'm a novice at HTML 5 and am totally clueless about Javascript. Your help is appreciated in advance.
HTML doesn't allow you to submit a form to an email.
You could use mailto but it's not the friendliest piece of functionality. It will open up Outlook and dump the form data into the email content. Has a lot of issues though.
More info on mailto
My recommendation is to use a "form mail script". This is only done on server side though so you'll need to have a web server. You'll need to google and read up on them.
Reference about form submit options
It's not possible in pure Javascript. Sending email requires server-side processing.
There are several websites that will let you generate simple email forms, check out: http://www.google.com/search?hl=en&safe=off&q=email+form+generator&aq=5&aqi=g10&aql=&oq=email+form
In my opinion the best thing you can do is to create a simple Back-End App in PHP.
Create file mail.php in your root directory.
In your HTML form tag you need to add the action attribute with the path to mail.php file and the method attribute, so that the form knows which HTTP Request Method use to send the data <form action="mail.php" method ="post">. This will add the action to trigger for the 'Send Message' button, that you said is not working.
This happens because now the button knows what to do if you click it. It takes all of your data from the form input fields and send them to the mail.php file. This file needs to fetch them and validate them. (You should at least create the validation for the required fields in your form, to check if they're not null. You can make some extra validations in your build-in html attributes or with some help of the JavaScript)
The most important thing now, is to create the Mail function in your mail.php. Here is all the documentation you need to do this: PHP Mail Documentation.
Here is the code (your site is not working so I'm just improvising with the input fields):
HTML:
<form action="mail.php" method="post">
<label for="name-field">Name:</label>
<input id="name-field" name="name" type="text" required>
<label for="surname-field">Surname:</label>
<input id="surname-field" name="surname" type="text" required>
<label for="message-field">Message:</label>
<textarea id="message-field" name="message" required></textarea>
<label for="mail-field">Your e-mail:</label>
<input id="mail-field" name="mail" type="mail" required>
<button type="submit">Send Message</button>
</form>
PHP:
// Validating if everything is filled
if(isset($_POST['name']) && isset($_POST['surname']) && isset($_POST['message']) && isset($_POST['mail'])
{
$to = "example#mysite.com";
$subject = "Automatically generated messege from" . $_POST['name'] . ' ' . $_POST['surname'];
$body = $_POST['message'];
$headers = 'To: ' . $to . "\r\n";
$headers .= 'From: ' . $_POST['mail'];
// Send mail function
if(mail($to, $subject, $body, $headers))
{
echo 'Mail sent successfuly!';
} else {
echo 'Error occurred while sending the message';
}
}
As mentioned in the other answers, you can't use HTML5 to send e-mail. This needs to be done on your server.
One easy and free solution is to use Google Apps Script though. You can publish your Apps Script as a Web App and have a doPost method like this:
function doPost(e){
var email = e.parameter.email;
var subject = 'E-mail from website';
var message = e.parameter.message;
MailApp.sendEmail(emailAddress, subject, message);
return ContentService.createTextOutput('E-mail sent!');
}
And in your HTML, you would have a form like this:
<form action="url to your deployed app script" method="post">
<input type="email" name="email"></input>
<textarea name="message"></textarea>
<input type="submit" value="Submit"></input>
</form>
The URL to put in the action attribute will be shown when you deploy your Apps Script as a Web App:

Categories