PHP - Vấn đề về lấy dữ liệu từ ajax trả về

Mình có 2 file: list.php (trang hiển thị) và page.php (trang trả về dữ liệu)

  • Vấn đề: Không tìm được $_POST['size'], $_POST["employeeId".$i]… trong list.php, list.php lấy dữ liệu từ trang page.php trả về qua ajax là các <input....>
  • Lỗi: Undefined index: size, employeeId...
    Theo mình hiểu là: Không tìm được các <input> trong <form> vì ajax được thêm vào sau khi trang tải xong
  • Trong list.php:
...
if($_SERVER['REQUEST_METHOD'] == 'POST'){
    if (isset($_POST['btnSubmit'])) // Kiểm tra nút có giá trị dữ liệu
    {
        if($_POST['btnSubmit'] == '+')
        {
          $year = $_POST['year'];
          $insert = $workday->insert_year($year);
        }

        if($_POST['btnSubmit'] == 'Insert All')
        {
          $size = $_POST['size'];
          $workdayMonth = $_POST["workdayMonth"];
          $workdayYear = $_POST["workdayYear"];
          for ($i = 1; $i <= 6; $i++){
            $employeeId = $_POST["employeeId".$i];
            $dayWorked = $_POST["dayWorked".$i];
            $overTime = $_POST["overTime".$i];
            $insert = $workday->insert_workday($employeeId, ...);
          }
        }
    }
...
<form method="POST" action="" id="list">
<table>
           // Dữ liệu từ ajax được chèn vào đây
</table>
</form>
  • Trong page.php
...
if ($rs){
    while($row = $rs->fetch_assoc()){
      $i++;
      echo "
        <tr>
          <td class='py-3'>".$i."</td>
          <td class='py-3' value='".$row["Employee_id"]."' name='employeeId".$i."'>".$row["Employee_id"]."</td>
          <td class='py-3'>".$row["Fullname"]."</td>
          <td class='py-3'>".$row["Department_name"]."</td>
          <td class='py-3'>".$row["Position_name"]."</td>
          <td class='py-3'><input type=text name='dayworked".$i."' size=5 class='form-control'></td>
          <td class='py-3'><input type=text name='overtime".$i."' size=5 class='form-control'></td>
        </tr>
      ";
    }
  }
  echo "<input type='text' name='size' value='".$amount."'>";
...

Ajax là gì, mình chưa thấy có gì gọi là ajax gì ở đâu cả

4 Likes

Đúng như kisuluoibieng nhận xét, mình soi từng dòng xem có cái gì là Ajax, tuyệt nhiên không thấy có JavaScript hoặc tương tự xuất hiện.

Tào lao, mất căn bản!

3 Likes

AJAX = Asynchronous JavaScript And XML.
Nói nôm na cho dễ hiểu, Ajax hàng của javascript, không phải PHP

MÌnh có lướt qua code của bạn, mà tại không có thời gian để ngồi viết lại, nên sugget cho bạn keyword để search, vì cái này cũng đơn giản, chì cần làm theo ví dụ trên mạng tầm 2-3 lần là hiểu duoc vấn đề:

keyword để google “PHP HTML form submit”

Xào tơi xào lui mấy cái ví dụ, xong chỉnh sửa theo ý mình

Khi làm submit form, có thể bạn sẽ quan tâm thêm tới 2 thằng htmlentities và htmlspecialchars

và xa hơn chút là Cross-site request forgery (CSRF) và CAPTCHA (chống spam)

3 Likes

Đây là đoạn js ạ.
Trong list.php

  var index = 1;
  var amount = 5;
  var btnFilter = $("#btn-filter");
  $(document).ready(function(){
    var workday_employee = $("#workday_employee").val();
    var workday_department = $("#workday_department").val();
    var workday_position = $("#workday_position").val();
    var workday_employeeId = $("#workday_employeeId").val();
    $.get("page.php",
          {
            page:index,
            amount,
            workday_employeeId: workday_employeeId,
            workday_employee: workday_employee,
            workday_department: workday_department,
            workday_position: workday_position
          },
          function(data){
            $("#body_add_workday").append(data);
    });

Mong được a/c góp ý
Cảm ơn mọi người! :frowning:

Bạn làm theo link này

Ghi chú: Nhớ import jquery

3 Likes

Cảm ơn bạn nhiều <3 Mình cũng đang search trên trang này

  1. Code của bạn đang gọi get, trong khi php bạn lại lấy POST
  2. Data request của bạn gửi lên cũng chẳng có những field mà bạn lấy

bạn cần xác định rõ cái cần code rồi hãy code, bỏ cái tư tưởng ngồi gõ rồi sửa một hồi sẽ ra được kết quả mong muốn

4 Likes

Mình nghĩ thế này ko biết đúng ko?

  1. method của form của mình là POST, còn của ajax là GET. Mình đang lấy từ form nên mình dùng POST
  2. data gửi sang có name đó mà bạn, do code dài nên mình chỉ chụp 1 đoạn
    Nếu có thời gian thì bạn xem qua mình với!
    Ngoài ra code còn yếu phần nào mong được mn góp ý :frowning:
    Đây là full code:
  • list.php:
<?php include '../../classes/workday.php' ?>
<?php
  $workday = new Workday();
  if($_SERVER['REQUEST_METHOD'] == 'POST'){
    if (isset($_POST['btnSubmit'])) // Kiểm tra nút có giá trị dữ liệu
    {
        if($_POST['btnSubmit'] == '+')
        {
          $year = $_POST['year'];
          $insert = $workday->insert_year($year);
        }

        if($_POST['btnSubmit'] == 'Insert All')
        {
          $size = $_POST['size'];
          $workdayMonth = $_POST["workdayMonth"];
          $workdayYear = $_POST["workdayYear"];
          for ($i = 1; $i <= 6; $i++){
            $employeeId = $_POST["employeeId".$i];
            $dayWorked = $_POST["dayWorked".$i];
            $overTime = $_POST["overTime".$i];
            $insert = $workday->insert_workday($employeeId, $dayWorked, $overTime, $workdayMonth, $workdayYear);
          }
        }
    }
  }
?>
<?php include '../../inc/header.php' ?>
<div class="body row">
  <?php include '../../inc/sidebar.php' ?>
  <div class="content col-10 col-sm-9 col-xl-10">
    <form class="insert-year" method="post" action="">
      <table class="mt-3">
        <tr>
          <td><input type="text" class="form-control" name="year" size="5" placeholder="Year"></td>
          <td>----</td>
          <td><input type="submit" class="btn btn-success" name="btnSubmit" value="+"></td>
        </tr>
      </table>
    </form>
    <div class="filter">
      <h3 class="text-center display-block">Filter</h3>
      <table class="table">
        <thead class="thead-light">
          <tr>
            <th scope="col">Employee Id</th>
            <th scope="col">FullName</th>
            <th scope="col">Department</th>
            <th scope="col">Position</th>
            <th scope="col">Action</th>
          </tr>
        </thead>
        <tbody>
          <td>
            <input type="text" id="workday_employeeId" name="workday_employeeId">
          </td>
          <td>
            <input type="text" id="workday_employee" name="workday_employee">
          </td>
          <td>
            <select class="form-control col-sm-8" id="workday_department" name="workday_department">
              <option selected value="">All</option>
              <?php
                $show = $workday->show('t_Department');
                if($show){
                  while($result = $show->fetch_assoc()){
              ?>
              <option value="<?php echo $result['Department_id']?>"><?php echo $result['Department_id']." - ".$result['Department_name']; ?></option>
              <?php
                  }
                }
               ?>
            </select>
          </td>
          <td>
            <select class="form-control col-sm-8" id="workday_position" name="workday_position">
              <option selected value="">All</option>
              <?php
                $show = $workday->show('t_Position');
                if($show){
                  while($result = $show->fetch_assoc()){
              ?>
              <option value="<?php echo $result['Position_id']?>"><?php echo $result['Position_id']." - ".$result['Position_name']; ?></option>
              <?php
                  }
                }
               ?>
            </select>
          </td>
          <td>
            <button id="btn-filter" class="btn btn-success">Filter</button>
          </td>
        </tbody>
      </table>
    </div>
    <h3 class="text-center display-block">Insert Workday Infomation</h3>
    <?php
      if(isset($insert)){
        echo $insert;
      }
    ?>
    <form  id="insert-workday" class="mx-auto" action="" method="post">
      <table style="margin-bottom: 10px">
        <tr>
          <td style="padding-right: 10px">
            <label>Year:</label>
          </td>
          <td style="width: 150px">
            <select class="form-control col-sm-8" id="worday_year" name="workdayYear">
              <option selected value="">All</option>
              <?php
                $show = $workday->show('t_Salary_year');
                if($show){
                  while($result = $show->fetch_assoc()){
              ?>
              <option value="<?php echo $result['Salary_year']?>"><?php echo $result['Salary_year']?></option>
              <?php
                  }
                }
               ?>
            </select>
          </td>
          <td style="padding-right: 10px">
            <label>Month:</label>
          </td>
          <td style="width: 100px">
            <select class="form-control col-sm-8" id="workday_month" name="workdayMonth">
              <option selected value="">All</option>
              <?php
                for ($i=1; $i<=12; $i++){
              ?>
              <option value="<?php echo $i?>"><?php echo $i ?></option>
              <?php
                }
               ?>
            </select>
          </td>
        </tr>
      </table>

      <table id="add-workday" class="table table-striped">
        <thead class="thead-dark">
          <tr>
            <th scope="col">Ordinal</th>
            <th scope="col">Employee Id</th>
            <th scope="col">Fullname</th>
            <th scope="col">Department</th>
            <th scope="col">Position</th>
            <th scope="col">Day worked</th>
            <th scope="col">Overtime</th>
          </tr>
        </thead>
        <tbody id="body_add_workday">

          <!-- Chèn nội dung ajax ở đây -->

        </tbody>
      </table>
      <input type="submit" class="btn btn-success" name="btnSubmit" value="Insert All">
      <nav aria-label="Page navigation example">
        <ul class="pagination justify-content-center" id="workday-pagenumber">

          <!-- Chèn nội dung ajax ở đây -->

        </ul>
      </nav>
    </form>

  </div>
</div>
<script>
  var index = 1;
  var amount = 5;
  var btnFilter = $("#btn-filter");
  $(document).ready(function(){
    var workday_employee = $("#workday_employee").val();
    var workday_department = $("#workday_department").val();
    var workday_position = $("#workday_position").val();
    var workday_employeeId = $("#workday_employeeId").val();
    $.get("page_add.php",
          {
            page:index,
            amount,
            workday_employeeId: workday_employeeId,
            workday_employee: workday_employee,
            workday_department: workday_department,
            workday_position: workday_position
          },
          function(data){
            $("#body_add_workday").append(data);
    });

    $.get("page_number_add.php",
          {
            amount,
            workday_employeeId: workday_employeeId,
            workday_employee: workday_employee,
            workday_department: workday_department,
            workday_position: workday_position
          },
          function(data){
      $("#workday-pagenumber").html(data);
    });

    // Cần nav.on() để load lại nav(nav là cha của page-link) trang sau khi gọi ajax
    $('nav').on('click','.page-link',function(e){
      e.preventDefault();
        var workday_employee = $("#workday_employee").val();
        var workday_department = $("#workday_department").val();
        var workday_position = $("#workday_position").val();
      index = Number($(this).text());
      $("li").removeClass('active');
      $(this).parent().addClass('active');
      $.get("page_add.php",
            {
              page:index,
              amount,
              workday_employeeId: workday_employeeId,
              workday_employee: workday_employee,
              workday_department: workday_department,
              workday_position: workday_position
            },
            function(data){
              $("#body_add_workday").html(data);
      });
    });

    $("#btn-filter").click(function(){
      index = 1;
        var workday_employee = $("#workday_employee").val();
        var workday_department = $("#workday_department").val();
        var workday_position = $("#workday_position").val();
      $.get("page_add.php",
            {
              page:index,
              amount,
              workday_employeeId: workday_employeeId,
              workday_employee: workday_employee,
              workday_department: workday_department,
              workday_position: workday_position
            },
            function(data){
        $("#body_add_workday").html(data);
      });
      $.get("page_number_add.php",
            {
              amount,
              workday_employeeId: workday_employeeId,
              workday_employee: workday_employee,
              workday_department: workday_department,
              workday_position: workday_position
            },
            function(data){
        $("#workday-pagenumber").html(data);
      });
    });
  });

</script>
<?php include '../../inc/footer.php' ?>

  • page_add.php (nó là trang page.php mà mình nói ở trên)
<?php
  include '../../lib/database.php';
  $database = new Database();
  $where = $_GET['page'];
  $amount =$_GET['amount'];
  $employeeId = empty($_GET['workday_employeeId'])?'%':$_GET['workday_employeeId'];
  $fullname = empty($_GET['workday_employee'])?'%':$_GET['workday_employee'];
  $department = empty($_GET['workday_department'])?'%':$_GET['workday_department'];
  $position = empty($_GET['workday_position'])?'%':$_GET['workday_position'];
  settype($page,"int");
  $start = ($where - 1) * $amount;
  $rs = $database->filter_employee_limit($employeeId, $fullname, '%', $department, $position, '%', '%', '%', '30000101', '1', $start, $amount);
  $i = $start;
  if ($rs){
    while($row = $rs->fetch_assoc()){
      $i++;
      echo "
        <tr>
          <td class='py-3'>".$i."</td>
          <td class='py-3' value='".$row["Employee_id"]."' name='employeeId".$i."'>".$row["Employee_id"]."</td>
          <td class='py-3'>".$row["Fullname"]."</td>
          <td class='py-3'>".$row["Department_name"]."</td>
          <td class='py-3'>".$row["Position_name"]."</td>
          <td class='py-3'><input type=text name='dayworked".$i."' size=5 class='form-control'></td>
          <td class='py-3'><input type=text name='overtime".$i."' size=5 class='form-control'></td>
        </tr>
      ";
    }
  }
  echo "<input type='text' name='size' value='".$amount."'>";
?>

Ghi chú: file page_number_add.php chỉ để đánh số trang

  • page_number_add.php
<?php
  include '../../lib/database.php';
  $database = new Database();
  $amount =$_GET['amount'];
  $id = empty($_GET['workday_employeeId'])?'%':$_GET['workday_employeeId'];
  $employee = empty($_GET['workday_employee'])?'%':$_GET['workday_employee'];
  $department = empty($_GET['workday_department'])?'%':$_GET['workday_department'];
  $position = empty($_GET['workday_position'])?'%':$_GET['workday_position'];
  $rs = $database->filter_employee($id, $employee, '%', $department, $position, '%', '%', '%', '30000101', '1');
  if ($rs){
    $num = $rs->num_rows;
      $totalPage = ceil($num / $amount);
      echo "<li class='page-item active'><button class='page-link'>1</button></li>";
      for ($i = 1;$i<$totalPage;$i++){
        echo "<li class='page-item'><button class='page-link'>".($i+1)."</button></li>";
      }
    }
  else{
    echo "<p class='alert alert-warning'>Khong co du lieu</p>";
  }

?>

Mặt dày ăn chửi để còn tiến bộ :frowning:

1 Like

đọc cách mô tả của bạn làm mình có cảm giá khá bực mình, kiểu bạn đang không hiểu code, mà lúc thì lại ajax, lúc thì lại form post, title chẳng liên quan nội dung mô tả

tuy nhiên sau khi đọc kĩ lại thì … đúng là như vậy

vấn đề của bạn chỉ là bạn click nút submit form post, nhưng server thì không nhận được những dữ liệu trong form. chỉ thế thôi
vậy thì bạn cần kiểm tra lại trong form bạn đã post có những field đó hay không, bằng cách mở html xem trước khi post form, và check tab network trên trình duyệt xem form data có giống với input trong html hay không. tất cả chỉ cần phím f12 và click chuột trên chrome thôi

trông thì dễ như vậy, nhưng với những gì bạn đang show ra, chả ai chạy thử được mà kiểm tra giúp bạn.
mà có chạy thử được thì riêng bản thân mình cũng không hứng thú copy về - chạy thử - đọc hiểu và giải thích giúp bạn nữa

có tinh thần ăn chửi để tiến bộ cũng hay, nhưng với mô tả của bạn thì chắc khó có ai giúp được

4 Likes

Mình thấy không có gì lạ lắm, ở chỗ bạn ý mới nên mấy khái niệm còn mơ hồ.

  1. Bạn không nắm được post/get. Cái cơ bản nhất là get thì mọi thứ nằm trên url, post thì không.
  2. Ajax là gì bạn nắm cũng không kỹ. Cũng dễ hiểu vì bản chất của get/post bạn còn lơ mơ
  3. Việc post lẻ tẻ file là rất đáng phê phán, cấu trúc code, file nọ include file kia thì chỉ bạn biết, không post lên thì không ai biết mà chỉ.

Do bạn đã cất công post hết lên rồi nên mình hướng dẫn sơ qua một chút, còn lại vẫn là bạn tự mò tiếp

  1. Cơ chế truyền nhận dữ liệu
    Khi bạn gõ 1 từ khóa lên google, rồi enter. Bạn đang hỏi google: ê đưa kết quả đây, hay nói cách khác, bạn muốn lấy thông tin từ google về, đây gọi là GET
    Google nhận được yêu cầu của bạn, xem xét từ khóa, rồi đi lọc trong database để trả về kết quả tương ứng với từ khóa của bạn

Đây là mô hình ví dụ đơn giản nhất để hình dung client - người dùng gõ từ khóa, server - google nhận request từ user, database hoạt động thế nào.

POST thì đơn giản thôi, bạn muốn gửi thông tin cho server, ví dụ đăng ký dịch vụ, bạn cần gửi/post username, email, password về để đăng ký với server

  1. Theo như code của bạn thì khi gọi $.get thì chính là lúc bạn đang yêu cầu server, chính là file page.php, trả về kết quả. Kể từ đây bạn tạm hiểu mỗi khi nhắc tới server, mình đang ám chỉ code ở PHP của bạn.

Tại file page.php này, bạn kiểm tra request phải ở dạng post, trong khi truyền lên lại là get. Nên việc không nhận thông tin là dễ hiểu, undefined index, size… gì gì là đương nhiên xảy ra.

  1. Bạn nói ajax là get. Đây là nhận định sai.
    Ajax là 1 cách cho phép gửi nhận dữ liệu mà không phải refresh lại trang. Hết. Chỉ có vậy. Gửi nhận dữ liệu là gì thì mình đã nói qua ví dụ google ở trên.

Tức là nếu đoạn code này không dùng ajax, nó vẫn có thể thực hiện được yêu cầu gửi nhận dữ liệu.
Cái riêng của ajax chỉ có mỗi là không bị refresh trang, hình dung bạn submit form, trang refresh, thì toàn bộ những gì đang làm trên trang, ví dụ như các input đang điền dở, sẽ mất focus (con trỏ không còn nháy tại input đấy nữa). Đây là mình ví dụ qua vậy cho dễ hiểu. Còn bạn muốn hiểu nhiều hơn thì tìm đọc trên mạng tiếp

  1. Code có vẻ như đang sai
    3 điều trên là đủ giúp bạn đi tiếp rồi, không cần đọc phần này cũng được. Vì với kiến thức hiện tại của bạn thì cũng không hẳn là sẽ hiểu.

Mình mới đọc qua thôi không đi sâu vào code. Nhưng hiểu là sau đoạn $(document).ready bạn gọi luôn ajax, đây là điều khá dị. Hay nói dễ hiểu hơn là khi chưa có tác động của user thì tự thân đoạn code lại gửi yêu cầu về server lấy dữ liệu.
Các bước gửi nhận dữ liệu sẽ như sau:

Ban đầu vào trang web -> server sẽ trả về trang web, bao gồm toàn bộ form, h1, h2…, bao gồm cả đoạn gọi ajax -> Sau đó ajax lại tiếp tục yêu cầu server trả về thêm thông tin thông qua $.get

Mấu chốt của chỗ này là chưa có tác động của user, tức là trang web từ khi server trả xuống, tới lúc gọi ajax, cả trang web không đổi gì, thế thì để server trả 100% code về cho nhanh. Cái đoạn ở dưới để server trả về tương tự như các thẻ input, form ấy, dùng ajax làm gì đâu

<table>
    // Dữ liệu từ ajax được chèn vào đây
</table>
8 Likes

Bạn cũng nên chú ý là học phải tới 1 mức độ nào đó, đủ ngấm thì mới hiểu được. Người ta mất 2h để hiểu 1 công thức, thì bạn mất 2h30’ hoặc hơn.
Miễn bạn chịu bỏ ra thời gian, và hiểu là bản thân cần bỏ nhiều công sức tìm kiếm và thực hành nhiều hơn.

Post lên đi hỏi thì cần đầy đủ và ngắn thôi.
Ví dụ như bài này, bản chất chỉ là $.get gửi lên server, server không nhận đc dữ liệu. Hết.
Bạn post mấy thứ loằng ngoằng include, với query database là thừa.

Có thể bạn không nhận ra bản chất nên buộc phải post code full, nhưng nên nhớ là không phải ai cũng rảnh để đi đọc hết code của bạn.

Tiếp nữa là bạn nên trình bày kỹ hơn, về phía bạn đã tìm hiểu được gì, đừng chỉ khơi khơi nói “không chạy, lỗi error…”
Thay vì nói vậy thì bạn nên trình bày lại: “theo e hiểu lỗi này là do abc, e lên google thì thấy họ chỉ là xyz…” thì người đọc người ta thấy được là bạn đang lắng nghe hướng dẫn và đã cất công đi tìm mà không giải quyết được.

Đây cũng chính là lý do mình trả lời vào topic này, vì nhận thấy kiến thức cơ bản còn yếu, và nắm khái niệm sai, cũng đã chịu khó đi google

Riêng về bài này thì mình thấy bạn nên kiếm mấy khóa học cơ bản về php, rồi thực hành, học 1 khóa không hiểu thì 10 khóa, bao giờ rõ thì thôi.
Đủ chất thì mới chuyển thành lượng được.

8 Likes
83% thành viên diễn đàn không hỏi bài tập, còn bạn thì sao?