使用JQuery,Ajax和PHP将数据填充到表中

时间:2015-10-21 16:07:55

标签: javascript php jquery ajax pdo

我想在HTML表格中填充数据库结果。单击<a class="editUsers">时,会弹出一个框以显示来自Ajax调用的数据。

应该显示:

<table id="userInfo">
    <tr>
        <thead>
            <td>User</td>
            <td>Mail</td>
            <td>Admin Access</td>
        </thead>
    </tr>
    <tr>
        <td>Jane Doe</td>
        <td>janedoe@islost.com</td>
        <td>Yes</td>
    </tr>
</table>        
$(".editUsers").click(function(){
    $("#userInfo").fadeIn(1000);
    $(".exitUsrMgmt").fadeIn(1000); //This is the close button for that popup

    $.ajax({    //create an ajax request to load_page.php
        type: "GET",
        url: "includes/getUserData.php",             
        dataType: "html",   //expect html to be returned                
        success: function(response){                   
            ("#userInfo").html(response);
        },
        error:function (xhr, ajaxOptions, thrownError){
            alert(thrownError);
        }
    });
}); 
<?php
  include_once('config.php');

  //Create PDO Object
  $con = new PDO( DB_DSN, DB_USERNAME, DB_PASSWORD );
  //Set Error Handling for PDO
  $con->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION );
  //Query
  $sql = "SELECT name, email, admin FROM user_admin";

  //Prepare Statement
  $stmt = $con->prepare($sql);
  $stmt->execute();

  while ($row = $stmt->fetch()){
    echo '<tr>';
    echo    '<td>'.$row[0].'</td>';
    echo    '<td>'.$row[1].'</td>';
    echo    '<td>'.$row[2].'</td>';
    echo '</tr>';
  }
?>

1 个答案:

答案 0 :(得分:1)

问题得到解决。我犯了一个愚蠢的错误,忘了加$。感谢Paul Roub的回答,我引用:

  

对于初学者,("#userInfo").html(response);缺少$。应该   $("#userInfo").html(response); - Paul Roub 8分钟前