Tuesday, July 15, 2014

KnockoutJS Mapping to PHP & MySQL

A little while back I wrote a post called ‘Hello LAMP with Codio’. I wanted to leverage that example and create one that also uses KnockoutJS and the ko.mapping plugin.

So, I added a few files to the project on Codio. First, I added the Knockout script and the mapping plugin mentioned above. I also created knockout.php and ShowMsgs.html. You can view and run them from the Codio project.

The important part of knockout.php is fetching an object instead of an array and then echoing JSON back to the requesting ajax call that will be shown below.


If you actually browse to knockout.php, you will see the JSON:


The piece you’re probably searching for: In ShowMsgs.html, I code my viewModel (which I actually leave to ko.mapping), my template and the jQuery.


Please note that you’re going to need that jQuery reference as well. I used their CDN but you can reference it any way you wish. Also, in production, you don’t want to use the Debug version of any script but we are just creating a demo that we want to step through here.

Here’s what we get when we browse to ShowMsgs.html


Please see the original post “Hello LAMP with Codio” to see how the MySQL data was setup along with how to set up a Codio project in general.

No comments:

Post a Comment