Using Knockout.js with PHP: Best Practices

I recently had a project that made me temporarily shift from my more native c#/ environment and use php on the backend instead. As by more and more developers these days I have become accustomed to doing just about everything in the front end with the JavaScript library Knockout. Of course knockout.js is completely compatible with php being that it is on the front end while php is on the back end, but in combining php with knockout there are a few things that I have found make the match just a bit smoother.

Use json_encode() to pass PHP arrays to knockout

function getOrders() {
include_once 'mysql_connect.php'; 
$email = $_SESSION['Email'];

$query = sprintf("SELECT * FROM `Order` WHERE `Email` = '%s' order by id desc",
		mysqli_real_escape_string($con, $email));
$result = mysqli_query($con, $query);
$data = array();
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC)){
  $data[] = $row;

return json_encode($data);//json_encode() is the key

Then on on the front-end:

$(document).ready(function () {
    //Pass JSON encoded data directly into javascript variable
    var data = <?php getOrders(); ?> ;
    var vm = new ViewModel(data);	

function ViewModel (data){
	self = this;
	self.Orders = ko.mapping.fromJS(data);

Use ko.toJS() to send data from your ViewModel to PHP

function ViewModel (){
    self = this;
    self.Order = {
		FirstName : ko.observable(),
		LastName : ko.observable(),
		URL : ko.observable(),	
		Comments : ko.observable()	
    self.CreateOrder = function() {
        //Here is where you convert the data to something php can swallow
        var data = ko.toJS({"Data":order});
            url: "CreateOrder.php",
            type: 'post',
            data: data,
            success: function (result) {

And then on the back end:

include_once 'mysql_connect.php'; 
//recieve raw data into php variable
$data = $_POST['Data'];

//extract each field from raw data
$email = $data['Email'];
$firstName = $data['FirstName'];
$lastName = $data['LastName'];
$comments = $data['Comments'];

How to Add Knockout Computed Observables With the Knockout Mapping Plugin

The knockout Mapping Plugin is a great way to save time, and write less code when creating view models in knockout. When I first started using knockout I was hesitant to use the mapping plugin because I was afraid that I would lose some control over the customization of my view model. But after staring at the documentation for a while, and then tinkering in jsFiddle, I found that it is possible to have full control over the model that the mapping plugin generates.

The following example demonstrates how to manually insert knockout computed observables into an observableArray that is generated with the Knockout Mapping Plugin.

Loading Select Drop Down Options using Ajax and Knockout.js

The following shows how to use the knockout options binding when loading the option values from the server with AJAX.

In the following HTML the select box requires 4 bindings. The options binding specifies which variable in the Knockout ViewModel is used to generate the options. The optionsText specifies the name of element in the options array of for the text each option. The optionsValue is the name of the element in the options array for each option value. Finally, the value binding sets which option is selected. IMPORTANT: If you are loading the value from the server make sure the value you are loading matches exactly the optionsValue elements.


        <th>Id</th><th>Security Level</th>
  <tbody data-bind="foreach: inspectors">
      <td><span data-bind="text: InspectorID" /> </td>
        <select data-bind="
          options: $root.inspectorLevels, 
          optionsText: 'Description', 
          optionsValue: 'InspectorLevelID', 
          value: InspectorLevelID">

Another important thing which seems to be only in the options binding is to set the $.ajax attribute “async” to false. If not, then the options may load after the values and thereby changing the observable values to the default option.

Javascript Knockout ViewModel:

    function Inspector(data) {
        this.InspectorID = ko.observable(data.InspectorID);
        this.InspectorLevelID = ko.observable(data.InspectorLevelID);

    function InspectorListViewModel() {
        var self = this;
        self.inspectors = ko.observableArray([]);
        self.inspectorLevels = ko.observableArray([]);
            type: "post",
            contentType: "application/json",
            success:function (data) {
                var array = [];
                $.each(data, function (index, value) {
    ko.applyBindings(new InspectorListViewModel());