0

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>
Barmar
  • 741,623
  • 53
  • 500
  • 612
BernardV
  • 640
  • 10
  • 28
  • Yes, that's exactly what you do. First split the response on newline characters, and loop over that. Create a row from that line, and append it to the table. – Barmar Jun 04 '16 at 09:49
  • See http://stackoverflow.com/questions/18333427/how-to-insert-row-in-html-table-body-in-javascript for how to add a row to a table. – Barmar Jun 04 '16 at 09:52
  • Thanks Barmar I will attempt it this way and report back.. – BernardV Jun 04 '16 at 12:42
  • @Barmar I just can't get this right.. – BernardV Jun 05 '16 at 11:23
  • Did you copy it correctly? The braces aren't balanced, and the calls to `xmlhttp.open()` and `xmlhttp.send()` are inside the `onreadystatechange` callback function. – Barmar Jun 05 '16 at 16:31
  • If you're using jQuery, why not use `$.ajax()` instead of the verbose `XMLHttpRequest` syntax? – Barmar Jun 05 '16 at 16:32
  • @Barmar thank you for you assistance, I have found a solution to my problem. I will put it within the "answer your own question" section. – BernardV Jun 06 '16 at 09:18

1 Answers1

0

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!

BernardV
  • 640
  • 10
  • 28