StolenSheep
StolenSheep

Reputation: 57

Parsing JSON Object - Angularjs + PHP

I'm working on some CRUD operations for an Angular app that communicates with a PHP API on the server. I'm very new to PHP so I'm have trouble parsing what I send to the delete.php when I want to delete an entry in the database. When I send the record's id in the Data properties of the request it brings the name with the value, so Data contains 'id=1', for example.

On the PHP end I went off an example that used $_Post['id'] to get the condition for doing the deleting but from what I can tell that doesn't work because of the fact I'm sending a file that doesn't match that name. I know there are ways to encode to JSON or otherwise get the value on the PHP end but I tried it and whatever mess I made of it it deletes the entire table rather than the entry I want to specify..!

How should I go about collecting the data and parsing it so that it can fit into the delete() function?

In the App.js:

    $http({
       method: 'POST',
       url: 'http://localhost:8080/sns/delete.php',
       data: {id: user.id}
    }).success(function(response){
        if(response.status == 'OK'){
                var index = $scope.users.indexOf(user);
                $scope.users.splice(index,1);
        }
    });

delete.php:

<?php

include 'DB.php';

$db = new DB();
$tblName = 'members';
            if(!empty($_POST['id'])){
                $condition = $_POST['id'];
                $delete = $db->delete($tblName,$condition);
                if($delete){
                    $data['status'] = 'OK';
                    $data['msg'] = 'User data has been deleted successfully.';
                }else{
                    $data['status'] = 'ERR';
                    $data['msg'] = 'Some problem occurred, please try again.';
                }
            }else{
                $data['status'] = 'ERR';
                $data['msg'] = 'POST id was, please try again.';
            }
            echo json_encode($data);
            exit;

Upvotes: 0

Views: 168

Answers (1)

Souhail Ben Slimene
Souhail Ben Slimene

Reputation: 668

try this and in then you should be able to call $_POST["id"] in your PHP script.

this should work for other request without any modification except the url and the data fields.

$http({
   method: 'POST',
   url: 'http://localhost:8080/sns/delete.php',
   data: {id: user.id},
   headers: {
            'Content-Type': 'application/x-www-form-urlencoded'
   },
   transformRequest: function (data) {
       transformedData="";
       keys=Object.keys(data);values=Object.values(data);
       for (i in keys)
            transformedData+=keys[i]+"="+values[i]+"&"; 
       return transformedData;
 }
}).success(function(response){
    if(response.status == 'OK'){
            var index = $scope.users.indexOf(user);
            $scope.users.splice(index,1);
    }
});

Upvotes: 1

Related Questions