How can I response a Jquery $.post call with Slimframework 3 with multiples status code?
my code is:
Javascript:
$.post('/insert/table/' + $pedido, table_data)
.done(function(data, statusText, xhr) {
alert(xhr.status);
if (xhr.status == 201) {
alert('Done');
} else {
alert('Error');
}
})
.fail(function(xhr, textStatus, errorThrown) {
alert(xhr.responseText);
});
PHP:
$this->post('/insert/table/{pedido}',
AppControllerMasterMasterController:SaveTable');
public function SaveTable($request, $response, $args) {
$params = (object) $request->getParams();
$logger = $this->container->get('logger');
$pedido = $args['pedido'];
if($pedido < 1){
$logger->error('Arg:Cod Pedido error.');
$response->withStatus(503);
return $response;
}
$conn = $this->container->get('DB_Producao');
if($conn) {
$tsql= "INSERT INTO .......";
if(!sqlsrv_query($conn, $tsql)) {
$logger->error('error');
$response->withStatus(503);
return $response;
die();
}
}
$response->withStatus(201)
->withHeader('Content-Type', 'text/plain')
->write('Done');;
return $response;
}
With this code, I always receive a status code 200 from post action. And I was expecting a 201 or 503 status code.
Advertisement
Answer
The request and response headers are “immutable”.
Instead of this:
$response->withStatus(503); return $response;
Try this:
return $response->withStatus(503);
or
$response = $response->withStatus(503); return $response;
// The headers are immutbale
$response = $response->withStatus(201)
->withHeader('Content-Type', 'text/plain');
// The body is not immutable
$response->getBody()->write('Done');
return $response;