0

I am using the following php code along with ajax. Everything works fine, but instead of only prompting with an ajax confirmation message that the message has gone through, i would like a url redirection. Any help would be greatly appreciated.

<?php   
// Check if sent
try {
    $sendmailResult = mail($recipient, $subject, $email_content, $headers);
    if( $sendmailResult === TRUE ) {
            returnAndExitAjaxResponse(

            constructAjaxResponseArray(
            TRUE
            )

        );


    } else {
        returnAndExitAjaxResponse(
            constructAjaxResponseArray(
                FALSE,
                'ERROR_AT_PHPMAIL',
                array('error_information'=> error_get_last() )
            )
        );
    }
} catch (Exception $_e) {
    returnAndExitAjaxResponse(
        constructAjaxResponseArray(
            TRUE,
            'ERROR_AT_PHPMAIL',
            array('error_message'=> $_e->getMessage())
        )
    );
}

/*
    Construct ajax response array
    Input: Result (bool), Message (optional), Data to be sent back in array
*/
function constructAjaxResponseArray ($_response, $_message = '', $_json = null) {
    $_responseArray = array();
    $_response = ( $_response === TRUE ) ? TRUE : FALSE;
    $_responseArray['response'] = $_response;
    if(isset($_message)) $_responseArray['message'] = $_message;
    if(isset($_json)) $_responseArray['json'] = $_json;
    return $_responseArray;
}
/*
    Returns in the Gframe ajax format.
    Input: data array processed by constructAjaxResponseArray ()
    Outputs as a html stream then exits.
*/
function returnAndExitAjaxResponse ($_ajaxResponse) {
    if(!$_ajaxResponse){
        $_ajaxResponse = array('response'=>false,'message'=>'Unknown error occurred.');
    }
     header("Content-Type: application/json; charset=utf-8");
    echo json_encode($_ajaxResponse);
    die();
}
?>

1 Answers1

0

Since it is ajax, I don't think you can redirect it directly from the backend call.

The best solution that I can think for this (of course there maybe other solutions that I am unaware but just giving you my insights) is return the url that you want to redirect to in the AJAX response and then use document.location.href for redirection from javascript when your AJAX call is successfull.

Hope this helps.

Kishen Nagaraju
  • 2,062
  • 9
  • 17