Search code examples
javascriptevent-handlingevent-delegation

How to use the data from the row selected?


How can I collect the data on the row from the table that I select and use it in the result?

Here is the javascript I am using to show the data entry screen, once the function has been called by selecting the row. Now I just need to design a form in PHP that will include (1) some of the data from the row selected and (2) some new data that will be collected.

Here is the Javascript to select the row and call the data entry form

$(document).ready(function () {
    $("tr").live('click',function(){
        $.post('data_entry_form.php', function(data) {
            $('#section2').html(data);
        });
    });
});

Here is the PHP Script

<?php
require_once "config.php";
$dbh = new PDO($dsn, $dbuser, $dbpass);
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

$result = $dbh->query("SELECT aif_id, fee_source_id, company_name_per_sedar, document_filing_date FROM a_aif ORDER BY aif_id DESC");
$result->setFetchMode(PDO::FETCH_ASSOC);

echo "<table id=\"all_aifs\">";
echo "<tr>";
echo "<th><b>Document ID</b></th>";
echo "<th><b>Pubco Name</b></th>";
echo "<th><b>Filing Date</b></th>";
echo "<th><b>PDF</b></th>";
echo "</tr>";

foreach($result as $index => $row) {
echo "<tr>";
echo "<td>$row[fee_source_id]</td>";
echo "<td>$row[company_name_per_sedar]</td>";
echo "<td>$row[document_filing_date]</td>";
echo "<td>Placeholder</td>";
echo "</tr>";
}

echo "</table>";
echo "<br>";
$dbh = NULL;
?>

Solution

  • The "Correct" answer to this problem is NOT to read from the DOM. Never a good idea. I suggest you pass the record id to the ajax call and have the ajax call return an already-populated form.

    //PHP
    //place the data attribute in the tr
    echo "<tr data-recordId='".$row['id']."'>";
    
    
    //JS
    $(document).ready(function () {
        $("tr").live('click',function(){
    
            //Get the ID from the row clicked
            var id = $(this).data('recordId'); 
    
            //short-hand
            $('#section2').load('data_entry_form.php?id='+id);
    
        });
    });
    

    Then your ajax page would just read $_REQUEST['id'] to get the id of the form being edited.

    //Ajax side PHP
    $id = (int)$_REQUEST['id'];
    //Fetch data and use it to pre-populate form item
    

    You would pre-populate your inputs like this

    <input type="text" value="<?php  echo $row['value']; ?>" />
    

    or

    echo '<input type="text" value="'.$row['value'].'" />';
    

    NOTE: If your values contain quotes, you will want to replace them with the code &quot;

    echo '<input type="text" value="'.str_replace('"', '&quot;', $row['value']).'" />';