Tywele
Tywele

Reputation: 485

Variable sent with AJAX is undefined in PHP

I'm trying to send a variable from Javascript to PHP using AJAX.

The 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>

The Javascript which is sending the AJAX request with jQuery (functions.js):

$(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");
      }
    });
  });
});

The PHP file (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>

The HTML displays data from a database in a table and each row has a button next to it. With jQuery I get the id of the row where the button has been clicked. I want to send this id to my php file to do some stuff there (irrelevant for now). The problem I'm having is that I can't access the send variable (fileID) in my edit.php file.

The alert in the success part of the AJAX call gets executed. What do I need to fix? I thought I had everything right.

I also tried to change the url of the AJAX call to ../edit.php but that didn't work either. Then the success part wouldn't be executed.

And different variable names didn't work either.

The project structure is as follows:

(*) directories

Edit:

The error message: Notice: Undefined variable: fileID in C:\xampp\htdocs\kuhlnotesweb\edit.php on line 10

Upvotes: 2

Views: 1180

Answers (3)

Tywele
Tywele

Reputation: 485

This is my solution now:

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>

I think there were many misunderstanding in what I was trying to achieve and how I was not able to understand how AJAX works exactly. edit.php is only a small part of HTML that gets included in index.php and the AJAX call I'm making gets made in the same file, so I was not able to use the variable I sent via AJAX in my edit.php file because at the point where I wanted to use it it wasn't even sent and thus the $_POST['fileID'] was undefined. My solution to this was that I created a seperate php file (ajax-edit.php) where I retrieve the information I need from the database and return it as a JSON object. With this I am able to use the information from the JSON object to change the value of the input fields.

Thank you for the help everybody and I am sorry that I was so stubborn ^^.

Upvotes: 0

mdamia
mdamia

Reputation: 4557

The problem is a syntax error in your js when you try to pass data your code. see js fiddle example http://jsfiddle.net/mdamia/njd8m0g5/4/. how to get the value from the tr.

  data: ({ fileID : fileID }), 

should be data:

 { fileID : fileID } // no ()

Tested and it works.

from jQuery AJAX

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

Upvotes: 0

MarshallOfSound
MarshallOfSound

Reputation: 2719

AJAX returns the content of the page in the data success variable. Trying console.log(data) and you should see you variable has been echoing into the returned HTML.

If not, check in the dev tools that the fileID parameter is actually attached to the request.

UPDATE

<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>

Upvotes: 2

Related Questions