2012-05-15 2 views
0

기본적으로 무슨 일이 발생합니까? 이메일을 보낼 수있는 PHP 양식이 있습니다. 여러 가지 유효성 검사 단계가 진행되는데, 모두 잘 작동합니다. 폼을 제출할 때 유효성 검사 오류가 있으면 자바 스크립트 경고 팝업이 나타납니다. 나는이 다음 PHP로 작업 한 :리디렉션 페이지가없는 PHP 양식 유효성 검사 알림

// Validate email 
if(!filter_var($EmailFrom, FILTER_VALIDATE_EMAIL)) 
{ 
    echo "<script language=javascript>alert('Please Use a Valid Email Address')</script>"; 
    exit; 
} 

경고가 나타나고 있지만 페이지가 빈 페이지와 사용자 잎있는 domain.com/sendemail.php 리디렉션. 정말 페이지를 다시로드하지 않고 경고 팝업을하고 싶습니다. 어떻게하면 좋을까요?

+1

가장 좋은 방법은 Ajax를 사용하는 것입니다. – VisioN

답변

0

이 스크립트는 내가 그것을 검증하기 위해 만든 몇몇 형태로 사용 된 스크립트입니다. 매우 간단하고 효과적입니다. 도움이 되었기를 바랍니다.

<script type="text/javascript"> 
function validate(){ 
    emailfilter = /^([a-zA-Z0-9_\.\-])+\@(([a-zA-Z0-9\-])+\.)+([a-zA-Z0-9]{2,4})+$/; 
    condition = 1; 
    mensaje = "Complete: "; 
    //Validate 1st input (Check if empty) 
    if (document.formname.forminput1.value.length==0){ 
     condition = 0; 
     msg = msg + "-Input 1 is empty " 
    } 
     //Validate 1nd input (Check email) 
    if (!emailfilter.test(document.formname.forminput1.value)) { 
     condition = 0; 
     msg = msg + "-Input 1 has a invalid email adresss " 
    } 

    if (condition == 0){ 
     alert(msg) 
     document.formname.forminput1.focus() 
     return 0; 
    } 

    //send 
    alert("Form sended."); 
    document.formname.submit(); 
} 
</script> 
0

아약스를 사용하여이를 수행 할 수 있습니다. 그러나 아약스 사용을 원하지 않는다면 오류가 발생하면 종료하는 대신 쿼리 문자열 매개 변수와 함께 양식 페이지로 다시 리디렉션 할 수 있습니다.

header("Location: http://www.example.com/form.php?error=1"); 

그리고 양식 페이지에서 PHP로 스크립트를 넣을 수 있습니다. 예 :

<?php if(isset($_GET['error']) && $_GET['error']==1): ?> 
<script> 
.... 
</script> 
<?php endif; ?> 

당신이 찾고있는 것이 달성 될 것입니다. 사실 여러 번 검사를 수행하고 검사를 기반으로 오류를 설정할 수 있습니다. 그러나 Ajax가 더 나은 사용자 경험을 제공 할 것이라고 제안합니다.

0

편집 : 슈퍼 쉬운 솔루션, jQuery를 양식 플러그인을 사용 http://jquery.malsup.com/form/

내 웹 응용 프로그램의 일부 비슷한 일을 할, 당신이 유용 할 수 있습니다.

나는 내 검증 서버 측을하고 내가 오류가 발생할 경우, 나는이 수행

json_die(array(
    'status' => 'error', 
    'message'=> 'Your error message' 
)); 

과 성공을위한

가 :

json_die(array(
    'status' => 'success', 
    'message'=> 'Your success message' 
)); 

json_die 기능이 있습니다 :

function json_die($array) { 
     header("content-type: application/json"); 
     die(json_encode($array, true)); 
} 

프런트 엔드에서 다음과 같이합니다.

$.post('/your_url', { 
         'your': vars 

        }, function (r) { 

         if(r.status == 'success') { 

          alert(r.message); 

         } else if (r.status == 'error') { 

          alert(r.message); 
          //handle error 

         } else { 
          alert('server exploded/no connection'); 
         } 

        },'json');