Skip to content

Instantly share code, notes, and snippets.

@jlcampana
Created November 29, 2013 20:47
Show Gist options
  • Save jlcampana/7711824 to your computer and use it in GitHub Desktop.
Save jlcampana/7711824 to your computer and use it in GitHub Desktop.
Llamada AJAX POST enviando json y recibiendo json en el response con Slim PHP
<?php
// header('Cache-Control: no-cache, must-revalidate');
// header('Expires: Mon, 26 Jul 1997 05:00:00 GMT');
// header('Content-type: application/json');
define('PETICION_OK' , 200);
define('PETICION_NO_AUTORIZADO' , 401);
//Login
$app->post('/api/login', function () use ($app)
{
$username = $app->request()->post('user');
$password = $app->request()->post('password');
$usuario = Model::factory('User')->where('id',$username)->where('psswd_md5',$password)->find_one();
$body = NULL;
$code = PETICION_OK;
if($usuario)
{
$profile = Model::factory('UserProfile')->where('user_id',$username)->find_many();
$body = array(
'msg' => 'Welcome '.$usuario->name,
'user' => $usuario->as_array(),
'profile' => $profile->as_array(),
);
}
else
{
$code = PETICION_NO_AUTORIZADO;
$body = array(
'msg' => 'Invalid user or password',
);
}
$app->outputJSON($body,$code);
});
?>
<?php
class CCSlim extends Slim\Slim
{
function outputJSON($data,$status)
{
switch($this->request->headers->get('Accept'))
{
case 'application/json':
default:
$this->response->headers->set('Content-Type', 'application/json');
$this->response->status($status);
echo json_encode($data);
}
}
}
?>
// En el fichero index.php del proyecto Slim:
// Prepare app
$app = new CCSlim(array(
'templates.path' => '../templates',
));
/*
$app = new \Slim\Slim(array(
'templates.path' => '../templates',
));*/
$('#btnSignIn').click( function()
{
dismissMessage();
$('#btnSignIn').attr("disabled",true);
var usuario = $.trim($('#user').val());
var pass = MD5($.trim($('#password').val()));
var call = $.post('/api/login', {user:usuario, password:pass});
call.done(function(response)
{
storeCredentials(response);
});
call.fail(function(response)
{
showMessage(response.statusText);
$('#btnSignIn').attr("disabled",false);
});
call.always(function()
{
console.log('Finished');
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment