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);
8
  • Look into knockout.js. It's exceptional for allowing backend changes that automatically update DOM. Commented Feb 25, 2014 at 4: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 :) Commented Feb 25, 2014 at 5: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. Commented Feb 25, 2014 at 5: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. Commented Feb 26, 2014 at 2:50
  • You can also use handlebars and bind the json data to the input value attribute. There's many ways to do this. Commented Feb 26, 2014 at 17:23

1 Answer 1

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...

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks for the help, what do you mean by "parse tree you have to prepare your addItem() function to parse items with recursion"?
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...

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.