Chris Volden Chris Volden - 1 year ago 57
PHP Question

How can I prevent a form submission from taking me to a different page

I've programmed a contact form that sends out an email with the details of the inputs.

On submission,(action="send_form_email.php") it takes me to the actual PHP file page. Is there any way to prevent this? I currently use this code below to bring me back to the page where the form is, but this prevents the other script from running that lets the person know that the form was submitted successfully.


Below is the code that will not echo out:

echo "<script type='text/javascript'>alert('thanks');</script>";

This form repeats on several pages on the website. In the end, I want the customer to remain on the current page and for them to be notified that everything was sent correctly.

THanks for help!

Answer Source

You cant. Default functionality for forms will redirect to whatever the action attribute holds. In order to do what you need, you need to use AJAX

easy example with Jquery:

    var postdata = $(this).serialize();
    var url = $(this).attr("action"); //something.php;
    $.post(url, postdata, function(res){
        console.log(res); //your PHP results
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download