headless

Javascript

Saving Angular $scope as JSON with PHP

14 Oct , 2014  

This is for a small Angular application where creating an API is overkill and the server is already set up with a LAMP stack

Because this is for a small application that just one client is using I just want to store my app’s data as a JSON file on the server and have the app download it straight into Angular $scope rather than have a proper API. Then save any changes made back to the JSON file.

Loading the JSON is straightforward within Angular but to do the saving there has to be a little snippet of server side coding. I chose PHP because I knew it a bit and the server was already running with a LAMP stack. However it wouldn’t work at first and took me quite a while to work out why so I thought I’d put these snippets out there in case anyone else has the same problem.

TL;DR

Loading

For these snippets I’m using content.json as my JSON file and  putting it into the $scope as $scope.content.

In bigger apps the Angular way would be to put this in a service but in a small simple app I think its ok to put this at the beginning of your controller.

 $http.get('content.json').
   success(function(data) {
     $scope.content = data;
   }).
   error(function() {
     // log error
   });

Saving

The Markup

Just to be thorough I thought I’d include a snippet showing a button to call the angular save function!

<button ng-click="save()" type="button" class="btn btn-primary">Save Changes</button>

The Angular

So I’ve called the PHP file saveJson.php and I’m using Angular’s shortcut method $http.post

$scope.save = function(){
  $http.post('saveJson.php', $scope.content).then(function() {
    // log success
  });
};

The PHP

This is the complete PHP file.

  • First it gets the data using php://input instead of $_POST and I’ll put in some further reading links as to why (headers!).
  • Then it  opens content.json with the server path (not the URL – you may also need to adjust permissions on this file – I did!)
  • Writes the JSON into it
  • Closes it again
<?php
  $json = file_get_contents("php://input");
  $file = fopen('/var/www/content.json','w+');
  fwrite($file, $json);
  fclose($file);
?>

Further Reading

If you want to know more about headers n’ stuff with Angular, JSON and PHP these are the links that helped me!

 


One response to “Saving Angular $scope as JSON with PHP”

  1. Alexander Pava says:

    excelente informacion…practica y facil para usar Json!
    gracias.

Leave a Reply

Your email address will not be published. Required fields are marked *