public
Created

Building a JSON End-Point With SLIM and jQuery: Part 2 – Zendcasts.com

  • Download Gist
home.tpl.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71
<html>
<head>
<title>Names Hello</title>
<script type="text/javascript" src="/js/jquery-1.5.1.js"></script>
<style>
*
{
 
margin: 0 0;
padding: 0 0;
font-family: helvetica, arial, sans-serif;
}
body {
 
background: #CCC;
}
#container
{
padding: 20px;
margin: 0 auto;
width: 600px;
background: #FFF;
}
</style>
<script>
$(function()
{
$('a.list').click(function(e)
{
findAll();
e.preventDefault();
});
 
$("form").submit(function(e)
{
$.post("/names",
{name: $("#newname").val() },
function(resp) {
findAll();
});
e.preventDefault();
});
 
});
 
function findAll()
{
$("#names").empty();
$.get("/names",function(resp)
{
$.each(resp,function(k,v)
{
$("#names").append('<li id="name_'+v.id+'" data-id="'+v.id+'">'+v.name+'</li>');
});
},"json");
};
</script>
 
</head>
<body>
<div id="container">
<h3> Names <a class="list" href="#">Load</a></h3>
<ul id="names"></ul>
<form class="" id="newnamefrm">
<input type="text" id="newname"></input><input type="submit" value="Add Name" />
</form>
</div>
</body>
 
</html>
index.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
<?php
require '../Slim/Slim.php';
require '../Name.php';
 
function json($obj)
{
header('Content-Type', 'application/json');
return json_encode($obj);
}
 
$app = new Slim();
$app->config(array('templates.path' => '../templates'));
 
$app->get('/names/:id',function($id) {
echo json(Name::find($id));
});
$app->get('/names',function() {
echo json(Name::findAll());
});
$app->post('/names',function() use ($app) {
$n = new Name(null,$app->request()->post('name'));
$n->create();
echo '{status: "success" }';
});
 
$app->get('/', function() use($app) {
$app->render('home.tpl.php');
 
});
 
 
$app->run();

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.