Is it possible for $http.put to update information in a JSON file?

Forgive my lack of experience in this area, but I'm encountering conflicting information while researching online.

I've developed an AngularJS application that reads data from a JSON file using $http.get and displays it as a form with each element bound to ng-model. My goal is for users to be able to edit a field, click save, and have the updated data reflected in the JSON file. Some sources have told me that I need a third-party server like NodeJS for this functionality, while others demonstrate it being done in videos. Can anyone clarify if it's possible without a third-party server, and if so, what the best approach would be?

Thank you

Answer №1

When it comes to using $http GET to access a resource on the client side, Chrome may present a CORS error unless you disable web security by running an alternative command. On the other hand, Firefox might incorrectly flag the JSON as not well formed even when it is. These inconsistencies can be frustrating for developers.

If you're looking for a reliable method of storing data on the client side and ensuring its persistence through page refreshes, HTML5 LocalStorage is a solid option. An excellent demonstration of this functionality can be found in the [TodoMVC example](https://github.com/tastejs/todomvc/tree/gh-pages/architecture-examples/angularjs)

The provided code showcases a straightforward approach to saving and retrieving a JSON file from local storage. It includes methods within a Service that enable interaction with the local storage.

INDEX.HTML

<body ng-app = "app">
<div ng-controller="MainCtrl">
  <form>
<input placeholder="Enter Name.." ng-model="newContact"/>
<button type="submit" class="btn btn-primary btn-lg"    
       ng-click="addContact(newContact)">Add
    </button>
  </form>
  <div ng-repeat="contact in contacts track by $index">
    {{contact.name}}
  </div>
</div>

APP.JS

angular.module('app', ['app.services'] )
.controller('MainCtrl', function ($scope, html5LocalStorage) {
    //create variable to hold the JSON
var contacts = $scope.contacts = html5LocalStorage.get();
$scope.addContact = function(contact) {     
  $scope.contacts.push( {"name":contact} ); //Add new value
  html5LocalStorage.put($scope.contacts);   //save contacts to local storeage
    }
});

SERVICES.JS

angular.module('app.services', [] )
.factory('html5LocalStorage', function () {
  var STORAGE_ID = 'localStorageWith_nG_KEY';   //the Local storage Key
    return {
    //Get the localstorage value
    get: function () 
    {
        return JSON.parse(localStorage.getItem(STORAGE_ID) || '[]');
    },
    //Set the localstorage Value
    put: function (values) 
    {
        localStorage.setItem(STORAGE_ID, JSON.stringify(values));
    }
  };
});

Alternatively, employing Node and Express to store the JSON file on the server is another viable solution. By utilizing the 'fs-extra' module from the file system, developers can handle interactions with the JSON file effectively. It would be necessary to establish RESTful API routes for clients to communicate with the server via $http requests for performing CRUD operations.

  • /put
  • /get
  • /delete
  • /post

Answer №2

I am intrigued to witness the process of completing this task without relying on the server to write to the file. It is not as simple as posting the .json file and expecting it to automatically replace the old one, unless your server setup (such as apache, nginx, tomcat, or node) allows for this functionality.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Retrieving post information with Slim PHP Framework

Currently, I am working on implementing CRUD methods using the Slim Framework for PHP and testing them with Postman. So far, I have been successful in executing select all or select a single object via Get methods. However, when attempting to insert an obj ...

Develop a revolutionary web tool integrating Node.js, MongoDb, and D3.js for unparalleled efficiency and functionality

I am exploring the creation of a web application that will showcase data gathered from various websites. To achieve this, my plan involves automating the process of data collection through web scraping. After collecting the data from these sites, I will fo ...

Transferring an Applescript list to ExtendScript in Javascript as an array for use in InDesign

Situation Background I have a large number of Applescripts (AS) that designers rely on in InDesign to streamline production workflows. These AS scripts handle a lot of OS interactions that JavaScript cannot replicate, so transitioning away from AS is not ...

Tips for inserting a hyperlink into a Chakra UI toast

Exploring the integration of Chakra UI within my Next.js project has led me to a curious question: Can Chakra UI toasts accommodate links and styled text? If so, what is the process for implementing these features? ...

Position the <a> to the right side of the div

Is there a way to right-align the <a> element, which contains a Button with the text Push Me, within the <div> (<Paper>)? https://codesandbox.io/s/eager-noyce-j356qe This scenario is found in the demo.tsx file. Keep in mind that using ...

Access deeply nested sub-documents in MongoDB at various levels

I have a complex document structure stored in my mongoDB database and I need to extract specific sub-objects from it. For example: { "organization": "Tech Inc", "CEO": "Alice Johnson", "departments": [ { "name": "Engineering" ...

How to dynamically display content based on option selection in AngularJS using ng-show

I am trying to create a functionality where my input field is bound to my select option. When the select option is set to Yes, I want the input field to be visible, and when it's set to No, I want the input field to be hidden. (function(){ var app ...

Displaying errors while using Dropzone to upload a photo

Hi, I'm facing an issue with uploading images using jQuery. Whenever I try to upload an image, I encounter errors. How can I resolve this problem? The reason I can't use the dropzone form is because it belongs to a different form. Here are the e ...

Recurring problem with Jquery ajax: constant undefined result value

I am completely new to utilizing ajax and jquery's ajax wrapper function. My objective is to fetch json data from an API and then add the result to the html of a website that I am constructing. Here is the code snippet: $.ajax({ type : 'GET ...

JavaScript - Verify if all properties belonging to an object are set to true

I'm facing a challenge with an object that contains various fields which could potentially be set to true for a user, similar to a list of achievements. If I have an object like {one: true, two: false, three: true}, how can I prevent the function from ...

Pseudo-element fails to display in React when applied to a paragraph tag, even with display block property set

I am experiencing an issue where the pseudo element ::after is not appearing in my browser. I am currently working with React.js and Material UI's makeStyles. Here is the code snippet causing the problem: modalTitle: { borderBottom: '2px sol ...

What could be causing my middleware to run twice?

A custom middleware was created in express.js/node.js to handle session checking. If a user ID is found in the session, it displays the user's menu; otherwise, it shows the default menu. For every page request, an ID check is performed and the user d ...

Is it possible to identify an event on an input field that has been disabled using Angular?

I am attempting to retrieve an event when an input field becomes disabled. <input [disabled]='disableTextbox' (click)="delectInput()"> The code snippet above represents my input field. I am trying to capture the event that occurs ...

Invoke a function in the Vue.js component

I am new to Vue.js and I am trying to figure out how to call a method from a component. var app = new Vue({ el: '#app', components: { message: { props: ['createdat'], template: ' ...

Deciphering JSON using Transact-SQL

I need to extract each value name and its corresponding value from a JSON string in order to pivot them into separate columns in SQL. This will allow me to easily incorporate them into a PowerShell script for sending data to an external API. DECLARE @json ...

What methods can be used to broaden configuration variables within VSCode using an extension?

I attempted to develop an extension for vscode that requires reading the pasteImage.parth variable from the ./vscode/settings.json file { "pasteImage.path": "${workspaceRoot}/assets/images" } In my attempt to retrieve the variable us ...

Having trouble connecting to a port on my ec2 instance to run an Angular application

I've been working on an angular application using the angular cli to get everything set up. After running the ng serve command, a server is spawned at this address <my_ec2_host_name>:4200. However, when I try to access the page on my browser, it ...

AngularJS is unable to access the MVC controller

As a beginner in angularJS, I am attempting to retrieve data from my MVC jsonresult in order to populate a list. However, my GetLogs function is not accessing the MVC jsonresult /misc/getlogs (even when using the full URL). Here is the code snippet: <b ...

How can we convert a BSON ObjectId into a JSON object?

I attempted to convert it to JSON format. _id: Object _bsontype: "ObjectID" id: "X±¸kÍ+I¿9À" Is there a way to convert this into JSON format? ...

Translating jQuery to Regular JavaScript Principles

Could someone please provide me with a comparison between various jQuery methods and their equivalent normal Javascript DOM methods? For example: prev() next() before() after() I would greatly appreciate it if you could offer a mapping of jQuery/Javascr ...