I have an HTML form as follows:
<form id="ContactForm" name="ContactForm" method="post" action="emailinfo.php">
and then a submit button that calls verify()
:
<a href="#" class="button1" onClick="verify()">Send</a>
verify
is defined as such:
function verify() {
if(document.getElementById("name").value=="" || document.getElementById("email").value=="") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
document.getElementById('ContactForm').submit();
}
}
Currently, when I click the submit button, the browser redirects to emailinfo.php
, which is just a blank white screen because that php
file just sends off an email and does nothing else. How can I run that php
file without redirecting to it?
What you want to do is use AJAX to send a request to the emailinfo.php file when the button is clicked. Making the form action blank will cause the form to post to the same page you're on.
If you're using jQuery, it's pretty easy to submit the form via ajax:
$(document).ready( function() {
$('.button1').click(function(){
var f = $('#ContactForm');
$.ajax({
type: "POST",
url: "emailinfo.php",
data: f.serialize()
});
});
});
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3/jquery.min.js"></script>
<script>
function verify() {
if(document.getElementById("name").value=="" || document.getElementById("email").value=="") {
alert("Please enter a name and an email.");
} else {
alert("Looks good, sending email");
//document.getElementById('ContactForm').submit();
var name=$('#name').val();
var email=$('#email').val();
var formData = "name="+name+"&email="+email;
$.ajax({
url : "emailinfo.php",
type: "POST",
data : formData,
success: function(data, textStatus, jqXHR)
{
//data - response from server
alert(data);
},
});
}
}
</script>
<form id="ContactForm" name="ContactForm" method="post" action="">
<input type="text" name="name" id="name"/>
<input type="text" name="email" id="email"/>
<a href="#" class="button1" onClick="verify()">Send</a>
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With