Hello and welcome to our community! Is this your first visit?
Register
Enjoy an ad free experience by logging in. Not a member yet? Register.
Results 1 to 8 of 8
  1. #1
    New Coder
    Join Date
    Jul 2009
    Posts
    39
    Thanks
    12
    Thanked 0 Times in 0 Posts

    Making a Table in JavaScript

    I am currently in an internship where my main goal is to construct a database that can be run client-side (in JS). I have it done it PHP and am having a very hard time switching it to javascript.

    Rows = all info on one client
    Columns = Specific information (name, date, etc)

    Up until last monday i had never programmed PHP HTML or JavaScript so any help at all would be greatly appreciated.

    This is the PHP function that creates a table (and works well)
    ($data = 2D array of client information; $numRows = number of rows; $columns = array of column headers)

    Code:
         function printJSTable()
          {
            echo '<script language="Javascript" src = "java_script.js"></script>';
            echo '<table id = "myTable" class = "halloween" border = "1">';
            echo '<tr>';
            foreach($this->columns as $header => $order)
            {
                    echo '<th>';
                    echo $header;
                    echo '</th>';
            }
            echo '</tr>';
            $counter = 0;
            for($i = 0; $i < $this->numRows; $i++)
            {
                    echo '<tr >';
                    foreach($this->data[$i] as $key => $value)
                    {
                            echo '<td id ="'.$counter.'" onmouseover = "ParaOver(this)" onmouseout = "ParaOut(this)" onclick = "changeInfo(id)">';
                            if($value!="")
                                    echo $value;
                            else
                            {
                                    echo '<input type = "button" value = "Empty" size = 10>';
                            }
                            $counter++;
                            echo '</td>';
    
                    }
                    echo '</tr>';
            }
            echo '</table>';
          }
    any help at all would be great!! thanks!

  • #2
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,516
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    I'm sorry, but this statement just doesn't make sense:
    [quote]my main goal is to construct a database that can be run client-side (in JS).[/code]

    Client-side JavaScript is incapable of connecting to a database. You *must* do that on the server.

    If you didn't really mean a true database--if you just meant a text file containing data--then JavaScript is *still* incapable of that. JavaScript is NOT allowed to write files to the user's computer and JS has no possible way of writing files on the server.

    So I think maybe you have the wrong end of the stick here.

    Yes, I read your other post. No clearer than this one, to me at least.

  • #3
    New Coder
    Join Date
    Jul 2009
    Posts
    39
    Thanks
    12
    Thanked 0 Times in 0 Posts
    Thats my bad your totally correct. What i meant to say it that I want to print the Table client side so that the client can manipulate, order, add and delete rows, without corresponding with the server.

    The actual database will be server side, yes. I just meant the Table which is a representation of the database.

    Thanks for pointing out that error

  • #4
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,346
    Thanks
    11
    Thanked 589 Times in 570 Posts
    i would investigate jQuery grid plugins.
    if you aren't opposed to jQuery, many almost cut-and-paste tools exist.

    also,
    simply setting the table's contentEditable attrib to true will let you navigate the table much easier while allowing client-side edits to cell values...
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%

  • #5
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,516
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts

    Okay...NOT a PHP programmer!!

    So pardon me if I make PHP typos.

    But I think you could do it something like this:
    Code:
    <?php
    function printJSArray()
    {
        $collist = "";
        $fldlist = "";
        foreach($this->columns as $header => $order)
        {
            $collist .= ",_" . $header;
            $fldlist .= "    this." . $header . "=_" . $header . ";\n";
        }
        $collist = substr($collist,1); // chop off leading comma
    ?>
    <script type="text/Javascript" src="java_script.js"></script>
    <script type="text/JavaScript">
    function RowInfo(<?= $collist ?>)
    {
        <?=$fldlist?>
    }
    
    var Rows = new Array(
    <?php
        for($i = 0; $i < $this->numRows; $i++)
        {
            $datalist = "";
            foreach($this->data[$i] as $key => $value)
            {
                $datalist .= "," . "'" . $value . "'";
            }
            echo "    new RowInfo(" . substr($datalist,1) . "),\n";
        }
    ?>
        null );
    </script>
    <?php
    }
    ?>
    The function RowInfo( ) is a *constructor* for a JavaScript object. And we generate the constructor from the field names, just as your <table> code dumped them out as <th>'s.

    Then, as we iterate through all the records, we invoke the constructor once per record to create a JS object.

    So let's say you have a SQL query such as "SELECT foo, bar, zam FROM table".

    Then *IF* I created that code correctly (and, if not, you should be able to fix the minor typos?), the output to the browser would look like this:
    Code:
    <script type="text/JavaScript">
    function RowInfo(_foo,_bar,_zam)
    {
        this.foo = _foo;
        this.bar = _bar;
        this.zam = _zam;
    }
    
    var Rows = new Array(
        new RowInfo('1','joe','eat at my place'),
        new RowInfo('2','bob','bob for apples'),
        null );
    </script>
    I didn't bother to clean up the last comma in the Rows array, opting to just give it a last null element. So when you iterate through the array, stop before the last element. Or stop when you get the null.

    So now you can use the data in that array of objects to contruct a <table> in JS. And, of course, you can sort the rows any which way, remove a row, etc.

    Note that my code assumes you won't have any apostrophes in the data. If you might, then just do a replace to convert each apostrophe to \' and JS will be happy.

    Oh...and the modern way to declare a JS block is shown there. The "language=JavaScript" attribute is obsolete and should be avoided.

    Again, not a PHP person, so good luck with it.

  • #6
    New Coder
    Join Date
    Jul 2009
    Posts
    39
    Thanks
    12
    Thanked 0 Times in 0 Posts
    just like to start by saying thnk u so much, this was very helpful. One question tho, is how do i actually *print* the table. I see that this function builds a JS 2D array, i believe. but how do u print the actual table?

    is there any JS command like <table><tr><td></td></tr></table> that i can create cells with?

    and thanks, im used to C++ and Java so these super flexible languages r definitely trippin me out. fun tho

  • #7
    Supreme Master coder! Old Pedant's Avatar
    Join Date
    Feb 2009
    Posts
    25,516
    Thanks
    77
    Thanked 4,381 Times in 4,346 Posts
    The *right* way to create a <table> in JS code is to use document.createElement("TABLE") and then to use methods on the resulting table object to add rows and, within rows, cells.

    However, most browsers will let you get away with creating the table as HTML text and then setting the .innerHTML property of some <div> that that HTML text.

    A demo of both techniques:
    Code:
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml" dir="ltr" lang="en">
    <head>
    <style type="text/css">
    #first table { table-collapse: collapse; }
    #first table td { border: solid blue 1px; padding: 5px; }
    
    #second table { table-collapse: collapse; }
    #second table td { border: solid red 1px; background-color: wheat; padding: 5px; }
    
    </style>
    
    <script type="text/javascript">
    function makeTableRightWay(where)
    {
        var tbl = document.createElement("TABLE");
        var tbody = document.createElement("TBODY");
        tbl.appendChild(tbody);
        where.appendChild( tbl );
        for ( var rn = 1; rn <= 3; ++rn )
        {
            var tr = document.createElement("TR");
            for ( var cn = 1; cn <= 4; ++cn )
            {
                var td = document.createElement("TD");
                td.innerHTML = "row " + rn + ", cell " + cn;
                tr.appendChild(td);
            }
            tbody.appendChild(tr);
        }
    }
    
    function makeTableViaInnerHTML(where)
    {
        var html = "<table>";
        for ( var rn = 1; rn <= 3; ++rn )
        {
            html += "<tr>";
            for ( var cn = 1; cn <= 4; ++cn )
            {
                html += "<td>" + "row " + rn + ", cell " + cn + "</td>";
            }
            html += "</tr>";
        }
        html += "</table>";
        where.innerHTML = html;
    }    
    </script>
    </head>
    <body>
    <div id="first" style="background-color: yellow;"></div>
    <div id="second" style="background-color: green;"></div>
    
    <form>
    <input type=button value="Add table to first div" onclick="makeTableRightWay(document.getElementById('first'));">
    <input type=button value="Add table to second div" onclick="makeTableViaInnerHTML(document.getElementById('second'));">
    </form>
    
    </body>
    </html>

  • Users who have thanked Old Pedant for this post:

    JustinC474 (07-27-2009)

  • #8
    Senior Coder rnd me's Avatar
    Join Date
    Jun 2007
    Location
    Urbana
    Posts
    4,346
    Thanks
    11
    Thanked 589 Times in 570 Posts
    Quote Originally Posted by JustinC474 View Post
    just like to start by saying thnk u so much, this was very helpful. One question tho, is how do i actually *print* the table. I see that this function builds a JS 2D array, i believe. but how do u print the actual table?

    is there any JS command like <table><tr><td></td></tr></table> that i can create cells with?
    I have a small Grid function that correctly builds tables from an array of objects.
    you can re-sort the colums by clicking the header, and sorts are type-aware.

    Grid
    Arguments: Array of Objects
    Returns : DOMTable

    i would throw the Grid function into an external script, i thought i had it hosted, but apparently not...

    anyway, all you need to do is print a function name before printing the json_encode function, the callback to send the data to.
    you can see how delicious does it for ref.


    (tested FF3.5, IE7)
    Code:
    <html><body>
    
    <script type='text/javascript' src='http://danml.com/mini'></script>
    	
    <script type='text/javascript'>
    
    function Grid(ob){var dc=dom.create;var t=dc("table");var thr=dc("tr");var tfr=dc("tr");var trs=dc("tbody");var LUTrow=obVals(ob[0]);var columns=obKeys(ob[0]);function buildCap(a,slot){var th=dc("th",a);th.slot=slot;th.onclick=function(){t.redraw(th.slot);};this.appendChild(th);}
    columns.map(buildCap,thr);columns.map(buildCap,tfr);t.appendChild(dc("thead",thr));t.appendChild(trs);t.appendChild(dc("tfoot",tfr));t.redraw=function(sortCol){var tt=tags(trs,"tr");if(tt&&tt.length){tt.map(dom.kill);}var ob2=Sort(ob.concat(),sortCol);ob2.map(function(a,b){var newRow=dc("tr");obVals(a).map(function(cellData){var d=dc("td",String(cellData));newRow.appendChild(d);});trs.appendChild(newRow);});};t.redraw(0);return t;function Sort(r,sortCol){var that=columns[sortCol];if(!Sort.flips){Sort.flips=[];}if(!Sort.flips[sortCol]){Sort.flips[sortCol]=-1;}Sort.flips[sortCol]*=-1;var sortFn={string:sortText,object:sortDate,number:sortNumber}[typeof r[0][that]];return Sort.flips[sortCol]<0?r.sort(sortFn).reverse():r.sort(sortFn);function sortText(a,b){return a[that]!=b[that]?b[that].toLowerCase()<a[that].toLowerCase()?1:-1:0;}
    function sortNumber(a,b){return a[that]!=b[that]?parseFloat(a[that])-parseFloat(b[that]):0;}
    function sortMoney(a,b){return a[that]!=b[that]?parseFloat(a[that].replace(/[^\d.]/g,""))-parseFloat(b[that].replace(/[^\d.]/g,"")):0;}
    function sortDate(a,b){return a[that]<b[that]?-1:a[that]>b[that]?1:0;}}}
    
    function parseRFC(s){s=s.replace(/-/g," ").replace("T"," ").slice(0,-1);r=s.split(" ");var y=r[0];r[0]=r[2]+"/";r[2]="/"+y;return new Date(r.join(" ")+" GMT");}
    
    
    // custom code:
    function gridCB(data){
    	var myData=data.pluck([ "n","d","dt"]).map(//choose fields
    		function(it){it.dt=parseRFC(it.dt);return it;});	//fix dates
    	document.body.appendChild(Grid(myData));
    }
    window.onload=function(){
    	jsGet("http://feeds.delicious.com/feeds/json/rndme/bundle:js?count=90&callback=gridCB");
    }
    </script>	
    </body>
    </html>

    if your data are clean, you simply need to call it like:
    Code:
    function gridCB(data){
    	document.body.appendChild(Grid(data));
    }
    EDIT:
    hmm, your'e not the one i sold php's json_encode() to, my bad. I'll keep the post up anyways.
    check out php's json_encode: it's lightning fast, and you can ignore aposes and quotes.
    with json_encode, and Grid, you can go from mySQL to a sortable table in about 3 lines of custom code...
    Last edited by rnd me; 07-28-2009 at 12:08 AM.
    my site (updated 13/9/26)
    BROWSER STATS [% share] (2014/5/28) IE7:0.1, IE8:5.3, IE11:8.4, IE9:3.2, IE10:3.2, FF:18.2, CH:46, SF:7.9, NON-MOUSE:32%


  •  

    Posting Permissions

    • You may not post new threads
    • You may not post replies
    • You may not post attachments
    • You may not edit your posts
    •