JavaScript Ajax – Page Redirect with Successful Ajax Request

ajaxhttp-redirectjavascriptjquery

I have a form that uses Ajax for client-side verification. The end of the form is the following:

$.ajax({
        url: 'mail3.php',
        type: 'POST',
        data: 'contactName=' + name + '&contactEmail=' + email + '&spam=' + spam,

        success: function(result) {
            //console.log(result);
            $('#results,#errors').remove();
            $('#contactWrapper').append('<p id="results">' + result + '</p>');
            $('#loading').fadeOut(500, function() {
                $(this).remove();

            });

        }
    });

EDIT: this is my mail3.php file dealing with errors:

$errors=null; 

if ( ($name == "Name") ) {
    $errors = $nameError; // no name entered
}
if ( ($email == "E-mail address") ) {
    $errors .= $emailError; // no email address entered
}
if ( !(preg_match($match,$email)) ) {
    $errors .= $invalidEmailError; // checks validity of email
}
if ( $spam != "10" ) {
    $errors .= $spamError; // spam error
}

if ( !($errors) ) {
    mail ($to, $subject, $message, $headers);
    //header ("Location: thankyou.html");
    echo "Your message was successfully sent!";
    //instead of echoing this message, I want a page redirect to thankyou.html

} else {
    echo "<p id='errors'>";
    echo $errors;
    echo "</p>";
}

I was wondering if it's possible to redirect the user to a Thank You page if the ajax request is successful and no errors are present. Is this possible?

Thanks!
Amit

Best Answer

Sure. Just put something at the the end of your success function like:

if(result === "no_errors") location.href = "http://www.example.com/ThankYou.html"

where your server returns the response no_errors when there are no errors present.

Related Question