Form Message Alert
I have the following form:
Solution 1:
HTML Code --
<p style="display:none">Mail Send Successfully </p>
<form method="post" action="contactus.php" name="myForm" autocomplete="off">
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name" maxlength="60" required/>
<label for="email">Email:</label>
<input type="text" name="email" id="email" maxlength="120" required/>
<label for="message">Message:</label><br />
<textarea name="message" rows="20" cols="20" id="message" required></textarea>
<input id="submit-btn" type="submit" name="submit" value="Submit" class="submit-button" />
</form>
AJAX Code --
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('#submit-btn').click(function(){
var name = $('#name').val();
var email = $('#email').val();
var message = $('#message').val();
$.ajax({
type: "POST",
url: "form-submit.php", // in this file we will put the code of send email and also we will return a response
data:"name="+name+"&email="+email+"&message="+message,
success: function(response) // we will get response
{
$('p').show(); // here message will show after send email
}
});
});
});
</script>
Solution 2:
If the PHP that sends mail is on the same page, I'm assuming a structure like this:
<?php
if (isset($_POST['email']) && strlen($_POST['email') {
mail("name@example.com", "subject", "text");
}
?>
I recommend you add a variable there, like this:
<?php
if (isset($_POST['email']) && strlen($_POST['email') {
mail("name@example.com", "subject", "text");
$sent_mail = true; // so we know later
}
?>
Then somewhere in the page, do this:
<?php
if (isset($sent_mail)) {
echo 'Success!';
}
?>
No javascript needed :)
Solution 3:
<form method="post" action="contactus.php?message=ok" name="myForm" autocomplete="off">
<label for="Name">Name:</label>
<input type="text" name="Name" id="Name" maxlength="60" required/>
<label for="email">Email:</label>
<input type="text" name="email" id="email" maxlength="120" required/>
<label for="message">Message:</label><br />
<textarea name="message" rows="20" cols="20" id="message" required</textarea>
<input type="submit" name="submit" value="Submit" class="submit-button" />
</form>
<div id="displayMessage"></div>*****************new div to display message put wherever you want******************
Javascript:
<script>
function getParameterByName(name) {
name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"),
results = regex.exec(location.search);
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " "));
}
if(getParameterByName("message") == "ok")
{
document.getElementById("displayMessage").innerHTML = "Message Sent.";
window.alert("Message Sent.");//If you want an alert box
}
<script>
Just put the <script></script>
at the end of your body...
Post a Comment for "Form Message Alert"