2017-01-20 1 views
-3

필자는 항상 많은 다른 코드가 필요하다고 생각하여 메일 발송 양식에 문제가 있습니다. 여기 "이름이 너무 짧거나 비어 있습니다!"

는 스크립트 종료 후

HTM 코드 PHP는 HTML 코드로 시작하는 메일 퍼즐 :

<div class="col-2 animation_fade_in_block"> 
<div class="form-style" id="contact_form_2"> 
<div id="contact_body"> 
<label> 
<input type="text" name="name" id="name" required class="input-field" placeholder="Name *" /> 
</label> 
<label> 
<input type="email" name="email" required class="input-field" placeholder="E-mail *" /> </label> 
<label> 
<input type="text" name="phone" maxlength="19" required placeholder="Phone *" class="tel-number-field long" /> </label> 
<label for="field5"> 
<textarea name="message" id="message" class="textarea-field" required placeholder="Message *"></textarea> 
</label> 
<label> 
<input type="submit" id="submit_btn_2" class="btn" value="Send message " /> </label> 
</div> 
<div id="contact_results"></div> 
</div> 
</div> 

SCRIPT

$("#submit_btn_2").click(function() { 

    var proceed = true; 
    //simple validation at client's end 
    //loop through each field and we simply change border color to red for invalid fields  
    $("#contact_form_2 input[required=true], #contact_form_2 textarea[required=true]").each(function() { 
     $(this).css('border-color', ''); 
     if (!$.trim($(this).val())) { //if this field is empty 
      $(this).css('border-color', 'red'); //change border color to red 
      proceed = false; //set do not proceed flag 
     } 
     //check invalid email 
     var email_reg = /^([\w-\.][email protected]([\w-]+\.)+[\w-]{2,4})?$/; 
     if ($(this).attr("type") == "email" && !email_reg.test($.trim($(this).val()))) { 
      $(this).css('border-color', 'red'); //change border color to red 
      proceed = false; //set do not proceed flag    
     } 
    }); 

    if (proceed) //everything looks good! proceed... 
    { 
     //get input field values data to be sent to server 
     post_data = { 
      'user_name': $('input[name=name]').val(), 
      'user_email': $('input[name=email]').val(), 

      'phone_number': $('input[name=phone]').val(), 
      'subject': $('select[name=subject]').val(), 
      'msg': $('textarea[name=message]').val() 
     }; 

     //Ajax post data to server 
     $.post('../php/contact.php', post_data, function(response) { 
      if (response.type == 'error') { //load json data from server and output message  
       output = '<div class="error">' + response.text + '</div>'; 
      } else { 
       output = '<div class="success">' + response.text + '</div>'; 
       //reset values in all input fields 
       $("#contact_form_2 input[required=true], #contact_form_2 textarea[required=true]").val(''); 
       $("#contact_form_2 #contact_body").fadeOut("fast"); //hide form after success 
      } 
      $("#contact_form_2 #contact_results").hide().html(output).slideDown(); 
     }, 'json'); 
    } 
}); 

//reset previously set border colors and hide all message on .keyup() 
$("#contact_form_2 input[required=true], #contact_form_2 textarea[required=true]").keyup(function() { 
    $(this).css('border-color', ''); 
    $("#contact_results").fadeOut("fast"); 
}); 


$("#submit_btn_2").click(function(e) { 
    e.preventDefault(); 
    //Rest of your code 

}); 

PHP 코드

<?php 
if($_POST) 
{ 
    $to_email  = "[email protected]"; //Recipient email, Replace with own email here 

    //check if its an ajax request, exit if not 
    if(!isset($_SERVER['HTTP_X_REQUESTED_WITH']) AND strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) != 'xmlhttprequest') { 

     $output = json_encode(array(//create JSON data 
      'type'=>'error', 
      'text' => 'Sorry Request must be Ajax POST' 
     )); 
     die($output); //exit script outputting json data 
    } 

    //Sanitize input data using PHP filter_var(). 
    $user_name  = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING); 
    $user_email  = filter_var($_POST["user_email"], FILTER_SANITIZE_EMAIL); 
    $phone_number = filter_var($_POST["phone_number"], FILTER_SANITIZE_NUMBER_INT); 
    $message  = filter_var($_POST["msg"], FILTER_SANITIZE_STRING); 

    //additional php validation 
    if(strlen($user_name)<3){ // If length is less than 3 it will output JSON error. 
     $output = json_encode(array('type'=>'error', 'text' => 'Name is too short or empty!')); 
     die($output); 
    } 
    if(!filter_var($user_email, FILTER_VALIDATE_EMAIL)){ //email validation 
     $output = json_encode(array('type'=>'error', 'text' => 'Please enter a valid email!')); 
     die($output); 
    } 

    if(!filter_var($phone_number, FILTER_SANITIZE_NUMBER_FLOAT)){ //check for valid numbers in phone number field 
     $output = json_encode(array('type'=>'error', 'text' => 'Enter only digits in phone number')); 
     die($output); 
    } 

    if(strlen($message)<3){ //check emtpy message 
     $output = json_encode(array('type'=>'error', 'text' => 'Too short message! Please enter something.')); 
     die($output); 
    } 

    //email body 
    $message_body = " 

    Name:".$user_name."\r\n 
    Email: ".$user_email."\r\n 
    Phone Number: ". $phone_number."\r\n 
    Message:".$message 
    ; 

    //proceed with PHP email. 
    $headers = 'From: '.$user_name.'' . "\r\n" . 
    'Reply-To: '.$user_email.'' . "\r\n" . 
    'X-Mailer: PHP/' . phpversion(); 

    $send_mail = mail($to_email, "Message from site", $message_body, $headers); 

    if(!$send_mail) 
    { 
     //If mail couldn't be sent output error. Check your PHP email configuration (if it ever happens) 
     $output = json_encode(array('type'=>'error', 'text' => 'Could not send mail! Please check your PHP mail configuration.')); 
     die($output); 
    }else{ 
     $output = json_encode(array('type'=>'message', 'text' => ' 

      <div class="popup_icon"><i class="fa fa-check "></i></div> 
<div class="popup_title">Спасибо за контакт со STYX!</div> 
<div class="popup_subtitle">Мы ответим очень скоро.</div> 


')); 
     die($output); 
    } 
} 
?> 

무엇 프로이다. 흠집; 문제는 내가 "이름이 너무 짧거나 비어 있습니다!"입니다. 매우 긴 이름을 쓸 때도 오류가 발생합니다. 나에게 도움이 될 사람이 있습니까?

미리 감사드립니다.

+0

문제를 디버그하고 문제의 출처를 찾으십니까? 최소 언어로 좁혀 라. – khelwood

+0

'echo $ _POST [ "user_name]"'을 PHP 스크립트에 넣으십시오. 데이터가 실제로 PHP 스크립트에 게시되어 있는지 테스트하십시오. – Twinfriends

+0

아니요 어디서 문제가 발생하는지 알 수 없었습니다. 그래서 모든 코드를 넣었습니다. 그러나 script.js의 어딘가에서 문제를 이해함에 따라 – Itrader

답변

0

문제 해결에 필요한 두 가지 사항이있을 수 있습니다.

  1. jQuery 스크립트가 user_name POST를 보내지 못하거나 선택기에서 값을 찾지 못했습니다.
  2. PHP가 $_POST['user_name']을 (를) 살균하고 많은 문자열을 제거합니다.

문제 해결 :. 크롬이나 파이어 폭스를 사용

1. 은, 크롬에이 콘솔 탭에 Options > More Tools > Developer Tools

클릭에서 발견된다 (개발자 콘솔 또는 개발 도구를 열 다음 두 > 기호 입력 $('input[name=name]').val() undefined을 반환하면 브라우저에서이 선택자를 찾을 수 없습니다.

잠재적 인 수정, 대신를 사용하십시오 name 속성도 name jQuery를 힘든 시간이 구문 분석이있을 수있다 $("input[name='name']").val()

때문입니다. *추측. 당신의 PHP 오른쪽을 $_POST 데이터

을 얻는 경우


2. 확인 내가 스크립트의 매우 시작시 신속하고

echo json_encode(array("type"=>"error", "text" => print_r($_POST,true)); 
exit(); 

더러운을 좋아 볼 수 있습니다.

다음 주석 시도 :

//Sanitize input data using PHP filter_var(). 
// > $user_name  = filter_var($_POST["user_name"], FILTER_SANITIZE_STRING); 

이 작동하는 경우에, 당신은 필터 VAR이 변수를 죽이고 알고있다.

0

나는 모든 아이디어를 다 해 보았습니다. 우선 모든 것에 감사드립니다. 두 개의 문의 양식이 있고 두 "매개 변수"매개 변수가 섞여서 문제가 발생했습니다. #contact_form 및 #contact_form_2를 추가하여 수정했습니다.

  'user_name'  : $('#contact_form input[name=name]').val(), 
      'user_email' : $('#contact_form input[name=email]').val(), 

      'phone_number' : $('#contact_form input[name=phone]').val(), 
      'subject'  : $('#contact_form select[name=subject]').val(), 
      'msg'   : $('#contact_form textarea[name=message]').val() 



      'user_name'  : $('#contact_form_2 input[name=name]').val(), 
      'user_email' : $('#contact_form_2 input[name=email]').val(), 

      'phone_number' : $('#contact_form_2 input[name=phone]').val(), 
      'subject'  : $('#contact_form_2 select[name=subject]').val(), 
      'msg'   : $('#contact_form_2 textarea[name=message]').val() 
관련 문제