简体   繁体   中英

Angular - $http.delete returns success but doesn't works

I have an Angular + PHP application and I'm having problem to delete an customer.

I got no error, actually, the application returns sucecess, but it doesn't delete the customer from my database.

This is my angular controller

    app.controller('consultar_cliente_controller', function($scope, $http){
    $scope.listaDeCliente = [];

    var init = function(){
        $scope.buscar();
    };

    $scope.buscar = function(){
        $http.get('consultar_cliente.php')
             .success(function(data){
                $scope.listaDeCliente = data;
             })
             .error(function(){
                console.error('Erro ao executar o GET do cliente');
             });
    };

    $scope.deletar = function(id){
        $http.delete('remover_cliente.php/' + id)
             .success(function(){
                console.log('Cliente removido com sucesso!');
                $scope.buscar();
             })
             .error(function(){
                console.error('Erro ao remover cliente');
             })
    };

    init();
});

This is my PHP

<?php
  $dbh = new PDO('pgsql:host=localhost;dbname=livraria_glp', 'postgres');
  /*
  * Recuperando todos os detalhes da requisição HTTP do Angular
  */ 
  $postdata = file_get_contents("php://input");
  $request  = json_decode($postdata);
  @$id      = $request->id;

  echo $id;

  $dbh->exec("DELETE FROM PRODUTO WHERE ID = '$id'") or die( $dbh->errorInfo() );

?>

And this is my HTML

<div class="well">
  <div class="container">
      <h2>Dados</h2>
      <div class="form-group">
        <label>Nome</label>
          <input class="form-control" type="text" ng-model="filtroNome" />
      </div>
  </div>
  <div class="container resultado">      
    <table class="table">
      <thead>
        <tr>
          <th>Nome</th>
          <th>CPF</th>
          <th>E-mail</th>
        </tr>
      </thead>
      <tbody>
        <tr ng-repeat="cliente in listaDeCliente | filter : filtroNome">
          <td>{{cliente.nome}}</td>
          <td>{{cliente.cpf}}</td>
          <td>{{cliente.id}}</td>
          <td><button class="btn btn-danger" ng-click="deletar(cliente.id)">Deletar</button></td>
        </tr>
      </tbody>
    </table>
  </div>
  <button class="btn btn-success" onclick="window.location.href='javascript:window.history.go(-1)'">Voltar</button>
</div>

Edit: I've tried this on PHP:

echo "DELETE FROM PRODUTO WHERE ID = '$id'";

And it returned:

DELETE FROM PRODUTO WHERE ID = ''

Why can't the PHP recieve the id?

Angular doesn't send a request body for DELETE so you're going to have to read id from the URL. You might as well just pass it as a query parameter

$http.delete('remover_cliente.php', {
    params: {id: id}
})

Then read it via $_GET['id'] .

<?php
if (!isset($_GET['id'])) {
    exit;
}

$id = $_GET['id'];
$dbh = new PDO('pgsql:host=localhost;dbname=livraria_glp', 'postgres');
$dbh->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

$stmt = $dbh->prepare('DELETE FROM PRODUTO WHERE ID = ?');
$stmt->execute([$id]);

echo $id;

Alternatively (and just in case $_GET doesn't work for DELETE requests), you could try forcing the request message data using

$http.delete('remover_cliente.php', {
    data: {id: id}
})

however I don't know if this is supported and it's certainly not very REST-ful. If it does work, you can continue to use file_get_contents('php://input') and json_decode() .

Please try to replace this,

$scope.deletar = function(id){
    var postData = {'id' : id};
    $http.delete('remover_cliente.php', postData)
         .success(function(){
            console.log('Cliente removido com sucesso!');
            $scope.buscar();
         })
         .error(function(){
            console.error('Erro ao remover cliente');
         })
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM