Louis
Louis

Reputation: 2618

jQuery ajax post doesn't redirect to php page

I have a contact form on my website with a jQuery ajax call, but I don't see the .php page when I click on the button.

Here's the ajax call:

    var data = {
        name: $("input.userName").val(),
        email: $("input.userEmail").val(),
        tel: $('input.userPhone').val(),
        message: "Projet de "+$("input.userName").val() + ", Tel : " + $('input.userPhone').val(),
            body: body
        };

    $.ajax({
        type: "POST",
        url: "acerola.php",
        data: data,
        success: function(data){
            console.log('ajax sucessfully sent');
        }
    });

With acerola.php:

<html>
<head><title>PHP Mail Sender</title></head>
<body>
<h1>OUIIiiii</h1>
<?php

echo "<h1>Coucou</h1>";

/* All form fields are automatically passed to the PHP script through the array $HTTP_POST_VARS. */
$name = $HTTP_POST_VARS['name'];
$email = $HTTP_POST_VARS['email'];
$tel = $HTTP_POST_VARS['tel'];
$message = $HTTP_POST_VARS['message'];
$body = $HTTP_POST_VARS['body'];

/* PHP form validation: the script checks that the Email field contains a valid email address and the Subject field isn't empty. preg_match performs a regular expression match. It's a very powerful PHP function to validate form fields and other strings - see PHP manual for details. */
if (!preg_match("/\w+([-+.]\w+)*@\w+([-.]\w+)*\.\w+([-.]\w+)*/", $email)) {
  echo "<h4>Invalid email address</h4>";
  echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ($subject == "") {
  echo "<h4>No subject</h4>";
  echo "<a href='javascript:history.back(1);'>Back</a>";
} elseif ( /* Sends the mail and outputs the "Thank you" string if the mail is successfully sent, or the error string otherwise. */
    mail("[email protected]", "Demande de devis web", $message . $body, "From:" . $email)
) {
  echo "<h4>Thank you for sending email</h4>";
  echo "<div>Thank you for sending email</div>";
} else {
  echo "<h4>Can't send email to $email</h4>";
}

?>
</body>
</html>

I would like the user to be redirected to acerola.php. But the user stays on the original page.

Upvotes: 0

Views: 941

Answers (1)

Ian Egner
Ian Egner

Reputation: 41

After the ajax response, fire a redirect with javascript.

$.ajax({
    type: "POST",
    url: "acerola.php",
    data: data,
    success: function(data){
        console.log('ajax sucessfully sent');
        window.location.replace('URL HERE')
    }
});

Upvotes: 2

Related Questions