简体   繁体   中英

Populating input fields with values from JSON object

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);

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM