2

I am currently trying to populate a form with values fetched from mysql database. The form is very dynamic thanks to the help of jquery. Input fields can be added or deleted with a button click. For more background information in the structure of the form check my previous. I am running into difficulties in a way to populate this form with values from the database. I have foreach loop that fetches the values and places them in a JSON object. How can autopolulate the fields with these values? JSFIDDLE

Edit- I am aware there exists angular, ember, knockout and other js technologies for the job but for learning reasons I decided to this without the help of a commercial framework.

Form

    <script type='text/template' data-template='item'>

<ul class="clonedSection">
    <li style="list-style-type: none;">
        <label>
            <input class="main-item" data-bind = 'firstItem' type="checkbox" />First Item</label>
        <ul class="sub-item" data-bind ='subItem' style="display: none;">
            <li style="list-style-type: none;">
                <label>
                    <input type="checkbox" />Sub Item</label>
            </li>
        </ul>
    </li>
    <li style="list-style-type: none;">
        <label>
            <input class="main-item" data-bind ='secondItem' type="checkbox" />Second Item</label>
        <ul class="sub-item" style='display: none;' data-bind='detailsView'>
            <li style="list-style-type: none;">How many items:
                <select class="medium" data-bind ='numItems' required>
                    <option value="" selected>---Select---</option>
                    <option value="1">1</option>
                    <option value="2">2</option>
                </select>
            </li>
            <li style="list-style-type: none;">
                <div data-bind ='items'> 
                    Item # {number}
                    <select>
                        <option value='initial' selected='true' >--- Select ---</option>
                        <option value='Bananas'>Bananas</option>
                        <option value='Apples'>Apples</option>
                        <option value='Oranges'>Oranges</option>
                    </select>

                </div>
            </li>
        </ul>
    </li>
</ul>
    </script>

<input type='button' value='add' data-action='add' />
<input type='button' value='remove' data-action='remove' />

getItems.php

header("Content-type: application/json");
$db_select  = $db_con->prepare("SELECT
    p.firstItem,
    p.subItem,
    p.secondItem,
    p.itemNames,
    case itemNames when null then 0
    when '' then 0
    else
    (LENGTH(itemNames) - LENGTH(replace(itemNames, ',', '')) +1)
    end
    as numItems
    FROM items_list p
    ");

if (!$db_select) return false;
if (!$db_select->execute()) return false;
$results = $db_select->fetchAll(\PDO::FETCH_ASSOC);
// check that the 'id' matches up with a row in the databse
if(!empty($results))
  $responses = array();
  foreach ($results as $value){
    $responses[] = array(
      'firstItem' => ($value['firstItem'] == '1' ? true : false),
      'subItem' => ($value['subItem'] == '1' ? true : false),
      'secondItem' => ($value['secondItem'] == '1' ? true : false),
      'numItems' => $value['numItems'],
      'items' => array_map('trim', explode(',', $value['itemNames']))
      );
  }
echo json_encode($responses);
Community
  • 1
  • 1
  • Look into knockout.js. It's exceptional for allowing backend changes that automatically update DOM. – azurelogic Feb 25 '14 at 04:31
  • @RobRibeiro While I suggested checking Knockout (and other such FWs) myself in the comments and contents of my answer in the other question - generally it is considered somewhat inappropriate to suggest a framework for this sort of thing. Note OP already has (hand rolled) data binding. techAddict - I'll give other people a chance to provide a better answer from the PHP side (I'm not the best php programmer to say the least), if they don't I'll try to come up with an answer in a few days :) – Benjamin Gruenbaum Feb 25 '14 at 05:41
  • @BenjaminGruenbaum Alright, sounds great. Could you show me here what you meant by iterating through the values from the array N times, creating Thing objects with them, then iterating through those and calling addThing on each of them. –  Feb 25 '14 at 05:46
  • 1
    Agree with Rob. Don't try to reinvent the wheel. Take a look at knockout, angular, ember, or other MV* frameworks. This is code that should be in a framework and you should be more concerned in your business logic. – turtlepick Feb 26 '14 at 02:50
  • You can also use handlebars and bind the json data to the input value attribute. There's many ways to do this. – Christopher Marshall Feb 26 '14 at 17:23
  • I strongly recommend you to use angularjs. You must build your model, then draw your view, and use js to glue things. Binding info it´s just easy as specify data-ng-model="myObject.myProperty" as an attribute of your input. Every time you change the data, the model will be updated without a single request. I warn you about the fact that these frameworks are js based. So, if you are targeting potential customers that may not have js support, keep on eye on a possible workaround for them. Regards! – Guillermo Feb 26 '14 at 18:55
  • @ChristopherMarshall Awesome, could you show me in answer format. Thank you. –  Feb 26 '14 at 23:33
  • @techAddict82 Unfortunately, I'm leaving work right now, but check out the docs at http://handlebarsjs.com/ – Christopher Marshall Feb 26 '14 at 23:39

1 Answers1

0

You have to deliver your data - generated by the server - to your client.

2 popular ways I can recommend:

  • AJAX and JSON
  • SCRIPT element and JSONP

After that you have to parse the data and build the HTML DOM elements you need. This can be done with templates or with DOM functions. When the code grows, you have to create many js classes to do different parts of the job. You can use for example MVC or MVVM pattern as well...

After a long time you'll have your own client side framework, like angular, backbone, ember, etc... It does worth to use them I think, but it is your choice...

edit:

In this exact case you should use the jquery ajax function the get and unserialize your json from your php file. After that you have to write a parser for that json which can transform it to "thing" instances. In your case the easiest way to modify the addItem() function to accept a json parameter.

For example the modifications by a simple item array should be something like this:

function Thing(source) { //we use this as an object constructor.
    this.firstItem = false;
    this.subItem = false;
    this.secondItem = false;
    this.numItems = 0;
    this.items = []; // empty list of items
    if (source)
        this.merge(source);
}
Thing.prototype.merge = function (source){
    for (var property in source)
        if (source.hasOwnProperty(property))
            this[property] = source[property];
};
Thing.prototype.toJSON = function (source){
return ({
    firstItem: this.firstItem,
    subItem: this.subItem,
    secondItem: this.secondItem,
    numItems: this.numItems,
    items: this.items
}).toJSON();
};

function addItem(source) {
    var thing = new Thing(source); // get the data
    //...
}

function parseFormRepresentation(json){
    for (var i = 0, l=json.length; i<l; ++i)
        addItem(json[i]);
}

$.ajax({
    url: "getItems.php",
    success: function (data){
        parseFormRepresentation(data);
    }
});

Ofc this is not perfect, to parse tree you have to prepare your addItem() function to parse items with recursion. I guess you can do that yourself...

inf3rno
  • 24,976
  • 11
  • 115
  • 197
  • Thanks for the help, what do you mean by "parse tree you have to prepare your addItem() function to parse items with recursion"? –  Feb 27 '14 at 01:39
  • Here is an example: http://stackoverflow.com/questions/6655522/javascript-parse-tree – inf3rno Feb 27 '14 at 01:45
  • If any of your things can have sub-things, then this data structure is called tree. It is a little bit harder to parse a tree than an array, but you can learn it fast... – inf3rno Feb 27 '14 at 01:47