1

I have a shortcode to display a form. When the user tries to click on the button to redirect to another page, I get headers already sent error. If I use javascript redirection, the redirection works.

But I would like to know what is wrong with the code that it is throwing this error:

Shortcode code:

/**
     * Processes shortcode 
     *
     *
     *
     * @return  mixed   $output     Output of the buffer
     */
    public function plugin_calc() {
        ob_start();

        include 'templates/get-form-calculator.php';
        $output = ob_get_contents();
        ob_end_clean();
        return $output;

    }

get-form-calculator.php:

$nameErr = $emailErr = "";

if ($_SERVER["REQUEST_METHOD"] == "POST") {
 $valid = true;
 if (empty($_POST["cf-name"])) {
     $nameErr = "This field is required";
     $valid = false;
 } else {
     $name = strip_tags($_POST["cf-name"]);
     // check if name only contains letters and whitespace
     if (!preg_match("/^[a-zA-Z ]*$/",$name)) {
         $nameErr = "Only letters and white space allowed";
         $valid = false;
     }
 }

 if (empty($_POST["cf-email"])) {
     $emailErr = "This field is required";
     $valid = false;
 } else {
     $email = strip_tags($_POST["cf-email"]);
     // check if e-mail address is well-formed
     if (!filter_var($email, FILTER_VALIDATE_EMAIL)) {
         $emailErr = "Invalid email format";
         $valid = false;
     }
 }

 if ($valid) {
    if (isset($_POST['cf-request-quote'])){
         $cf_name = $name;
         $cf_email = $email;
         $url = home_url( '/rquote/?cfn=' . urlencode($cf_name) . '&cfe='. urlencode($cf_email));
         //wp_safe_redirect( $url );  //This doesn't work
         echo '<script> window.location = "'.$url.'"; </script>'; //This works
         exit();
     }
 }

}

?>

//HTML Form Code here

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Browse other questions tagged or ask your own question.