Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
Browse files

docs: PHP example initial release (issue #73)

  • Loading branch information...
commit 4cd99d2d0ac2db9cc0086d82ec1acb3a7a0b79ea 1 parent 50c4de3
@warpech warpech authored
Showing with 276 additions and 0 deletions.
  1. +151 −0 demo/php.html
  2. +34 −0 demo/php/load.php
  3. +91 −0 demo/php/save.php
View
151 demo/php.html
@@ -0,0 +1,151 @@
+<!doctype html>
+<html xmlns="http://www.w3.org/1999/html">
+<head>
+ <meta charset='utf-8'>
+ <title>PHP example - Handsontable</title>
+
+ <!--
+ Loading handsontable dependencies.
+ Please note that some dependencies are optional:
+ - bootstrap-typeahead.js - is required only if you need the sexy autoexpanding textarea feature
+ - jquery.autoresize.js - is required only if you need the autocomplete feature
+ - jquery.contextMenu.js - is required only if you need the context menu feature
+ - jquery.contextMenu.css - is required only if you need the context menu feature
+ - jquery.ui.position.js - is required only if you need the context menu feature
+ -->
+ <script src="../lib/jquery.min.js"></script>
+ <script src="../jquery.handsontable.js"></script>
+ <script src="../lib/bootstrap-typeahead.js"></script>
+ <script src="../lib/jquery.autoresize.js"></script>
+ <script src="../lib/jQuery-contextMenu/jquery.contextMenu.js"></script>
+ <script src="../lib/jQuery-contextMenu/jquery.ui.position.js"></script>
+ <link rel="stylesheet" media="screen" href="../lib/jQuery-contextMenu/jquery.contextMenu.css">
+ <link rel="stylesheet" media="screen" href="../jquery.handsontable.css">
+
+ <!--
+ Loading demo dependencies. They are used here only to enhance the examples on this page
+ -->
+ <script src="js/json2.min.js"></script>
+ <link rel="stylesheet" media="screen" href="css/demo.css">
+</head>
+
+<body>
+<a href="http://github.com/warpech/jquery-handsontable"><img style="position: absolute; top: 0; right: 0; border: 0;" src="http://s3.amazonaws.com/github/ribbons/forkme_right_darkblue_121621.png" alt="Fork me on GitHub"/></a>
+
+<div id="container">
+ <h1><a href="../index.html">Handsontable</a></h1>
+
+ <div class="description">
+ Handsontable is a minimalistic approach to Excel-like table editor in HTML & jQuery
+ <br><a href="../index.html">&lt; back to main</a>
+ </div>
+
+ <h2>PHP example</h2>
+
+ <p>This page loads and saves data on server. In this example, client side uses <b>$.ajax</b>. Server side uses <b>PHP with PDO (SQLite)</b>.</p>
+
+ <p>Please note. This page and the PHP scripts are a work in progress. They are not yet configured on GitHub. Please run it on your own localhost.</p>
+
+ <p>
+ <button name="load">Load</button>
+ <button name="save">Save</button>
+ <label><input type="checkbox" name="autosave" checked="checked" autocomplete="off"> Autosave</label>
+ </p>
+
+ <div id="exampleConsole" class="console">Click "Load" to load data from server</div>
+
+ <div id="exampleGrid" class="dataTable"></div>
+
+ <script>
+ var $container = $("#exampleGrid");
+ var $console = $("#exampleConsole");
+ var $parent = $container.parent();
+ var autosaveNotification;
+ $container.handsontable({
+ rows: 8,
+ cols: 3,
+ rowHeaders: true,
+ colHeaders: ['Manufacturer', 'Year', 'Price'],
+ minSpareCols: 0,
+ minSpareRows: 1,
+ contextMenu: true,
+ onChange: function (change, source) {
+ if (source === 'loadData') {
+ return; //don't save this change
+ }
+ if ($parent.find('input[name=autosave]').is(':checked')) {
+ clearTimeout(autosaveNotification);
+ $.ajax({
+ url: "php/save.php",
+ dataType: "json",
+ type: "POST",
+ data: {changes: change}, //contains changed cells' data
+ success: function (data) {
+ $console.text('Autosaved (' + change.length + ' cell' + (change.length > 1 ? 's' : '') + ')');
+ autosaveNotification = setTimeout(function () {
+ $console.text('Changes will be autosaved');
+ }, 1000);
+ }
+ });
+ }
+ }
+ });
+ var handsontable = $container.data('handsontable');
+
+ $parent.find('button[name=load]').click(function () {
+ $.ajax({
+ url: "php/load.php",
+ dataType: 'json',
+ type: 'GET',
+ success: function (res) {
+ var data = [], row;
+ for (var i = 0, ilen = res.cars.length; i < ilen; i++) {
+ row = [];
+ row[0] = res.cars[i].manufacturer;
+ row[1] = res.cars[i].year;
+ row[2] = res.cars[i].price;
+ data[res.cars[i].id - 1] = row;
+ }
+ handsontable.loadData(data);
+ $console.text('Data loaded');
+ }
+ });
+ }).click(); //execute immediately
+
+ $parent.find('button[name=save]').click(function () {
+ $.ajax({
+ url: "php/save.php",
+ data: {"data": handsontable.getData()}, //returns all cells' data
+ dataType: 'json',
+ type: 'POST',
+ success: function (res) {
+ if (res.result === 'ok') {
+ $console.text('Data saved');
+ }
+ else {
+ $console.text('Save error');
+ }
+ },
+ error: function () {
+ $console.text('Save error');
+ }
+ });
+ });
+
+ $parent.find('input[name=autosave]').click(function () {
+ if ($(this).is(':checked')) {
+ $console.text('Changes will be autosaved');
+ }
+ else {
+ $console.text('Changes will not be autosaved');
+ }
+ });
+ </script>
+
+ <h3>About</h3>
+
+ <p>This is advanced usage example of <a href="../index.html">Handsontable</a>. Check out the
+ <a href="../index.html">main page</a> for more demos.</p>
+</div>
+</body>
+</html>
View
34 demo/php/load.php
@@ -0,0 +1,34 @@
+<?php
+/**
+ * This is an example code that shows how you can load Handsontable data from server using PHP with PDO (SQLite).
+ * This code is not intended to be maximally efficient nor safe. It is for demonstrational purposes only.
+ * Changes and more examples in different languages are welcome.
+ *
+ * Copyright 2012, Marcin Warpechowski
+ * Licensed under the MIT license.
+ * http://warpech.github.com/jquery-handsontable/
+ */
+
+try {
+ //open the database
+ $db = new PDO('sqlite:cars.sqlite'); //will create the file in current directory. Current directory must be writable
+
+ //create the database if does not exist
+ $db->exec("CREATE TABLE IF NOT EXISTS cars (id INTEGER PRIMARY KEY, manufacturer TEXT, year INTEGER, price INTEGER)");
+
+ //select all data from the table
+ $select = $db->prepare('SELECT * FROM cars ORDER BY id ASC LIMIT 100');
+ $select->execute();
+
+ $out = array(
+ 'cars' => $select->fetchAll(PDO::FETCH_ASSOC)
+ );
+ echo json_encode($out);
+
+ // close the database connection
+ $db = NULL;
+}
+catch (PDOException $e) {
+ print 'Exception : ' . $e->getMessage();
+}
+?>
View
91 demo/php/save.php
@@ -0,0 +1,91 @@
+<?php
+/**
+ * This is an example code that shows how you can save Handsontable data on server using PHP with PDO (SQLite).
+ * This code is not intended to be maximally efficient nor safe. It is for demonstrational purposes only.
+ * Changes and more examples in different languages are welcome.
+ *
+ * Copyright 2012, Marcin Warpechowski
+ * Licensed under the MIT license.
+ * http://warpech.github.com/jquery-handsontable/
+ */
+
+try {
+ //open the database
+ $db = new PDO('sqlite:cars.sqlite'); //will create the file in current directory. Current directory must be writable
+
+ //create the database if does not exist
+ $db->exec("CREATE TABLE IF NOT EXISTS cars (id INTEGER PRIMARY KEY, manufacturer TEXT, year INTEGER, price INTEGER)");
+
+ $colMap = array(
+ 0 => 'manufacturer',
+ 1 => 'year',
+ 2 => 'price'
+ );
+
+ if ($_POST['changes']) {
+ foreach ($_POST['changes'] as $change) {
+ $rowId = $change[0] + 1;
+ $colId = $change[1];
+ $newVal = $change[3];
+
+ if (!isset($colMap[$colId])) {
+ echo "\n spadam";
+ continue;
+ }
+
+ $select = $db->prepare('SELECT id FROM cars WHERE id=? LIMIT 1');
+ $select->execute(array(
+ $rowId
+ ));
+
+ if ($row = $select->fetch()) {
+ $query = $db->prepare('UPDATE cars SET `' . $colMap[$colId] . '` = :newVal WHERE id = :id');
+ } else {
+ $query = $db->prepare('INSERT INTO cars (id, `' . $colMap[$colId] . '`) VALUES(:id, :newVal)');
+ }
+ $query->bindValue(':id', $rowId, PDO::PARAM_INT);
+ $query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
+ $query->execute();
+ }
+ } elseif ($_POST['data']) {
+ $select = $db->prepare('DELETE FROM cars');
+ $select->execute();
+
+ for ($r = 0, $rlen = count($_POST['data']); $r < $rlen; $r++) {
+ $rowId = $r + 1;
+ for ($c = 0, $clen = count($_POST['data'][$r]); $c < $clen; $c++) {
+ if (!isset($colMap[$c])) {
+ continue;
+ }
+
+ $newVal = $_POST['data'][$r][$c];
+
+ $select = $db->prepare('SELECT id FROM cars WHERE id=? LIMIT 1');
+ $select->execute(array(
+ $rowId
+ ));
+
+ if ($row = $select->fetch()) {
+ $query = $db->prepare('UPDATE cars SET `' . $colMap[$c] . '` = :newVal WHERE id = :id');
+ } else {
+ $query = $db->prepare('INSERT INTO cars (id, `' . $colMap[$c] . '`) VALUES(:id, :newVal)');
+ }
+ $query->bindValue(':id', $rowId, PDO::PARAM_INT);
+ $query->bindValue(':newVal', $newVal, PDO::PARAM_STR);
+ $query->execute();
+ }
+ }
+ }
+
+ $out = array(
+ 'result' => 'ok'
+ );
+ echo json_encode($out);
+
+ // close the database connection
+ $db = NULL;
+}
+catch (PDOException $e) {
+ print 'Exception : ' . $e->getMessage();
+}
+?>
Please sign in to comment.
Something went wrong with that request. Please try again.