0

I'm using angular to retrieve json data via get request. I would like to update the json file similarly by post, and have PHP respond by sending back the updated json. The problem is that the page is not updating (ajax) when the json file is updated.

HTML

<html ng-app="myApp">
    <body ng-controller="mainController">
<div>
    <h3>Rules</h3>
    <ul>
        <li ng-repeat="rule in rules">{{rule.rulename}}</li>
    </ul>
</div>

<div>
    <label>New Rules:</label>
    <input type="text" ng-model="newRule" />
    <input type="button" ng-click="addRule()" value="Add" />
</div>

JavaScript

var myApp = angular.module('myApp', []);
myApp.controller('mainController', ['$scope','$http', function($scope,  $scope.getItems = function() {
        $http.get("localhost:8888/json/newRules.json")
       .then(
           function(response){
                //success callback
                $scope.rules = response.data;
           }, 
           function(response){
                // failure callback
                console.log(response);
           }
        );
    };

    $scope.getItems();
    $scope.newRule = '';
    $scope.addRule = function() {
    $http.post("localhost:8888/json/newRules.json", JSON.stringify([{rulename: $scope.newRule}]))
           .then(
               function(response){
                    //success callback
                    $scope.getItems();
                    $scope.rules = response;    
                    $scope.newRule = '';    
               }, 
               function(response){
                    // failure callback
                    console.log(response);
               }
            );  
    };

}]);

PHP

<?php  

    $data = file_get_contents("newRules.json");
    $data2 = file_get_contents("php://input");
    $postData = json_decode($data);
    $postData2 = json_decode($data2);
    $newArray = array_merge($postData, $postData2);
    $newPost = json_encode($newArray);
    file_put_contents("newRules.json", $newPost);

?>
Almac
  • 227
  • 2
  • 9
  • 18
  • What kind of stack are you using in PHP ? Legacy php ? Framework ? etc... – Okazari Feb 10 '16 at 16:18
  • @Okazari I'm using mamp. – Almac Feb 10 '16 at 18:18
  • @Almac regarding your question that nothing comes back from the server -are you actually posting to the URL like "https://api.myjson.com/bins/16mjh"? Didn't you forget to change these URLs to your local server URLs? – Borys Serebrov Feb 10 '16 at 21:35
  • @BorisSerebrov I'm using local server ip address. I can see the post request from the network tab on chrome, but no response. – Almac Feb 10 '16 at 21:45
  • @Almac in general it should work, try to test it separately. For example, check if you server url returns the data if you post it with curl: `curl -H "Content-Type: application/json" --data '{ "test": "value" }' http://your/url/here` – Borys Serebrov Feb 10 '16 at 22:11
  • I think I was using legacy angular code for my get and post requests. I've updated the code but still having problems updating json. – Almac Feb 10 '16 at 22:36
  • @BorisSerebrov I added the php file I'm using. I'm getting a response from the php. However, the ajax file is not getting updated thus the new data is being shown. – Almac Feb 10 '16 at 23:36
  • @BorisSerebrov I have it kind of working now but ran into a new problem. The json file gets completely overwritten by the content of the user's input. The override changes the json formatting. – Almac Feb 11 '16 at 00:31
  • @BorisSerebrov I got it working but it's not pretty lol – Almac Feb 11 '16 at 04:09
  • @Almac looks like this is a problem not related to this question, check [this](http://stackoverflow.com/questions/6054033/pretty-printing-json-with-php). – Borys Serebrov Feb 11 '16 at 09:33

2 Answers2

2

As I remember angular doesn't automatically add an application/x-www-form-urlencoded header to requests, so on the php side you may also need to decode the POST data this way:

// get the POST data
$data = file_get_contents("php://input");
$postData = json_decode($data);
// process the data
// ...
// send response
echo json_encode($responseData);

Or you can configure angular to send the header, see the details here.

Borys Serebrov
  • 15,636
  • 2
  • 38
  • 54
  • + JSON.stringify({inputRule: $scope.inputRule}) – Peter Feb 10 '16 at 16:33
  • @Peter if I use JSON.stringify, then I do not need to decode before encoding? – Almac Feb 10 '16 at 17:39
  • @Peter I don't think stringy is actually needed, I checked some examples in my code and I never used it. And, Almac, if I am right, you still will need to use `json_decode`, maybe even twice. – Borys Serebrov Feb 10 '16 at 17:53
  • @BorisSerebrov your right it's not necessarily needed, but not all data types supported by javascript are valid JSON (i.e. data objects, regular expressions, undefined, ... ). I always convert my javascript objects into JSON before sending them to the backend. Your answer is really good i just finished it with best practice in my own eyes. – Peter Feb 11 '16 at 09:33
0

use json_encode function to send response in json

check http://php.net/manual/en/function.json-encode.php

in your php script you need to do

echo json_encode(['id'=>123]);
Jimit Shah
  • 92
  • 1
  • 10