Waseem Barcha Waseem Barcha - 4 months ago 34
Javascript Question

How to redirect on button click using php

I am using a button on my form. I am trying to redirect to another page on button click after successful submission of user info. Every thing works properly except redirection. Here is the code I tried.

Html code:



<form role="form" id="contact-form" method="get">
<div class="form-group row">
<input type="email" id="email" name="email" placeholder="Enter your email" required="required" class="form-control input-lg" />
<input type="text" id="address" name="address" placeholder="Enter your address" required="required" class="form-control input-lg" />
<button type="submit" class="btn btn-t-primary">Show Me Now!</button>
</div>
</form>





Javascript code:



function contact() {
$("#contact-us-form").submit(function (e) {
e.preventDefault();
e.stopImmediatePropagation();
form = $(this);
data = $(this).serialize();
$.post("contact.php", data, function(response){
form.trigger('reset');
});
}





Php code:

<?php
ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");
if (isset($_POST['email'])) {
$email = $_POST['email'];
$address= $_POST['address'];
$subject = "Message from: ".$email;
$content = "Email: " . $email."\n"
. "Address: " . $address;
$headers ='Reply-To: ' . $email . "\r\n";
mail('example@gmail.com', $subject ,$content, $headers );
header("Location:https://www.example.com");
echo 1;
}else {
echo 0;
}


?>

Answer

You can't redirect an ajax request from PHP, instead use this:

$(function() {

    $("#contact-form").submit(function(e) {
        e.preventDefault();
        e.stopImmediatePropagation();
        form = $(this);
        data = $(this).serialize();
        $.post("contact.php", data, function(response) {
            form.trigger('reset');
            //Redirection
            window.location.href = "https://www.google.com";
        });
    });

});

Just remove this header("Location:https://www.example.com"); from your PHP.

I hope this will help you.

Comments