2016-11-01 3 views
0

Я только что сделал свою контактную форму для работы, вроде. Он имеет несколько вопросов:Контактный формуляр (Bootstrap, html & php)

  • Когда форма отправлена, она пинает тебя на странице, направляет вас на пустую страницу с сообщением: «Спасибо и т.д.». Мне бы хотелось остаться на странице и просто получить всплывающее окно с сообщением о успехе или просто оставить его на странице. Либо хорошо :)

  • Сообщение об ошибке не отображается, оно просто помещает вас на пустую страницу.

  • Ошибки, такие как «пожалуйста, заполните действующий e-mail», не отображаются. Возможно, потому, что я удалил ярлыки, но я хотел бы показать это сообщение в поле, а не под ним.
  • Это переопределение моего CSS! Но это случается иногда на моем компьютере, когда я вижу строки в других случаях, я вижу коробки. Так что проблема может быть где-то в другом месте. Однако с «рабочей формой» он меняет мой последний ящик.

This is what I meant with changing CSS on my boxes

PHP код:

<?php 

if (isset($_POST["submit"])) { 
    $name = $_POST['name']; 
    $subject = $_POST['subject']; 
    $phone = $_POST['phone']; 
    $email = $_POST['email']; 
    $message = $_POST['message']; 
    $from = 'Demo Contact Form'; 
    $to = '[email protected]'; 
    $subject = 'Message from Contact Demo'; 

    $body = "From: $name\n Subject: $subject\n Number: $phone\n E-Mail: $email\n Message:\n $message"; 

    //Check if name has been entered 
    if(!$_POST['name']) { 
     $errName = 'Vul alsjeblieft je naam in'; 
    } 

    //Check if subject has been entered 
    if(!$_POST['subject']) { 
     $errName = 'Vul alsjeblieft een onderwerp in'; 
    } 

    //Check if number has been entered 
    if(!$_POST['phone']) { 
     $errName = 'Vul alsjeblieft je nummer in'; 
    } 

    //Check if e-mail is entered and valid 
    if(!$_POST['email'] || !filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) { 
     $errEmail = 'Vul alsjeblieft je e-mailadres in'; 
    } 

    //Check if message has been entered 
    if(!$_POST['email']) { 
     $errMessage = 'Laat alsjeblieft een bericht achter'; 
    } 

    // If no errors, send email 
    if (!$errName && !$errSubject && !$errPhone && !$errEmail && !$errMessage) { 
     if (mail ($to, $subject, $body, $from)) { 
      echo $result='<div class="alert alert-success">Thank You! I will be in touch</div>'; 
     } 
     else { 
      $result='<div class="alert alert-danger">Sorry there was an error sending your message. Please try again later</div>'; 
     } 
    } 
} 

?> 

HTML:

<form class="form-horizontal" role="form" method="post" action="partials/contactform.php"> 

    <div class="form-group offset-top-45"> 
     <textarea rows="11" cols="100" class="form-control" id="message" name="message" placeholder="Laat hier je bericht voor ons achter:"></textarea><?php echo htmlspecialchars($_POST['message']);?></textarea> 
     <span class="help-block" style="display: none;">Laat alsjeblieft een bericht achter</span> 
     <?php echo "<p class='text-danger'>$errMessage</p>";?> 
    </div> 
</div>      

<div class="col-md-6"> 
    <div class="row offset-top-10"> 
     <div class="pull-right"> 
      <img height="60" width="100" src="/images/stamp.png" alt="stamp"> 
     </div> 
    </div> 

    <div class="row offset-top-10" style="padding-right:20px; padding-left:10px"> 
     <form role="form" id="feedbackForm"> 

      <div class="form-group">  
       <input type="text" class="form-control" id="name" name="name" placeholder="Hoe heet je?" value="<?php echo htmlspecialchars($_POST['name']); ?>"> 
       <span class="help-block" style="display: none;">Vul alsjeblieft je naam in</span> 
       <?php echo "<p class='text-danger'>$errName</p>";?> 
      </div> 

      <div class="form-group"> 
       <input type="text" class="form-control" id="subject" name="subject" placeholder="Wat is het onderwerp?" value="<?php echo htmlspecialchars($_POST['subject']); ?>"> 
       <span class="help-block" style="display: none;">Vul alsjeblieft een onderwerpin</span> 
       <?php echo "<p class='text-danger'>$errSubject</p>";?> 
      </div> 

      <div class="form-group"> 
       <input type="text" class="form-control" id="phone" name="phone" placeholder="Op welk nummer kunnen wij jou bereiken?" value="<?php echo htmlspecialchars($_POST['phone']); ?>"> 
       <span class="help-block" style="display: none;">Vul alsjeblieft je nummer in</span> 
       <?php echo "<p class='text-danger'>$errPhone</p>";?> 
      </div> 

      <div class="form-group"> 
       <input type="email" class="form-control" id="email" name="email" placeholder="Wat is je e-mailadres?"> 
       <span class="help-block" style="display: none;">Vul alsjeblieft je e-mail in</span> 
       <?php echo "<p class='text-danger'>$errEmail</p>";?> 
      </div> 

      <div class="form-group"> 
       <div class="col-md-12 text-right"> 
        <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary btn-s"> 

        <div class="form-group"> 
         <div class="col-sm-10 col-sm-offset-2"> 
          <?php echo $result; ?> 
         </div> 
        </div> 
       </div> 
      </div> 

     </form>  

Помощь очень ценится!

+0

отправить форму на текущей странице добавить

"> –

+0

Thnk you! Должен ли я добавить это где-то сверху, прежде чем «if (isset ...»? HTML довольно новый, PHP еще не имеет для меня смысла. – Denise

+0

нет на теге формы ' «заменить action =» partials/contactform.php с кодом tht –

ответ

0

Полный скрипт, он должен работать без каких-либо проблем

<?php 


$result = ""; 

$errors = ""; //use to count errors 


//Error message variables 
$errName = ""; 
$errSubject = ""; 
$errEmail = ""; 
$errMessage = ""; 


//message variables 
$name = ""; 
$subject = ""; 
$phone = ""; 
$email = ""; 
$message = ""; 
$to  = "[email protected]"; 


if (isset($_POST['submit'])) { 


     //check if name has been entered 

     if (empty($_POST['name'])) { 

       $errName = "Vul alsjeblieft je naam in"; 
       $errors++; 
     } else { 

       $name = UserInput($_POST['name']); 
     } 

     ////Check if subject has been entered 
     if (empty($_POST['subject'])) { 


       $errSubject = "Vul alsjeblieft een onderwerp in"; 
       $errors++; 
     } else { 

       $Subject = UserInput($_POST['subject']); 
     } 

     //check if email entered 
     if (empty($_POST['email'])) { 

       $errEmail = "Laat alsjeblieft een bericht achter"; 
       $errors++; 

     } else { 

       $email = UserInput($_POST['email']); 


       // check if email is valid 

       if (!preg_match("/([\w\-]+\@[\w\-]+\.[\w\-]+)/", $email)) { 

         $errEmail = "Vul alsjeblieft je e-mailadres in"; 
         $errors++; 
       } 
     } 

     if (empty($_POST['phone'])) { 

       $errPhone = "Vul alsjeblieft je nummer in"; 
       $errors++; 
     } else { 

       $phone = UserInput($_POST['phone']); 

       // check if email is numbers 

       if (!is_numeric($phone)) { 

         $errPhone = "enter numbers only"; 
         $errors++; 
       } 
     } 

     //check message 

     if (empty($_POST['message'])) { 


       $errMessage = "Laat alsjeblieft een bericht achter"; 
     } else { 

       $message = UserInput($_POST['message']); 
     } 

     if ($errors > 0) { 
       // we have errors do not send email 

       $result = "<div class=\"alert alert-danger\">Sorry there was an error sending your message. Please fix " . $errors . " errors on the form </div>"; 


     } else { 
       //no errors set email headers and send email 


       // Always set content-type when sending HTML email 
       $headers = "MIME-Version: 1.0" . "\r\n"; 
       $headers .= "Content-type:text/html;charset=UTF-8" . "\r\n"; 
       // More headers 
       $headers .= 'From: <' . $email . '>' . "\r\n"; 


       $body = "<p> New email from $name"; 
       $body .= "<p> Phone : $phone</p>"; 
       $body .= "<p> Email : $email<p>"; 
       $body .= "<p>Message : $message</p>"; 


       if (mail($email, $subject, $msg, $header)) { 

         $result = "<div class=\"alert alert-success\">Thank You! I will be in touch</div>"; 
         $_POST = array(); //clear the form aftter sendig 

       } else { 

         $result = "<div class=\"alert alert-danger\">Sorry there was an error sending your message. Please try again later</div>"; 
       } 




     } 


} 



//sanitise use input 
function UserInput($data) 
{ 

     $data = trim($data); 
     $data = stripslashes($data); 
     $data = htmlspecialchars($data); 
     return $data; 
} 


?> 

<form class="form-horizontal" role="form" method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>"> 
    <div class="form-group"> 
     <div class="col-md-12 text-right"> 
     <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary btn-s"> 
     <div class="form-group"> 
      <div class="col-sm-10 col-sm-offset-2"> 
       <?php echo $result; ?> 
      </div> 
     </div> 
     </div> 
    </div> 
    <div class="form-group offset-top-45"> 
     <textarea rows="11" cols="100" class="form-control" id="message" name="message" placeholder="Laat hier je bericht voor ons achter:"></textarea><?php if(!empty($_POST['message'])){echo $_POST['message'];}?></textarea> 
     <?php echo "<p class=\"text-danger\">".$errMessage."</p>";?> 
    </div> 
    </div>      
    <div class="col-md-6"> 
    <div class="row offset-top-10"> 
     <div class="pull-right"> 
     <img height="60" width="100" src="/images/stamp.png" alt="stamp"> 
     </div> 
    </div> 
    <div class="row offset-top-10" style="padding-right:20px; padding-left:10px"> 
<form role="form" id="feedbackForm"> 
    <div class="form-group">  
     <input type="text" class="form-control" id="name" name="name" placeholder="Hoe heet je?" <?php if(!empty($_POST['name'])){echo "value=\"".$_POST['name']."\"";}?>> 
     <?php echo "<p class=\"text-danger\">".$errName."</p>";?> 
    </div> 
    <div class="form-group"> 
     <input type="text" class="form-control" id="subject" name="subject" placeholder="Wat is het onderwerp?" <?php if(!empty($_POST['Subject'])){echo "value=\"".$_POST['Subject']."\"";}?>> 
     <?php echo "<p class=\"text-danger\">".$errSubject."</p>";?> 
    </div> 
    <div class="form-group"> 
     <input type="text" class="form-control" id="phone" name="phone" placeholder="Op welk nummer kunnen wij jou bereiken?" <?php if(!empty($_POST['phone'])){echo "value=\"".$_POST['phone']."\"";}?>> 
     <?php echo "<p class=\"text-danger\">".$errPhone."</p>";?> 
    </div> 
    <div class="form-group"> 
     <input type="email" class="form-control" id="email" name="email" placeholder="Wat is je e-mailadres?"> 
     <?php echo "<p class='text-danger'>$errEmail</p>";?> 
    </div> 
</form> 

Позвольте мне знать, если у вас есть какие-либо вопросы или нужна любая помощь.

+0

Уважаемый Масивуй , большое спасибо за усилия ответить мне! HTML скремблирует макет, но я проверю, могу ли я исправить это позже :) Для PHP, спасибо! Уборка после этого супер, спасибо! ErrMessages постоянно отображаются над полями, подобно тому, как это делается в HTML. Я посмотрю, смогу ли это изменить тоже :) Спасибо, что прошли через все эти неприятности! – Denise

+0

вам нужно соответствующим образом начертить свою страницу, ошибки будут отображаться только тогда, когда поля не будут установлены –

Смежные вопросы