Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Call php in HTML form on action but don't redirect

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?

like image 626
StanLe Avatar asked Dec 12 '22 10:12

StanLe


2 Answers

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()
        });
    });
});
like image 65
Michael J. Anderson Avatar answered Jan 04 '23 12:01

Michael J. Anderson


<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>
like image 39
sudhakar Avatar answered Jan 04 '23 12:01

sudhakar