Almac
Almac

Reputation: 227

PHP: respond to AJAX post request

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);

?>

Upvotes: 0

Views: 1007

Answers (2)

Borys Serebrov
Borys Serebrov

Reputation: 16182

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.

Upvotes: 2

Jimit Shah
Jimit Shah

Reputation: 92

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]);

Upvotes: 0

Related Questions