2

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:

  • project (*)
    • edit.php
    • index.php
    • scripts (*)
      • functions.js

(*) directories

Edit:

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

Jay Blanchard
  • 34,243
  • 16
  • 77
  • 119
Tywele
  • 485
  • 1
  • 7
  • 21
  • 1
    Have you watched the request / response in the browser's console? – Jay Blanchard Aug 25 '15 at 14:23
  • The console doesn't give any errors. – Tywele Aug 25 '15 at 14:25
  • your data object is wrapped in brackets, it shouldn't be – Paul Osborne Aug 25 '15 at 14:26
  • Without them it's still not working (it now only has curly braces) – Tywele Aug 25 '15 at 14:29
  • Just updated my answer, try using that code and the error should go away – MarshallOfSound Aug 25 '15 at 14:50
  • Place `print_r($_POST);` at the top of the file to see if anything is getting set in the POST array. – Jay Blanchard Aug 25 '15 at 14:52
  • Are you sure `$row['idFile']` is set? – Jay Blanchard Aug 25 '15 at 14:55
  • Are you sure that `fileID` is set? You have to set that by clicking one button, then you click another for the AJAX call. Maybe the logic is a bit mixed up here? – Jay Blanchard Aug 25 '15 at 14:57
  • Yes `fileID` is set I'm sure of this. Tested it with alert. The first click is to bring up a popupmenu the second is selecting something from that menu. – Tywele Aug 25 '15 at 14:59
  • The problem is on the initial page load $fileID won't be set. You need to wrap it with an if (isset()) like in my answer below – MarshallOfSound Aug 25 '15 at 15:01
  • @Jay Blanchard: when I `console.log(data)` in the success part I see the value in the `$_POST` variable but not when it's displayed in the browser: http://i.imgur.com/QrqULvU.png – Tywele Aug 25 '15 at 15:01
  • @MarshallOfSound: But that's what I'm doing ... (at the beginning of edit.php) – Tywele Aug 25 '15 at 15:05
  • @Tywele check my updated answer, the error is how are you passing data – mdamia Aug 25 '15 at 15:06
  • You may be looking for the result in the wrong place. Are you loading the edit.php and expecting to see the variable populated? If so, that will not work. AJAX is sending data to and expecting to receive data from edit.php. You will see the populated variable in that receipt, not by navigating to the page. – Jay Blanchard Aug 25 '15 at 15:06
  • @mdamia: I already updated it like that in my question and also in my code and that wasn't the error. – Tywele Aug 25 '15 at 15:07
  • @Tywele, but you aren't.. You check if the post is there and if it is you set $fileID. If it isn't there you don't set it. But later on you try and echo $fileID whether it has been set or not and that is your problem – MarshallOfSound Aug 25 '15 at 15:08
  • @MarshallOfSound: Even if I do an isset check there it won't solve my problem. – Tywele Aug 25 '15 at 15:09
  • @Jay Blanchard: Thanks I think that is my problem. But how can I do what I'm trying to achieve then? Like this: http://stackoverflow.com/questions/15461786/pass-javascript-variable-to-php-via-ajax – Tywele Aug 25 '15 at 15:10
  • Look at my comment and @MarshallOfSound's answer. Your error is at Line 10 when you echo out the variable while visiting the page directly. If you have to check to see if the variable `isset()` there OR change your `isset()` so that `$fileID = ''` if `$_POST['fileID'] *is not set*. – Jay Blanchard Aug 25 '15 at 15:11
  • No one is listening to us @JayBlanchard :( – MarshallOfSound Aug 25 '15 at 15:14
  • I think I am being misunderstood. I want to do the same thing as in the link I posted in my previous comment. I want to send a javascript variable via AJAX to my edit.php and use it there. How do I do that? – Tywele Aug 25 '15 at 15:14
  • So I can do everything with `$_POST['fileID']` except using it in `echo`? – Tywele Aug 25 '15 at 15:18
  • Or can I not use it in `edit.php` at all? – Tywele Aug 25 '15 at 15:27

3 Answers3

2

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>
MarshallOfSound
  • 2,629
  • 1
  • 20
  • 26
0

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 );
});
mdamia
  • 4,447
  • 1
  • 24
  • 23
  • What happens if you try to access edit.php from the browser? – mdamia Aug 25 '15 at 14:34
  • I don't quite understand. If I view edit.php through the browser it gets displayed(?) just like it should (with the error message because of the PHP variable being not defined.) – Tywele Aug 25 '15 at 14:37
  • of course,you have $_POST['fileID'] in your edit.php you cannot access it without sending 'fileID' param – Spl2nky Aug 25 '15 at 14:37
  • 1
    But didn't I do that in `functions.js`? – Tywele Aug 25 '15 at 14:45
  • 1
    Why should the OP "try this"? A good answer will always have an explanation of what was done and why it was done that way, not only for the OP but for future visitors to SO. – Jay Blanchard Aug 25 '15 at 14:49
  • I have updated my answer. Tested the code and it works. that s the only thing you have to change, I was able to echo data back from server to the browser and it works – mdamia Aug 25 '15 at 14:59
  • @MarshallOfSound not the bracket but the parenthesis, they should not be there, updated post with example from jquery api – mdamia Aug 25 '15 at 15:09
  • If you want to call them parenthesis thats ok but ({a: 1}) == {a: 1}. The brackets don't effect the value – MarshallOfSound Aug 25 '15 at 15:13
  • This was only a *part* of the problem, the other part being how `$fileID` is being set on Line 10 when accessing the page directly in the browser. – Jay Blanchard Aug 25 '15 at 15:14
  • @MarshallOfSound we are not arguing the value of ({a: 1}) == {a: 1} here, the ajax syntax is wrong. – mdamia Aug 25 '15 at 15:37
0

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

Tywele
  • 485
  • 1
  • 7
  • 21