Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

It is possible to add content to a JSON file using AngularJS $http.post method?

I'm trying to update a json file using angularjs $http.post method, am I doing it wrong or it's not possible?

app.controller('MainController', function($scope, $http) {
    // we create an object called formModel and used ngModel="formModel.name/email/password" 
// to create properties inside it
    $scope.formModel = {};
    $scope.jsonStructure = [];
    $scope.submitting = false;

    // function to send data when the button register is clicked
    $scope.onSubmit = function(valid) {

        if (valid) {
            $scope.jsonStructure.push($scope.formModel);

            $scope.submitting = true;
            console.log($scope.formModel);
            // function to post data to a servers using http, the first parameter is the address, the second parameter is the 
// form that we are sending, sucess is the callback to execute when the post method is completed, and error is the callback
// to execute if the post method didnt work https://minmax-server.herokuapp.com/register/
            $http.post('about.json', $scope.jsonStructure).success(function(data){
                console.log($scope.jsonStructure);
                console.log(':)');
                $scope.submitting = false;
            }).error(function(data){
                console.log(':(');
                $scope.submitting = false;
            });

        } else {

            console.log('Invalid');

        };

    };
});

1 Answer

You can't write data to a local file with just an ajax request.

You need server side code that does that. Search for json-server to get a simple server solution.

Thanks, that's all I need to know