2015-08-03 2 views
2

У меня есть форма, которую я использую на своей странице для того, чтобы клиент мог отправлять мне некоторые сообщения. Все в порядке и работает. Единственное, чего не хватает, это то, что каждая форма ошибок и результат, например (ошибка электронной почты, имя отсутствует) отображаются на новой странице. Я бы хотел, чтобы на одной странице были уведомления, а также результаты, например «Ваше сообщение отправлено». Я видел, что на некоторых страницах форма ввода может быть высокой на красном, если что-то ошибочно и т. Д. Я читал, что это может быть сделано либо ajax, либо jquery, но, честно говоря, я не настолько знаком с ним. В моем решении я использую bootstrap и php. Можете ли вы помочь мне в этом? Ниже моего текущего кода.Форма проверки и результат на той же странице html

HTML (с использованием начальной загрузки):

<form action="send_form_email.php" method="post" class="form-horizontal"> 
       <div class="form-group"> 
       <label for="first_name" class="col-lg-2 control-label">First name</label> 
       <div class="col-lg-10"> 
       <input type="text" class="form-control" id="first_name" name="first_name" placeholder="Enter you first name"> 
       </div> 
       </div><!-- End form group --> 

       <div class="form-group"> 
       <label for="last_name" class="col-lg-2 control-label">Last name</label> 
       <div class="col-lg-10"> 
        <input type="text" class="form-control" id="last_name" name="last_name" placeholder="Enter you last name"> 
       </div> 
       </div><!-- End form group --> 

       <div class="form-group"> 
       <label for="email" class="col-lg-2 control-label">Email</label> 
       <div class="col-lg-10"> 
        <input type="text" class="form-control" id="email" name="email" placeholder="Enter you Email Address"> 
       </div> 
       </div><!-- End form group --> 

       <div class="form-group"> 
       <label for="telephone" class="col-lg-2 control-label">Telephone</label> 
       <div class="col-lg-10"> 
        <input type="text" class="form-control" id="telephone" name="telephone" placeholder="Enter you phone number"> 
       </div> 
       </div> 

       <div class="form-group"> 
       <label for="comments" class="col-lg-2 control-label">Any Message</label> 
       <div class="col-lg-10"> 
        <textarea name="comments" id="comments" name="comments" class="form-control" 
        cols="20" rows="10" placeholder="Enter your Message"></textarea> 
       </div> 
       </div> 

       <div class="form-group"> 
       <div class="col-lg-10 col-lg-offset-2"> 
        <button type="submit" class="btn btn-primary">Submit</button> 
       </div> 
       </div> 



      </form> 

вот PHP, которые обрабатывают электронную почту для отправки и формы проверки:

<?php 
if(isset($_POST['email'])) 
{ 

    // CHANGE THE TWO LINES BELOW 
    $email_to = "[email protected]"; 

    $email_subject = "Nowy formularz od osoby"; 


    function died($error) { 
     // your error code can go here 
     echo "We are very sorry, but there were error(s) found with the form you submitted. "; 
     echo "These errors appear below.<br /><br />"; 
     echo $error."<br /><br />"; 
     echo "Please go back and fix these errorsbr /><br />"; 
     echo '<input type="button" value="BACK" onclick="history.back();">'; 
     die(); 
    } 

    // validation expected data exists 
    if(!isset($_POST['first_name']) || 
     !isset($_POST['last_name']) || 
     !isset($_POST['email']) || 
     !isset($_POST['telephone']) || 
     !isset($_POST['comments'])) { 
     died('We are sorry, but there appears to be a problem with the form you submitted.');  
    } 

    $first_name = $_POST['first_name']; // required 
    $last_name = $_POST['last_name']; // required 
    $email_from = $_POST['email']; // required 
    $telephone = $_POST['telephone']; // not required 
    $comments = $_POST['comments']; // required 

    $error_message = ""; 
    $email_exp = '/^[A-Za-z0-9._%-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; 
    if(!preg_match($email_exp,$email_from)) { 
    $error_message .= The Email Address you entered does not appear to be valid.<br />'; 
    } 
    $string_exp = "/^[A-Za-z .'-]+$/"; 
    if(!preg_match($string_exp,$first_name)) { 
    $error_message .= 'The First Name you entered does not appear to be valid.<br />'; 
    } 
    if(!preg_match($string_exp,$last_name)) { 
    $error_message .= 'The Last Name you entered does not appear to be valid.<br />'; 
    } 
    if(strlen($comments) < 2) { 
    $error_message .= 'The Comments you entered do not appear to be valid.<br />'; 
    } 
    if(strlen($error_message) > 0) { 
    died($error_message); 
    } 
    $email_message = "Zawartosc wypelnionego formularza\n\n"; 

    function clean_string($string) { 
     $bad = array("content-type","bcc:","to:","cc:","href"); 
     return str_replace($bad,"",$string); 
    } 

    $email_message .= "First Name: ".clean_string($first_name)."\n"; 
    $email_message .= "Last Name: ".clean_string($last_name)."\n"; 
    $email_message .= "Email: ".clean_string($email_from)."\n"; 
    $email_message .= "Telephone: ".clean_string($telephone)."\n"; 
    $email_message .= "Comments: ".clean_string($comments)."\n"; 


// create email headers 
$headers = 'From: '.$email_from."\r\n". 
'Reply-To: '.$email_from."\r\n" . 
'X-Mailer: PHP/' . phpversion(); 
if(mail($email_to, $email_subject, $email_message)) { 
echo "Dziekuje za kontakt postaram sie odezwac jak najszybciej | Thank you for contacting me. I will be in touch with you very soon."; 
echo '<input type="button" value="BACK" onclick="history.back();">'; 
}else{ 

     echo "Nie wyslano z z powodu nieznanego bledu prosze sprobuj ponownie lub zadzwon do mnie bezposrednio | Form was not send due to unknown reason please go back and try again if it would not help please try to rich me directly on my phone.<br/><br/><br/><br/>"; 
     echo '<input type="button" value="BACK" onclick="history.back();">'; 

} 
} 
// die(); 

ответ

1

Изменение От

<form action="send_form_email.php" method="post" class="form-horizontal"> 

Для

<form action="" method="post" class="form-horizontal"> 

Затем сохраните файл HTML в PHP и добавить PHP код в верхней части страницы формы

Обновленный PHP код для пользовательских сообщений об ошибках типа.

<?php 
if(isset($_POST['email'])) 
{ 

    // CHANGE THE TWO LINES BELOW 
    $email_to = "[email protected]"; 

    $email_subject = "Nowy formularz od osoby"; 


    function died($error) 
    { 
     // your error code can go here 
     // Adding bootstrap style class 
     echo '<div class="alert alert-warning" role="alert">'; 
     echo "We are very sorry, but there were error(s) found with the form you submitted. "; 
     echo "These errors appear below.<br /><br />"; 
     echo $error."<br /><br />"; 
     //Not needed any more 
     //echo "Please go back and fix these errorsbr /><br />"; 
     //echo '<input type="button" value="BACK" onclick="history.back();">'; 
     echo '</div>'; 
     die(); 
    } 

    // New function style the error messages 
    function styleErrorMsg($string) 
    { 
     $string = '<div class="alert alert-warning" role="alert">'.$string.'</div>'; 
     return $string; 
    } 

    // validation expected data exists 
    if(!isset($_POST['first_name']) || 
     !isset($_POST['last_name']) || 
     !isset($_POST['email']) || 
     !isset($_POST['telephone']) || 
     !isset($_POST['comments'])) 
    { 
     died('We are sorry, but there appears to be a problem with the form you submitted.');  
    } 

    $first_name = $_POST['first_name']; // required 
    $last_name = $_POST['last_name']; // required 
    $email_from = $_POST['email']; // required 
    $telephone = $_POST['telephone']; // not required 
    $comments = $_POST['comments']; // required 

    $error_message = ""; 

    $email_exp = '/^[A-Za-z0-9._%-][email protected][A-Za-z0-9.-]+\.[A-Za-z]{2,4}$/'; 
    if(!preg_match($email_exp,$email_from)) 
    { 
     $error_message .= styleErrorMsg('The Email Address you entered does not appear to be valid.<br />'); 
    } 

    $string_exp = "/^[A-Za-z .'-]+$/"; 
    if(!preg_match($string_exp,$first_name)) 
    { 
     $error_message .= styleErrorMsg('The First Name you entered does not appear to be valid.<br />'); 
    } 

    if(!preg_match($string_exp,$last_name)) 
    { 
     $error_message .= styleErrorMsg('The Last Name you entered does not appear to be valid.<br />'); 
    } 

    if(strlen($comments) < 2) 
    { 
     $error_message .= styleErrorMsg('The Comments you entered do not appear to be valid.<br />'); 
    } 

    if(strlen($error_message) > 0) 
    { 
     died($error_message); 
    } 
    $email_message = "Zawartosc wypelnionego formularza\n\n"; 

    function clean_string($string) 
    { 
     $bad = array("content-type","bcc:","to:","cc:","href"); 
     return str_replace($bad,"",$string); 
    } 

    $email_message .= "First Name: ".clean_string($first_name)."\n"; 
    $email_message .= "Last Name: ".clean_string($last_name)."\n"; 
    $email_message .= "Email: ".clean_string($email_from)."\n"; 
    $email_message .= "Telephone: ".clean_string($telephone)."\n"; 
    $email_message .= "Comments: ".clean_string($comments)."\n"; 


// create email headers 
$headers = 'From: '.$email_from."\r\n". 
'Reply-To: '.$email_from."\r\n" . 
'X-Mailer: PHP/' . phpversion(); 
    if(mail($email_to, $email_subject, $email_message)) 
    { 
     echo "Dziekuje za kontakt postaram sie odezwac jak najszybciej | Thank you for contacting me. I will be in touch with you very soon."; 
     echo '<input type="button" value="BACK" onclick="history.back();">'; 
    } 
    else 
    { 
     echo "Nie wyslano z z powodu nieznanego bledu prosze sprobuj ponownie lub zadzwon do mnie bezposrednio | Form was not send due to unknown reason please go back and try again if it would not help please try to rich me directly on my phone.<br/><br/><br/><br/>"; 
     echo '<input type="button" value="BACK" onclick="history.back();">'; 
    } 
} 
// die(); 
?> 
Смежные вопросы