Created
November 7, 2011 21:52
-
-
Save jlebensold/1346313 to your computer and use it in GitHub Desktop.
Building a JSON End-Point With SLIM and jQuery: Part 2 – Zendcasts.com
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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> |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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(); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment