2016-10-15 4 views
1

PHP 폼을 작성 중입니다. 이 스크립트는 양식 필드를 순환하며 비어 있는지 여부를 알려줍니다. 양식을 제출하면 index.html에서 contact.php로 리디렉션되고 빈 페이지가 표시됩니다. index.html에 $ errmsg를 폼 위에 표시하고 싶습니다. 내가 도대체 ​​뭘 잘못하고있는 겁니까? 여기에 내가 정보를 당겨있어 어디 : http://www.w3schools.com/php/php_form_required.asp내 HTML 페이지에서이 PHP '필드 필수'메시지를 에코 할 수 있습니까?

PHP :

<?php 
$fields = array('name', 'email', 'telephone'); 
$error = false; 
foreach($fields AS $fieldname) { 
     if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) { 
       $errmsg = 'Please Fill All Fields. '.$fieldname.' is empty!<br />'; 
       $error = true; 
    } 
} 

HTML :

<form class="form-horizontal" role="form" method="post" action="contact.php"> 
    <div class="form-group"> 
      <span class="error">* <?php echo $errmsg;?></span> 

여기에 문제가 더 아래 인 경우 내 전체 contact.php입니다.

<?php 
$fields = array('name', 'email', 'telephone'); 
$error = false; 
foreach($fields AS $fieldname) { 
     if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) { 
       $errmsg = 'Please Fill All Fields. '.$fieldname.' is empty!<br />'; 
       $error = true; 
     } 
} 

if(!$error) { 
     if (isset($_POST["submit"])) { 
       $name = $_POST['name']; 
       $email = $_POST['email']; 
       $telephone = $_POST['telephone']; 
       $message = $_POST['message']; 
       $headers = "From: [email protected]\r\n"; 
       $to = '[email protected]'; 
       $subject = 'New Lead'; 
       $body = "From: $name\n E-Mail: $email\n Phone: $telephone\n Message: $message"; 
     mail('[email protected]', $subject, $body, $headers); 
     header("Location: http://www.example.com/messagesent.html"); 
     die(); 
     } 
} 
?> 

편집 : 전체 HTML 양식. 그것은 당신이 정말로 그것을 할 몇 가지 심각한 농구를 통해 이동하지 않는 한 당신은 HTML 파일에서 PHP 코드를 실행할 수 없습니다 스파게티

<!-- Contact Form --> 
<form class="form-horizontal" role="form" method="post" action="contact.php"> 
     <div class="form-group"> 
       <span class="error">* <?php echo $errmsg;?></span> 
       <label for="name" class="col-sm-2 control-label">Name</label> 
       <div class="col-sm-10"> 
         <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name"> 
       </div> 
     </div> 
     <div class="form-group"> 
       <label for="email" class="col-sm-2 control-label">Email</label> 
       <div class="col-sm-10"> 
         <input type="email" class="form-control" id="email" name="email" placeholder="[email protected]"> 
       </div> 
     </div> 
       <div class="form-group"> 
       <label for="telephone" class="col-sm-2 control-label">Phone</label> 
       <div class="col-sm-10"> 
         <input type="text" class="form-control" id="telephone" name="telephone" placeholder="250-555-555"> 
     </div> 
     </div> 
     <div class="form-group"> 
      <label for="message" class="col-sm-2 control-label">Message</label> 
      <div class="col-sm-10"> 
        <textarea class="form-control" rows="4" name="message"></textarea> 
      </div> 
    </div> 
    <div class="form-group"> 
      <div class="col-sm-10 col-sm-offset-2"> 
        <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary"> 
      </div> 
     </div> 
     </div> 
</form> 
<!-- End Contact Form --> 
+0

이 양식의 전체 HTML을 제공 할 수 있습니까? – Reisclef

답변

0
**Use Ajax Method**  

**index.html** 

    <!DOCTYPE html> 
    <html lang="en"> 
    <head> 
    <meta charset="utf-8"> 
    <title>using Ajax in jQuery</title> 
    <style type="text/css"> 
     label{ 
      display: block; 
      margin-bottom: 10px; 
     } 
    </style> 
    <script src="https://code.jquery.com/jquery-1.11.3.min.js"></script> 
    <script type="text/javascript"> 
    $(document).ready(function(){ 
     $("form").submit(function(event){ 
      // Stop form from submitting normally 
      event.preventDefault(); 

      /* Serialize the submitted form control values to be sent to the web server with the request */ 
      var formValues = $(this).serialize(); 

      // Send the form data using post 
      $.post("contact.php", formValues, function(data){ 
       // Display the returned data in browser 
       $("#result").html(data); 
      }); 
     }); 
    }); 
    </script> 
    </head> 
    <body> 
     <form> 
      <label>Name: <input type="text" name="name"></label> 
      <input type="submit" value="Send"> 
     </form> 
     <div id="result"></div> 
    </body> 
    </html>    



contact.php 


<?php 
$fields = array('name'); 
$error = false; 
foreach($fields AS $fieldname) { 
     if(!isset($_POST['name']) || empty($_POST['name'])) { 
       $errmsg = 'Please Fill All Fields. '.$fieldname.' is empty!<br />'; 
       $error = true; 
     } 
} 

if($error==true){ 
    echo $errmsg; 
    die(); 
} 
else{ 
     if (isset($_POST["submit"])) { 
       $name = $_POST['name']; 
       $headers = "From: [email protected]\r\n"; 
       $to = '[email protected]'; 
       $subject = 'New Lead'; 
       $body = "From: $name\n E-Mail: $email\n Phone: $telephone\n Message: $message"; 
     mail('[email protected]', $subject, $body, $headers); 
     header("Location: http://www.example.com/messagesent.html"); 
     die(); 
     } 
} 
?> 
0

죄송 부트 스트랩에 중첩입니다. 대신 index.html의 이름을 index.php로 변경하십시오.

+0

방금 ​​시도했지만 여전히 빈 contact.php로 리디렉션됩니다. –

+0

페이지에서 PHP를 실행하지 않고 HTML 페이지에 메시지를 표시하는 방법이 있습니까? –

+0

위대한 단계 1입니다. 나는 왜 이것이 일어나고 있는지에 관해서는 더 이상 다른 대답을 쓰고있다. 인내심을 가지고) – kajes

0
 <?php 
      $fields = array('name', 'email', 'telephone'); 
      $error = false; 
      foreach($fields AS $fieldname) { 
        if(!isset($_POST['fieldname']) || empty($_POST['fieldname'])) { 
          $errmsg = 'Please Fill All Fields. '.$fieldname.' is empty!<br />'; 
          $error = true; 
        } 
      } 

      if(!$error) { 
        if (isset($_POST["submit"])) { 
          $name = $_POST['name']; 
          $email = $_POST['email']; 
          $telephone = $_POST['telephone']; 
          $message = $_POST['message']; 
          $headers = "From: [email protected]\r\n"; 
          $to = '[email protected]'; 
          $subject = 'New Lead'; 
          $body = "From: $name\n E-Mail: $email\n Phone: $telephone\n Message: $message"; 
        mail('[email protected]', $subject, $body, $headers); 
        header("Location: http://www.example.com/messagesent.html"); 
        die(); 
        } 
      } 
      ?> 

    **Main Error:** 

    if(!isset($_POST[$fieldname]) || empty($_POST[$fieldname])) { 
      // your code 
} 
        above line should be 

    if(!isset($_POST['fieldname']) || empty($_POST['fieldname'])) { 
} 
+0

나는 원래 contact.php에 오류 메시지를 출력하는 코드 조각을 가지고 있었고 잘 동작했다. 단지 contact.php 대신에 html 파일에 echo 할 필요가있다. –

0
좋아

, 그래서 여기에 문제는 실제로 HTML 코드 (따라서 빈 페이지) 출력되지 않는 액션 - 속성, 당신은 contact.php을 보내는 것입니다. contact.php 파일은 실제로 양식의 기능을 수행하는 도우미 파일이므로 사용자를 그 파일로 보내는 것은 무의미합니다. 그들은 물론 index.php 파일에 있어야합니다.

먼저 폼 태그의 "action"속성을 contact.php 대신 index.php를 가리 키도록 변경하십시오.

두 번째로, php-function이 index.php 파일에 실제로 액세스 할 수 있도록 contact.php 파일을 요구해야합니다.

세 번째로 제출을 동일한 페이지로 안내하기 때문에 양식을로드하기 전에 양식 제출 여부를 확인해야합니다.

그래서있는 거 코드는 다음과 같은 종류의보고해야합니다

<?php 

require 'contact.php'; // Path to your contact.php script 

?> 

<!DOCTYPE html> 
<html> 
    <head> 
     <meta charset="utf-8"> 
     <title>Contact form</title> 
    </head> 
    <body> 
     <!-- Contact Form --> 
     <form class="form-horizontal" role="form" method="post" action="index.php"> 
       <?php if ($_SERVER['REQUEST_METHOD'] === 'POST') { // I'm putting my if statement to check if form is submitted here, but you could put it anywhere you like as long as it's wrapping the error message in some way.?> 
        <div class="form-group"> 
         <span class="error">* <?php echo $errmsg;?></span> 
         <label for="name" class="col-sm-2 control-label">Name</label> 
         <div class="col-sm-10"> 
          <input type="text" class="form-control" id="name" name="name" placeholder="First & Last Name"> 
         </div> 
        </div> 
       <?php } ?> 
       <div class="form-group"> 
         <label for="email" class="col-sm-2 control-label">Email</label> 
         <div class="col-sm-10"> 
           <input type="email" class="form-control" id="email" name="email" placeholder="[email protected]"> 
         </div> 
       </div> 
         <div class="form-group"> 
         <label for="telephone" class="col-sm-2 control-label">Phone</label> 
         <div class="col-sm-10"> 
           <input type="text" class="form-control" id="telephone" name="telephone" placeholder="250-555-555"> 
       </div> 
       </div> 
       <div class="form-group"> 
        <label for="message" class="col-sm-2 control-label">Message</label> 
        <div class="col-sm-10"> 
          <textarea class="form-control" rows="4" name="message"></textarea> 
        </div> 
      </div> 
      <div class="form-group"> 
        <div class="col-sm-10 col-sm-offset-2"> 
          <input id="submit" name="submit" type="submit" value="Send" class="btn btn-primary"> 
        </div> 
       </div> 
       </div> 
     </form> 
     <!-- End Contact Form --> 
    </body> 
</html> 
+0

이것은 단지 빨리 코딩되었으므로 무슨 일이 일어나는지 이해한다. 그리고 왜. 필요에 따라 코드를 조정해야합니다. 희망이 도움이됩니다. – kajes

+0

내 모든 인터넷 검색 기능에서 나는 결코 요구 기능을 발견하지 못했습니다. PHP를 사용한 두 번째 날입니다. 정말 고맙습니다! –

+0

도움이 된 것을 기쁘게 생각합니다. 이와 같은 형식을 취하는 것은 다소 어색하다. 더 나은 유용성을 위해 자바 스크립트 솔루션을 사용해야 할 수도 있지만, PHP를 배우면 좋은 교훈이다. – kajes