How to update JSON file on server using JavaScript

I am encountering an issue that has been discussed quite frequently. Despite trying various solutions, none have proven effective so far.

The problem lies in my JavaScript file where I have some data that I need to append to an existing .json file on my server. Although I attempted the following approach, whenever I check the .json file after calling ajax_get_json(), the new data is not added.

function ajax_get_json(){
var hr = new XMLHttpRequest();
hr.open('POST', 'myyjson.json', true);
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
var us = document.getElementById("firstname").value;
var msg= document.getElementById("message").value;
hr.onreadystatechange = function(){
    if (hr.readyState == 4 && hr.status == 200){
        var obj = JSON.parse(hr.responseText);
        obj['participant'].push({"user": us, "message": msg});
        var sendingObj = JSON.stringify(obj);
    }
}
hr.send(sendingObj);

}

The structure of myjson.json file is as follows:

{ "participant":[
{"user":"Steven", "message":"Hey, I'm in!"},
{"user":"Tim", "message":"I wrote something."},
{"user":"Lukas", "message":"example"}
]}     

Can anyone provide insight into what might be causing the issue or suggest a better approach?

Thank you in advance!

Answer №1

When it comes to writing JSON on the server side using JavaScript on the client, it's crucial to consider security implications. It's not advisable to directly write JSON on the server from the client side as this can pose a security risk. The recommended approach is to use server-side languages like PHP, Java, or JavaScript to handle JSON writing operations. You can then trigger these server functions from the client side using techniques like AJAX.

  1. On the client side, you can initiate a request by accessing a specific URL such as

    www.yourserver.com/writejson.php?u=steven&m=Hi
    .

  2. The server will intercept this request and proceed to write the data to a JSON file. In this case, the username is steven and the message is Hi.

It's important to clarify a misconception regarding the XMLHttpRequest.send method. This method is not used for sending data to be saved on the server; rather, it triggers the XMLHttpRequest. Here's a breakdown of how your code executes:

function ajax_get_json(){
var hr = new XMLHttpRequest(); // 1.
hr.open('POST', 'myyjson.json', true); // 2.
hr.setRequestHeader("Content-type", "application/x-www-form-urlencoded"); // 3.
var us = document.getElementById("firstname").value; // 4.
var msg = document.getElementById("message").value; // 5.
hr.onreadystatechange = function(){ // 6.
    if (hr.readyState == 4 && hr.status == 200){ // 8. This callback is triggered when the XMLHttpRequest state changes
    var obj = JSON.parse(hr.responseText); // 9. Parse the response once it's complete
    obj['participant'].push({"user": us, "message": msg}); // 10. Modify the object with user input
    var sendingObj = JSON.stringify(obj); // 11. Convert the updated object to JSON
    }
}
hr.send(sendingObj); // 7. Note that sendingObj should be defined before being sent

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

Parsing JSON in Node.js: Adding the Key-Value Pair at the Beginning of the JSON

I am working with a JSON file that contains numerous lines of code, each one uniquely identified by a time stamp. I need to extract this time stamp and add it at the beginning of the JSON data itself. I'm unsure of the best approach to achieve this ta ...

Integrate JavaScript code with HTML pages

After creating a basic HTML structure that I am proud of, I encountered some challenges with getting the Javascript to function properly. I am new to working with Javascript and received some initial assistance, but unfortunately, it is no longer working. ...

Prevent additional clicks on the image

Currently, I am dealing with a situation where I have a list containing a jQuery handler for mouse clicks. The dilemma is that I need to insert an image into the list, but I want clicking on the image to trigger a different function than clicking elsewhere ...

Utilizing the require function to implement an AngularJS Controller without having

I've been working with requireJS in my application. Every time I try to register a controller on my module, it gives me an error saying that the controller is not defined. Here's the code for my LoginController located in login.controller.js: f ...

Encountered an npm ERR while executing the React project

I'm encountering an issue with running my React project. When I use the command "npx start", I receive the following error message. Can someone please assist me with this? npm ERR! could not determine executable to run npm ERR! A detailed log of thi ...

Basic Django button for triggering view function

After attempting tutorials for a few days, I've decided to throw in the towel. Any assistance would be greatly appreciated. I'm struggling to make this work - it seems straightforward, but it's actually quite complex. All I'm trying to ...

Is it possible to exclude specific URLs from CSRF protection in sails.js?

I am currently integrating Stripe with my sails.js server and need to disable CSRF for specific URLs in order to utilize Stripe's webhooks effectively. Is there a way to exempt certain URLs from CSRF POST requirements within sails.js? I have searched ...

Issue with Spring JPA: Foreign keys missing from response

I have a database containing entities in a parent-child relationship. When querying the child table to retrieve all rows, only the non-foreign key fields are returned in the JSON response. Can someone assist me in including the foreign key in the JSON resp ...

Modify the displayed text according to the content of the input field in HTML

I need to update the value of an <h3> tag based on user input in an input field. Here is my current code snippet: <input id="Medication" name="Medication" size="50" type="text" value=""> <script> $(document).ready(function () { $(&apos ...

Unable to utilize the post method in Node.js

<form class="ui form" action"/submit" method="post"> <div class="field"> <label>Time dedicated to studying:</label> <input type="number" name="study" placeholder="Total time spent on studies:"> ...

embedding a button alongside the pager in an HTML document

I am encountering an issue with the positioning of a button in my paginated table setup. The button is currently displaying below the pager instead of being aligned on the left side of the page along with the pager. https://i.stack.imgur.com/gUiB9.png To ...

Creating a worldwide entity through the use of an Immediately Invoked Function Expression

There are 2 methods I discovered for defining a global object using IIFE: (function () { var func = function () { }; window.func = func; }()); compared to: (function (myFunc) { window.func = myFunc(); }(function () { var func = functi ...

The onchange function in JavaScript is malfunctioning

<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Product page</title> <!-- Fonts -- ...

Attempting to alert a particular device using Flutter for notification delivery

Currently, I am developing a Chat app using Flutter and attempting to send notifications to specific devices through Firebase functions. Initially, I retrieve the device token and store it in Firebase. Now, my challenge lies in fetching the token and invok ...

Button to scroll down

I have successfully implemented a #scrolldownbutton that scrolls to the first component. However, I am now attempting to modify it so that when the button is clicked, the page smoothly scrolls within the viewport and stops at the partially visible componen ...

Creating dynamic components in Vue.js using VueJS and jQuery synergistically

New to Vue.js and in the process of building a Vue component inspired by this custom select menu. I want to include an ionicon with each list item. Typically, I can add the icon in Vue.js using: <component class="icon" :is="name-of-icon& ...

What is the best way to transfer variables between PHP and an external JavaScript file?

I need to transfer 2 variables (which store data for a chart) to an external JS file that contains the chart settings. In my PHP code, I have: <script type='text/javascript'> var final_values = '$final_values'; var final_names = ...

How can JavaScript be used to make an AJAX request to a server-side function?

I am diving into the world of AJAX and feeling a bit uncertain about how to structure my AJAX call. $.ajax({ type: "POST", url: "Default.aspx/function", data: '{ searchBy: id }', contentType: "application/json; charset=utf-8" }). ...

Retrieve content from Wordpress blog including image preview

Can someone help me find a PHP script that can import posts from my WordPress blog and display them on another website, complete with a thumbnail of each blog post? Thank you in advance for your assistance! ...

Implementing a dynamic like functionality using Ajax in Django

I've created a new structure for the like button, but it's not functioning correctly. Here are the files I'm working with: models.py class Comment(models.Model): title = models.CharField(max_length=50) author = models.ForeignKey(Pr ...