user3324415 user3324415 - 5 months ago 10
HTML Question

Fill HTML <table> dynamically based on xmlhttp.responseText

Currently I have a JavaScript function which has been serving me well when I know the number of results that will be returned from my PHP side (I prepare my HTML tables before, knowing that only one line would be returned as an example), as follows:

<script>
function findInfo(str1, str2) {

var searchOne (str1.value);
var searchTwo = (str2.value);

if (searchOne.length === 0 || searchTwo.length === 0) {
document.getElementById("existingTableCell").innerHTML = "Missing mandatory field(s)!";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
var splitResponse = xmlhttp.responseText.split(":",5);
var firstCell = splitResponse[0];
var secondCell = splitResponse[1];
var thirdCell = splitResponse[2];
var fourthCell = splitResponse[3];
var fifthCell = splitResponse[4];

document.getElementById("cellID1").innerHTML = firstCell;
document.getElementById("cellID2").innerHTML = secondCell;
document.getElementById("cellID3").innerHTML = thirdCell;
document.getElementById("cellID4").innerHTML = fourthCell;
document.getElementById("cellID5").innerHTML = fifthCell;

}
};

xmlhttp.open("GET", "myPHPLogic.php?varA="+ searchOne + "&varB=" + searchTwo, true);
xmlhttp.send();
}
}
</script>


But now seeing as though the MSSQL query that get's run on the PHP side could have an indeterminate number of rows return I don't see how I can keep using this xmlhttp.responseText.split method and pre created tables?

Not sure what would be the best method to handle this requirement? Do I build the new rows in the JavaScript function as I try and work through the xmlhttp.responseText?

UPDATE I just cannot wrap my head around this syntax and logic, I have tried for hours now :(

<script>
function findInfo(str1, str2) {

var searchOne (str1.value);
var searchTwo = (str2.value);

if (searchOne.length === 0 || searchTwo.length === 0) {
document.getElementById("existingTableCell").innerHTML = "Missing mandatory field(s)!";
return;
} else {
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function ()
{
if (xmlhttp.readyState === 4 && xmlhttp.status === 200)
{
/*
I HAVE A MSSQL RESPONSE COMING BACK FROM THE PHP THAT WOULD LOOK AS FOLLOWS:
Value: Value2: Value3: Value4: ETC: ETC:
*/

var responseSplit = xmlhttp.responseText.split(":");
//Value, Value2, Value3, Value4, ETC, ETC,

/*
I have a table that looks as follows:
Column 1 Column 2 Column 3

I want to insert //Value, Value2, Value3, Value4, ETC, ETC, all in their own cell in column 1..
*/

var arrayLength = responseSplit.length;
for (var i = 0; i < arrayLength; i++) {
$(tableOne).find(tableOneBody).find(tableOneTableRow1).append("<td>"+responseSplit[i]+"</td>");
}
};

xmlhttp.open("GET", "myPHPLogic.php?varA="+ searchOne + "&varB=" + searchTwo, true);
xmlhttp.send();
}
}
</script>

Answer

I had to make many changes to solve this problem, I will briefly try and provide a useful answer:

  1. I removed all data from my HTML tables, all that is left is:
    <div class="section">
   <div class="container">
      <div class="row">
         <div class="col-md-12">
            <table class="table" id="tableOne">
               <thead>
                  <tr>
                     <th>Column One</th>
                     <th>Column Two</th>
                     <th>Column Three</th>
                  </tr>
               </thead>
               <tbody>
               </tbody>
            </table>
         </div>
      </div>
   </div>
</div>
<div class="section">
   <div class="container">
      <div class="row">
         <div class="col-md-12">
            <table class="table" id="tableTwo">
               <thead>
                  <tr>
                     <th>Column One</th>
                     <th>Column Two</th>
                  </tr>
               </thead>
               <tbody>
               </tbody>
            </table>
         </div>
      </div>
   </div>
</div>
  1. My JavaScript function was modified as follows:

    <script>
        function findInformation(str1, str2) {
    
            var inputBoxOne = (str1.value);
            var inputBoxTwo = (str2.value);
    
            if (inputBoxOne.length === 0 || inputBoxTwo.length === 0) {
                alert("Missing mandatory field(s)!");
                return;
                } else {
    
                    //TABLE ONE LOGIC
                    var xmlhttpOne = new XMLHttpRequest();
                    xmlhttpOne.onreadystatechange = function ()
    
                    {
                        if (xmlhttpOne.readyState === 4 && xmlhttpOne.status === 200)
    
                        {
                            var thetableBodyPart1 = xmlhttpOne.responseText;                                                                
                            $(tableOne).append(thetableBodyPart1);                                                               
                        }
                    };
    
                    //PHP 1 (findInformation.php)
                    xmlhttpOne.open("GET", "findInformation.php?q=" + inputBoxOne + "&w=" + inputBoxTwo, true);
                    xmlhttpOne.send();
    
                    //TABLE TWO LOGIC
                    var xmlhttpTwo = new XMLHttpRequest();
                    xmlhttpTwo.onreadystatechange = function ()
    
                    {
                        if (xmlhttpTwo.readyState === 4 && xmlhttpTwo.status === 200)
    
                        {                                                           
                            var thetableBodyPart2 = xmlhttpTwo.responseText;                                                                
                            $(tableTwo).append(thetableBodyPart2);                                
                        }
                    };                        
    
                    //PHP 2 (findInformation2.php)
                    xmlhttpTwo.open("GET", "findInformation2.php?e=" + inputBoxOne + "&r=" + inputBoxTwo, true);
                    xmlhttpTwo.send();                   
                }
            }        
    

3a. PHP Logic handles adding table data as follows, for Table One:

<?php

$q = $_REQUEST["q"];
$w = $_REQUEST["w"];

if ($q !== "" && $w !== "") {

//MSSQL SERVER CONNECTION
$serverName = "127.0.0.1\INSTANCENAME,PORTNUMBER"; //serverName\instanceName
$connectionInfo = array("Database" => "DBNAME", "UID" => "USERNAME", "PWD" => "PASSWORD");
$conn = sqlsrv_connect($serverName, $connectionInfo);

if ($conn) {
    //echo "Connection established.<br />";
} else {
    echo "Connection could not be established.<br />";
    die(print_r(sqlsrv_errors(), true));
}


    $queryForTable1 =               "SELECT THINGONE, THINGTWO, THINGTHREE
                                     FROM TABLE                                     
                                     WHERE SOMETHING = $q   
                                     AND SOMETHINGELSE = $w;";

    $stmtForTable1 = sqlsrv_query($conn, $queryForTable1);

            while ($row = sqlsrv_fetch_array($stmtForTable1, SQLSRV_FETCH_ASSOC)) {
                echo'<tr>'; 
                echo'<td>'. $row['THINGONE']."</td>";
                echo'<td>'. $row['THINGTWO'].'</td>';
                echo'<td>'. $row['THINGTHREE'].'</td>';
                echo'<tr>';
            }
}

else {

    echo "Missing data input!";

}

3b. PHP Logic handles adding table data as follows, for Table Two:

<?php

$e = $_REQUEST["e"];
$r = $_REQUEST["r"];

if ($e !== "" && $r !== "") {

//MSSQL SERVER CONNECTION
$serverName = "127.0.0.1\INSTANCENAME,PORTNUMBER"; //serverName\instanceName
$connectionInfo = array("Database" => "DBNAME", "UID" => "USERNAME", "PWD" => "PASSWORD");
$conn = sqlsrv_connect($serverName, $connectionInfo);

if ($conn) {
    //echo "Connection established.<br />";
} else {
    echo "Connection could not be established.<br />";
    die(print_r(sqlsrv_errors(), true));
}


    $queryForTable2 =               "SELECT THINGFOUR, THINGFIVE
                                     FROM TABLE                                     
                                     WHERE SOMETHING = $e   
                                     AND SOMETHINGELSE = $r;";

    $stmtForTable2 = sqlsrv_query($conn, $queryForTable2);

            while ($row2 = sqlsrv_fetch_array($stmtForTable2, SQLSRV_FETCH_ASSOC)) {
                echo'<tr>'; 
                echo'<td>'. $row2['THINGFOUR']."</td>";
                echo'<td>'. $row2['THINGFIVE'].'</td>';
                echo'<tr>';
            }
}

else {

    echo "Missing data input!";

}

I really hope this helps someone in future!

Comments