2016-08-30 2 views
0

간단한 검색을 수행 한 후에 값이있는 양식을 채우려하고 있지만 스크립트를 실행할 때 "undefined"또는 빈 응답이 표시됩니다. 경고 (데이터);PHP : ajax를 사용하여 쿼리 결과로 html 양식 필드를 채우는 방법

search.php

<?php 
include_once 'config/config.php'; 
include_once 'config/connect.php'; 
$conn = dbconn(); 

if(isset($_POST['btn-search'])) 
{ 
    $sub_id = mysqli_real_escape_string($conn, $_POST['user_id']); 
    $sql = "SELECT * FROM users WHERE user_id = '".$sub_id."'"; 
    $res = mysqli_query($conn, $sql); 
    $row = mysqli_fetch_array($res); 

    $found = array(); 
    while ($row = mysqli_fetch_array($res)) 
    { 
     $found[] = array(
      'name' => $row['full_name'], 
      'init_date' => $row['init_date'], 
      'position' => $row['position'], 
      'email' => $row['email'], 
     ); 
     echo json_encode($found); 
    } 
} 
mysqli_close($conn); 
?> 

스크립트

<script> 
/* 
simple validation script 
*/ 

$('document').ready(function() 
{ 
    $('#register-submit-btn').attr('disabled', 'disabled'); 
    /* validation */ 
    $("#register-form").validate({ 
     rules: 
     { 
      user_id: { 
      required: true, 
      minlength: 5, 
      }, 
     }, 
     messages: 
     { 
      cedulaid:{ 
         required: "The user ID is required", 
         minlength: "The user ID should be no less than 5 characeters long.", 
        }, 
     }, 
     submitHandler: submitForm 
     }); 
     /* validation */ 

     /* get data */ 
     function submitForm() 
     {   
      var data = $("#details-form").serialize(); 

      $.ajax({ 
      type : 'POST', 
      url : 'search.php', 
      data : data, 
      beforeSend: function() 
      { 
       $("#detailsmsg").fadeOut(); 
       $("#btn-search").html('<img src="include/btn-ajax-loader.gif" /> &nbsp; Looking...'); 
       $('#btn-search').attr('disabled', 'disabled'); 
      }, 
      success : function(data) 
       { 
       alert(data); 
         $("#detailsmsg").fadeIn(1000, function(){      
         $("#detailsmsg").removeClass("alert-danger").addClass("alert-success"); 
         $('#btn-search').removeAttr('disabled'); 
         $("#btn-search").html('Search again?'); 
         $('#register-submit-btn').removeAttr('disabled'); 
         $("#detailsmsg").html("<span>Data Found</span>"); 

         }); 
         $("#name").val(data.name); // not sure how to do this part. this is probably very wrong but still not getting anything on the alert. 
         $("#init_date").val(data.init_date); 
         $("#position").val(data.position); 
         $("#email").val(data.email); 
       } 
      }); 
       return false; 
     } 
     /* get data */ 
}); 
</script> 

내가 얻을 것이 무엇을보고 싶어하기 때문에 나는 성공 함수의 상단에있는 경고 (데이터)가 돌아 오지만 그것은 다시 비어있게됩니다. 내가 경고 (데이터 [0]) 할 경우 "정의되지 않은"메시지가 나타납니다.

콘솔 POST 반환이 :

name=&init_date=&position=&email= 

이 스크립트에서 많은 실수가 아마 나는 내가 할 수있는 모든 피드백과 도움에 열려있어. 다른 세부 정보가 필요한지 알려주세요. 사전에

감사합니다, 단지 빨리이 중첩 된 배열을 반환하는 PHP 코드를보고

+2

는 echo json_encode ($ found)를 넣으려고 시도 할 수 있습니다. search.php에서 벗어난 루프 –

답변

3

단일 출력을 얻으려면 $ row = mysqli_fetch_array ($ res) 만 필요합니다. 루프가 아닙니다. 단일 매개 변수 출력을 반환합니다.

Search.php 

<?php 
include_once 'config/config.php'; 
include_once 'config/connect.php'; 
$conn = dbconn(); 

if(isset($_POST['btn-search'])) 
{ 
    $sub_id = mysqli_real_escape_string($conn, $_POST['user_id']); 
    $sql = "SELECT * FROM users WHERE user_id = '".$sub_id."'"; 
    $res = mysqli_query($conn, $sql); 
    $row = mysqli_fetch_array($res); 

    $found = array(); 

     $found[] = array(
      'name' => $row['full_name'], 
      'init_date' => $row['init_date'], 
      'position' => $row['position'], 
      'email' => $row['email'], 
     ); 
     echo json_encode($found); 

} 
mysqli_close($conn); 
?> 

한번 시도해보십시오. 도움이 될 수도 있습니다.

+0

고맙습니다. @Kamlesh 굽타. 당신의 제안은 약간 진전되었습니다. 나는 이번에 결과를 얻었지만, 모든 값을 얻었습니다. [{ "name": null, "init_date": null, "position": null, "email": null}].이 예제를 사용하여 샘플 user_id를 사용하여 데이터베이스를 쿼리하면 찾고있는 결과를 얻을 수 있으므로 쿼리와 관련이 없다고 생각합니다. 어떤 아이디어? – BlueSun3k1

+0

좋아요, 저는 data : data : {user_id : $ ('# user_id'). val()}에 대한 ajax 호출에서 data : data 수정을 변경하여 배열에 값을 가져 왔습니다. if (isset ($ _ POST [ 'btn-search']))에서 if (isset ($ _ POST [ 'user_id']))로 PHP 스크립트를 실행합니다. 이제 입력 필드에 값을 가져 오는 방법은 무엇입니까? – BlueSun3k1

+0

나는 일하도록했다. JSON.stringify (data)를 사용하고 있는데 배열 결과를 얻었지만 dataType : 'json'을 제거하고 result = jQuery.parseJSON (data); 이제 result.user_id를 사용하여 배열에서 값을 가져올 수 있습니다. 그래서 $ ("# user_id"). val (result.user_id); 이제 작동합니다. – BlueSun3k1

1

: 당신이 먼저 $found = array();을 정의하고 $found[] = array(...)으로 더 많은 배열을 추가하기 때문에

[ 
    [ 
     'name' => 'whatever', 
     'init_date' => 'date', 
     ... 
    ] 
] 

발생합니다.

그러나 자바 스크립트 부분은 존재하지 않는 data.name에 액세스하려고합니다. 아마도 data[0].name이 데이터베이스에 최소한 하나의 레코드가 있다고 가정해야합니다.

대신 배열로 data을 반복 하시겠습니까?

그러나 어쩌면 문제는 두 번 mysqli_fetch_array()를 호출하기 때문에 $row 변수를 무시하고 발견 된 첫 번째 결과를 건너 뛰 PHP 부분에있다 :

$row = mysqli_fetch_array($res); 

$found = array(); 
while ($row = mysqli_fetch_array($res)) 
{ 
... 
내가 볼

마지막 것은 당신이 아마 후 echo json_encode($found);를 호출 할 것입니다 모든 검색 결과를 수집 할 때 while 루프가 발생합니다. 그건 그렇고, 이것은 또한 잘못된 JSON을 생성합니다.

+0

Martin 감사합니다. 나는 Kamlesh Gupta가 제안한대로 루프를 제거하고 약간의 진전을 이루었습니다. 반드시 데이터를 배열로 반복 할 필요는 없지만 좋은 접근 방법이라고 생각했습니다. 예상되는 필드를 채우기 위해 php 변수의 값을 전달하는 방법을 모르겠습니다. $ user_id = $ row [ 'user_id']와 같은 일반 변수를 수행하면; 어떻게 값을 폼에로드 할 수 있습니까? – BlueSun3k1

관련 문제