【问题标题】:Variable sent with AJAX is undefined in PHP使用 AJAX 发送的变量在 PHP 中未定义
【发布时间】:2015-11-19 07:29:04
【问题描述】:

我正在尝试使用 AJAX 将变量从 Javascript 发送到 PHP。

HTML (index.html):

  <div class="table-popup">
    <ul>
      <li id="edit-toggle">Bearbeiten</li>
      <li>Zu Favoriten hinzufügen</li>
      <li>Datei öffnen</li>
      <li>Im Ordner öffnen</li>
      <li>Löschen</li>
    </ul>
  </div>

  <div class="main-content">
    <h2 class="main-content-header">Datenbank</h2>
    <div id="table">
      <table>
        <thead>
          <tr class="table-row" tabindex="1">
            <th class="fixed-header"></th>
            <th>Dateiname</th>
            <th>Benutzer</th>
            <th>Erstelldatum</th>
            <th>Änderungsdatum</th>
            <th>Erste Zeile</th>
            <th>Kategorie</th>
            <th>Projekt</th>
          </tr>
        </thead>
        <?php
        include_once('connect.php');
        $result = $connect->query("SELECT file.name AS 'filename', file.description AS 'filedescription', category.name AS 'categoryname', project.name AS 'projectname', user.name AS 'username', idFile
          FROM file, category, project, file_has_project, file_has_category, user, user_has_project, user_has_category
          WHERE file.idFile = file_has_project.file_idFile AND file_has_project.project_idProject = project.idProject AND file.idFile = file_has_category.file_idFile AND file_has_category.category_idCategory = category.idCategory AND user.idUser = user_has_project.user_idUser AND user_has_project.project_idProject = project.idProject AND user.idUser = user_has_category.user_idUser AND user_has_category.category_idCategory = category.idCategory AND user.idUser = '".$_SESSION['userid']."'");
          //echo "<tbody><td>".$result->num_rows."</td></tbody>";
        if ($result->num_rows > 0) {
          echo "<tbody>";
          while($row = $result->fetch_assoc()) {
            echo "<tr class='table-row' tabindex='1' id='".$row['idFile']."'>";
            echo "<th class='table-edit-button fixed-header'><img src='images/open.gif' /></th>";
            echo "<td>".$row['filename']."</td>";
            echo "<td>".$row['username']."</td>";
            echo "<td>-</td>";
            echo "<td>-</td>";
            echo "<td>".$row['filedescription']."</td>";
            echo "<td>".$row['categoryname']."</td>";
            echo "<td>".$row['projectname']."</td>";
            echo "</tr>";
          }
          echo "</tbody>";
        }
        ?>
      </table>
    </div>
  </div>

使用 jQuery (functions.js) 发送 AJAX 请求的 Javascript:

$(document).ready(function() {
  var fileID;
  $('.table-edit-button').click(function() {
    fileID = $(this).parent().attr('id');
  });
  $('#edit-toggle').click(function() {
    $.ajax({
      url: 'edit.php',
      type: 'post',
      data: { fileID : fileID },
      success: function(data) {
        alert("Success");
      }
    });
  });
});

PHP 文件(edit.php):

<?php
if (isset($_POST['fileID']))
 $fileID = $_POST['fileID'];
?>

<div class="edit-content">
  <h2 class="edit-content-header">Bearbeiten<img src="images/cross.gif" /></h2>
  <div>
    <form action="" method="post">
      <?php echo $fileID; ?>
      <input type="text" placeholder="Dateiname"/>
      <input type="text" placeholder="Benutzer"/>
      <textarea placeholder="Erste Zeile" rows="7em" cols="100"></textarea>
      <select name="Kategorie">
        <option disabled selected>Kategorie</option>
        <?php
          include_once('connect.php');
          $result = $connect->query("SELECT name FROM category");
          if($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
              echo "<option value='".$row['name']."'>".$row['name']."</option>";
            }
          }
        ?>
      </select>
      <select name="Projekt">
        <option disabled selected>Projekt</option>
        <?php
          $result = $connect->query("SELECT name FROM project");
          if($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
              echo "<option value='".$row['name']."'>".$row['name']."</option>";
            }
          }
        ?>
      </select>

      <img id="savebtn" src="images/save.gif" />
    </form>
  </div>
</div>

HTML 在表格中显示来自数据库的数据,并且每一行旁边都有一个按钮。使用 jQuery,我可以获得单击按钮的行的 ID。我想将此 id 发送到我的 php 文件以在那里做一些事情(现在无关紧要)。 我遇到的问题是我无法访问 edit.php 文件中的发送变量 (fileID)。

AJAX 调用成功部分的alert 被执行。 我需要解决什么问题?我以为我做的一切都是对的。

我还尝试将 AJAX 调用的 url 更改为 ../edit.php,但这也不起作用。那么成功的部分就不会被执行了。

而且不同的变量名也不起作用。

项目结构如下:

  • 项目 (*)
    • edit.php
    • index.php
    • 脚本 (*)
      • functions.js

(*) 目录

编辑:

错误信息:注意:未定义变量:第 10 行 C:\xampp\htdocs\kuhlnotesweb\edit.php 中的 fileID

【问题讨论】:

  • 你看过浏览器控制台中的请求/响应吗?
  • 控制台没有给出任何错误。
  • 你的数据对象被括在括号中,它不应该是
  • 没有它们它仍然无法工作(它现在只有花括号)
  • 刚刚更新了我的答案,尝试使用该代码,错误应该会消失

标签: javascript php jquery ajax


【解决方案1】:

这是我现在的解决方案:

functions.js:

$(document).ready(function() {
  var fileID, fileName, fileDescription, fileCategory, fileProject;
  $('.table-edit-button').click(function() {
    fileID = $(this).parent().attr('id');
  });

  $('#edit-toggle').click(function() {
    $.ajax({
      url: 'ajax-edit.php',
      type: 'post',
      data: { fileID : fileID },
      dataType: 'json',
      success: function(data) {
        fileName = data.filename;
        fileDescription = data.filedescription;
        fileCategory = data.categoryname;
        fileProject = data.projectname;
        $('#edit-fileid').val(fileID);
        $('#edit-filename').val(fileName);
        $('#edit-description').val(fileDescription);
        $('#edit-projectname').val(fileProject);
        $('#edit-categoryname').val(fileCategory);
      }
    });
  });
});

ajax-edit.php:

<?php
if (isset($_POST['fileID'])) $fileID = $_POST['fileID'];

include_once('connect.php');
$result = $connect->query("SELECT file.name AS 'filename', file.description AS 'filedescription', project.name AS 'projectname', category.name AS 'categoryname'
  FROM file, project, category, file_has_project, file_has_category
  WHERE file.idFile = file_has_project.file_idFile AND file_has_project.project_idProject = project.idProject AND file.idFile = file_has_category.file_idFile AND file_has_category.category_idCategory = category.idCategory AND file.idFile = '".$fileID."'");
$result = $result->fetch_assoc();

echo json_encode($result);
 ?>

edit.php:

<div class="edit-content">
  <h2 class="edit-content-header">Bearbeiten<img src="images/cross.gif" /></h2>
  <div>
    <form action="edit.php" method="post">
      <input type="hidden" id="edit-fileid" name="edit-fileid"/>
      <input type="text" id="edit-filename" name="edit-filename" placeholder="Dateiname"/>
      <input type="text" id="edit-username" name="edit-username" placeholder="Benutzer"/>
      <textarea id="edit-description" name="edit-description" placeholder="Erste Zeile" rows="7em" cols="100"></textarea>
      <select id="edit-categoryname" name="edit-categoryname">
        <option disabled selected value="category-first">Kategorie</option>
        <?php
          include_once('connect.php');
          $result = $connect->query("SELECT category.name FROM category,user,user_has_category WHERE user.idUser = user_has_category.user_idUser AND user_has_category.category_idCategory = category.idCategory AND user.idUser = '".$_SESSION['userid']."'");
          if($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
              echo "<option value='".$row['name']."'>".$row['name']."</option>";
            }
          }
        ?>
      </select>
      <select id="edit-projectname" name="edit-projectname">
        <option disabled selected value="project-first">Projekt</option>
        <?php
          $result = $connect->query("SELECT project.name FROM project,user,user_has_project WHERE user.idUser = user_has_project.user_idUser AND user_has_project.project_idProject = project.idProject AND user.idUser = '".$_SESSION['userid']."'");
          if($result->num_rows > 0) {
            while($row = $result->fetch_assoc()) {
              echo "<option value='".$row['name']."'>".$row['name']."</option>";
            }
          }
        ?>
      </select>

      <input type="image" name="submit-button" id="savebtn" src="images/save.gif" />
    </form>
  </div>
</div>

我认为在我试图实现的目标以及我无法理解 AJAX 的工作原理方面存在很多误解。 edit.php 只是包含在 index.php 中的 HTML 的一小部分,而我正在进行的 AJAX 调用是在同一个文件中进行的,因此我无法在我的 edit.php 中使用通过 AJAX 发送的变量文件,因为在我想使用它的时候它甚至没有被发送,因此 $_POST['fileID'] 是未定义的。 我对此的解决方案是我创建了一个单独的 php 文件 (ajax-edit.php),我在其中从数据库中检索我需要的信息并将其作为 JSON 对象返回。有了这个,我可以使用来自 JSON 对象的信息来更改输入字段的值。

谢谢大家的帮助,很抱歉我这么固执^^。

【讨论】:

    【解决方案2】:

    问题是当您尝试传递数据时,您的 js 中的语法错误 你的代码。请参阅 js 小提琴示例 http://jsfiddle.net/mdamia/njd8m0g5/4/。如何从 tr 中获取值。

      data: ({ fileID : fileID }), 
    

    应该是数据:

     { fileID : fileID } // no ()
    

    经过测试,它可以工作。

    来自jQuery AJAX

    $.ajax({
      method: "POST",
      url: "some.php",
        data: { name: "John", location: "Boston" }
      })
      .done(function( msg ) {
        alert( "Data Saved: " + msg );
    });
    

    【讨论】:

    • 如果您尝试从浏览器访问edit.php会发生什么?
    • 我不太明白。如果我通过浏览器查看edit.php,它会按原样显示(?)(由于未定义PHP变量而出现错误消息。)
    • 当然,你的 edit.php 中有 $_POST['fileID'] 如果不发送 'fileID' 参数就无法访问它
    • 但我不是在functions.js中这样做了吗?
    • 为什么 OP 应该“试试这个”?一个好的答案总是会解释所做的事情以及这样做的原因,不仅适用于 OP,而且适用于 SO 的未来访问者。
    【解决方案3】:

    AJAX 在数据成功变量中返回页面内容。尝试 console.log(data) ,您应该会看到您的变量已回显到返回的 HTML 中。

    如果没有,请在开发工具中检查 fileID 参数是否实际附加到请求中。

    更新

    <div class="edit-content">
      <h2 class="edit-content-header">Bearbeiten<img src="images/cross.gif" /></h2>
      <div>
        <form action="" method="post">
          <?php
              if (isset($_POST['fileID'])) {
                   echo $_POST['fileID'];
              }
          ?>
          <input type="text" placeholder="Dateiname"/>
          <input type="text" placeholder="Benutzer"/>
          <textarea placeholder="Erste Zeile" rows="7em" cols="100"></textarea>
          <select name="Kategorie">
            <option disabled selected>Kategorie</option>
            <?php
              include_once('connect.php');
              $result = $connect->query("SELECT name FROM category");
              if($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                  echo "<option value='".$row['name']."'>".$row['name']."</option>";
                }
              }
            ?>
          </select>
          <select name="Projekt">
            <option disabled selected>Projekt</option>
            <?php
              $result = $connect->query("SELECT name FROM project");
              if($result->num_rows > 0) {
                while($row = $result->fetch_assoc()) {
                  echo "<option value='".$row['name']."'>".$row['name']."</option>";
                }
              }
            ?>
          </select>
    
          <img id="savebtn" src="images/save.gif" />
        </form>
      </div>
    </div>
    

    【讨论】:

    • 好的,我做到了,变量确实在数据变量中得到了回显。但我仍然在网站本身上收到错误消息。
    • 您的变量显示在返回的 HTML 内容中?
    • 是的。 没有足够的字符来发表评论
    • 我的本地文件上没有出现错误,你确定你复制我的代码正确吗? if (isset()) 应该处理未定义的问题
    猜你喜欢
    • 1970-01-01
    • 2015-09-30
    • 2017-11-18
    • 2021-03-20
    • 2011-10-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-11-01
    相关资源
    最近更新 更多