How can I response a Jquery $.post call with Slimframework 3 with multiples status code?
my code is:
Javascript:
JavaScript
x
13
13
1
$.post('/insert/table/' + $pedido, table_data)
2
.done(function(data, statusText, xhr) {
3
alert(xhr.status);
4
if (xhr.status == 201) {
5
alert('Done');
6
} else {
7
alert('Error');
8
}
9
})
10
.fail(function(xhr, textStatus, errorThrown) {
11
alert(xhr.responseText);
12
});
13
PHP:
JavaScript
1
29
29
1
$this->post('/insert/table/{pedido}',
2
AppControllerMasterMasterController:SaveTable');
3
4
public function SaveTable($request, $response, $args) {
5
$params = (object) $request->getParams();
6
$logger = $this->container->get('logger');
7
$pedido = $args['pedido'];
8
if($pedido < 1){
9
$logger->error('Arg:Cod Pedido error.');
10
$response->withStatus(503);
11
return $response;
12
}
13
14
$conn = $this->container->get('DB_Producao');
15
if($conn) {
16
$tsql= "INSERT INTO .......";
17
if(!sqlsrv_query($conn, $tsql)) {
18
$logger->error('error');
19
$response->withStatus(503);
20
return $response;
21
die();
22
}
23
}
24
$response->withStatus(201)
25
->withHeader('Content-Type', 'text/plain')
26
->write('Done');;
27
return $response;
28
}
29
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:
JavaScript
1
4
1
$response->withStatus(503);
2
3
return $response;
4
Try this:
JavaScript
1
2
1
return $response->withStatus(503);
2
or
JavaScript
1
4
1
$response = $response->withStatus(503);
2
3
return $response;
4
JavaScript
1
9
1
// The headers are immutbale
2
$response = $response->withStatus(201)
3
->withHeader('Content-Type', 'text/plain');
4
5
// The body is not immutable
6
$response->getBody()->write('Done');
7
8
return $response;
9