Before Down voting (I wanted to implement the CRUD using JSON file and not the Database)
I am using the below code in Angular JS to send the form data to PHP and from PHP I wanted to modify my local JSON file.
I am facing below issues
- The Form values are going as Null in the JSON file
I want to append the array every time user clicks on the register button
<!DOCTYPE html> <html lang="en"> <head> <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script> </head> <body ng-app="myApp"> <div ng-controller="myCtrl"> <form> <h2>Register Form</h2> <div> <label>First Name</label> <input type="text" ng-model="firstname" placeholder="First Name" required="required"> </div> <div> <label>Last Name</label> <input type="text" ng-model="lastname" placeholder="Last Name" required="required"> </div> <button ng-click='Register()'>Register</button> </form> <table> <tr> <th>First Name</th> <th>Last Name</th> </tr> <tr ng-repeat="data in usersData"> <td>{{data.firstname}}</td> <td>{{data.lastname}}</td> </tr> </table> </div> <script type="text/javascript"> var app = angular.module('myApp', []); app.controller('myCtrl', function ($scope, $http) { $scope.Register = function () { $http.post("misc.php", { 'firstname': $scope.firstname, 'lastname': $scope.lastname }).success(function (response) { $scope.usersData = response.users; }); }; }); </script> </body> </html>
PHP Code
<?php
$file="misc.json";
$json = json_decode(file_get_contents($file),TRUE);
$first = $_POST['firstname'];
$last = $_POST['lastname'];
$json[$user] = array("first" => $first, "last" => $last);
file_put_contents($file, json_encode($json));
?>
But Once I Submit I am getting below info in the JSON file
{"":{"first":null,"last":null}}
But I wanted to send real values and the JSON format I want as
[{
"first": "John",
"last": "Anderson"
},
{
"first": "Mike",
"last": "Langer"
}]
file_get_contents('php://input')in PHP instead of POST, or change the submitted form data in angular. You also need to set your development environment to show all errors. And lastly, your expected output does not match what you will get from$json[$user] = array(..., it will give you a json file with{ "whatever $user is": ["first": "jim", "last": "leirvik"] }.