2012-08-29 3 views
0

저는 PHP 초보예요. 이제 학습 과정에서 입력을 검증하는 연습을합니다. 보통 순수 PHP 코드만을 사용하여 입력을 검증하고 입력을 검증하여 페이지를 새로 고침 할 때마다 http://api.jquery.com/jQuery.ajax/, http://api.jquery.com/jQuery.post/ (다른 링크를 게시 할 수 없음)과 같은 기사를 찾았지만 다른 접근법을 갖고 있기 때문에 혼란 스럽습니다. Jquery 튜토리얼에서 접근 방법을 사용하고 싶지만 아무 것도 발견하지 못했습니다. 좋은 자습서 및 데이터베이스를 사용하고 jQuery의 사이트에는 튜토리얼이없는, 보통 나는 다음과 같은 코드 :페이지를 다시로드하지 않고 데이터베이스에서 직접 입력을 확인하려면 어떻게해야합니까?

<form method="post"> 
<label for="Username">Username:</label> 
<input id="Username" type="text" name="username"> 
<?php 
session_start(); 
if(isset($_SESSION['msg'])){ 
$msg=$_SESSION['msg']; 
echo '<label for="Username">'.$msg.'</label>'; 
?> 
<input type="submit" name="reg"> 
</form> 
<?php 
if(isset($_POST['reg'])){ 
$result=//check username from database here 
if($result){ 
$_SESSION['msg']='username not available.'; 
} 
else { 
$_SESSION['msg']='username available.'; 
} 
} 
?> 

은 이제 페이지를 다시로드하지 않고 내가 데이터베이스에서 직접 입력을 확인할 수있는 방법을 배우고 싶어요? 어디에서 시작해야하는지, 내 코드에 무엇을 추가해야할지 모르겠습니다. 모든 도움, 조언 또는 제안은 내게 큰 도움이 될 것입니다.

+0

데이터베이스에서 직접 백엔드를 의미합니까? 그 경우에는 아약스로 할 수 있다고 생각합니다. – insomiac

+1

페이지를 새로 고칠 것으로 예상하는 것처럼 유효성 검사 스크립트를 작성하십시오. 오류 메시지를 출력하는 대신 JSON 배열에 넣고 JSON 데이터를 인쇄하십시오. 그런 다음 AJAX 함수에서 스크립트를 호출하십시오. 정말 간단합니다. – Matt

+0

예, jquery에서 자습서를 읽었지만 데이터베이스가 없습니다. –

답변

0

첫째, 양식의 onSubmit 함수를 추가

<form name='myform' type='POST' action='http://www.action.fr' onSubmit="return check_form()"> 

이렇게 할 수 있습니다. 잭스는 PHP 파일에서 그

function check_form() 
{ 
    var user = $('#Username').val(); // Username is the id of your input 
    var password = $('#password').val(); // password is the id of your input 
    $.ajax(
    { 
    type:"POST", // or get as you want 
    url:"myfile.php", // it is the php file which can do the job 
    data: "user="+user+"&password="+password, // the param to send to your file, 
    success:function(msg) 
    { 
      ;// msg is the result of your 'myfile.php', everything you write is in the msg var 

    } 
    }); 
} 

처럼이 같은 데이터를 얻을 수 있습니다 : 당신이 내 코드에 문제가있는 경우

$user = $_POST['user']; 
$password = $_POST['password']; 
// if your type is get then use $_GET instead of $_POST 

말해.

+0

나는 당신의 함수 check_form()에서 당신이 반환 false가 있어야합니다 말을 깜빡; 결국. 양식 검증을하지 않을 경우 페이지가 다시로드됩니다. – dharth

+0

}}; 이 부분 이후에 내가 거짓을 돌려 놓았습니까? –

+0

PHP 파일에 echo를 넣으면 성공에 무엇을 넣어야합니까? function (msg) {? –

0

페이지 새로 고침을 기대하는 것처럼 유효성 검사 스크립트를 작성하십시오. 오류 메시지를 출력하는 대신 JSON 배열에 넣고 JSON 데이터를 인쇄하십시오. 그런 다음 AJAX 함수에서 스크립트를 호출하십시오. 정말 간단합니다.

<form action="" method="post" id="theForm"> 
    <input type="text" name="sampleInput_number" id="sampleInput_number" /> 
    <input type="button" id="formSubmit" value="Submit" /> 
</form> 

을 그리고 당신의 자바 스크립트는 다음과 같이 보일 것이다 :

<?php 
// validate.php 

$sampleInput_number = isset($_POST['sampleInput_number']) ? $_POST['sampleInput_number'] : ""; 

$errors = array(); 
if (trim($sampleInput_number) == "" || !is_numeric(trim($sampleInput_number)) { 
    $errors[] = "SampleInput_number must be a number!"; 
} 

// sample input must also match a value from the database 
if (!matchesDBValue($sampleInput_number)) { 
    $errors[] = "SampleInput_number must match a value from the database!"; 
} 

function matchesDBValue($value) { 
    $retval = false; 

    // compare to db values here... 

    return $retval; 
} 

echo json_encode($errors); 

양식은 다음과 같이 보일 것

<script language="javascript" type="text/javascript"> 
    $(#formSubmit).on("click", function() { 
     $.post("validate.php", 
      { 
       sampleInput_number: $("#sampleInput_number").val() 
      }, function(data) { 
       // check returned json data 
       // perform action based on results 

       if (no_errors) { 
        $("#theForm").submit(); 
       } 
      }, "json" 
     ); 
    }); 
</script> 
+0

미안 hehe :) - –

관련 문제