Incorporating an Array into a JSON Object and transmitting it to a server

I have stored an Object in a .json file that contains only an Array.

Now I want to prompt the user for a word and add it to this Array. Below are the relevant code snippets:

function addWord() {
    let myWords = getWords();
    let newWord = prompt("Please enter a word to add to your list:", "");
    myWords.push(newWord);
    let myWordsJson = JSON.stringify(myWords);
    let xhr2 = new XMLHttpRequest();
    xhr2.open("GET", "words.json?wordsArray=" + myWordsJson);
    xhr2.send();
}

Here is the getWords() function:

function getWords() {
    let xhr = new XMLHttpRequest();
    xhr.open("GET", "words.json", false);
    xhr.send();
    let myCode = JSON.parse(xhr.responseText);
    return myCode["wordsArray"];
}

I have tested my code and successfully retrieved the Array from the server, added the new word, but encountered issues when trying to save the updated Array to the words.json file.

Below is the content of words.json:

{"wordsArray" : ["hello", "pencil", "school", "tooth", "family", "class"]}

Answer №1

To add single words into an array, follow these steps:

 let newWord = "Enter the word to add to the list";
 myWords['wordsArray'].push(newWord);

If you have multiple words in an array to push, use a for loop like this:

 let newWord = ["Enter the words separated by commas"];
         
      for(let i = 0; i < newWord.length ; i++) {   
         myWords['wordsArray'].push(newWord[i]);
         }

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

Personalized JavaScript Arrays

Seeking assistance to format data received from an API. Can anyone provide guidance? fields: [ { name: "A", values: { data: [1, 2, 3, 4, 5] } }, { name: "B", values: { data: [6 ...

What is the best way to bring a JavaScript file from the source file into an index.html document

I am currently in the process of developing a system using React, and as someone new to the framework, I have encountered an issue. I need to include a JavaScript file in my index.html that is located within the src folder. This js file is essential for th ...

Strategies for accessing array elements based on category

I am currently working with an array of diverse products var productList = [ { id: '1', category: 'todos', menuName: 'Empanada de Carne, Pollo o Mixta + Café 8oz.', menuPrice: '9.99&a ...

Is there a way to deactivate keyboard input on an HTML number input field? How about in a React or Material-UI environment?

I am working with an <input> tag that has the attribute type="number", and I want to disable keyboard input so that users are required to adjust the value using the spinner (up and down arrows). This will allow me to consume the input value on each c ...

What techniques can be used to resize an image to perfectly fit a square on a webpage?

A challenge on the web page is to display images in a square format of 90 * 90 pixels. However, the sizes of these images are not consistent and may vary from 80*100 to 100*80 or even 90 * 110. The requested solution is to stretch the image as follows: ...

The D3js visualization is failing to display properly for the user, with the D3 source code residing on the server

I have encountered an issue after transferring my D3js chart generation system from a development server with no problems to a live Windows 2008 r2 server. On the live server, only the background SVG element is displayed and none of the other elements like ...

Utilizing Mantine dropzone in conjunction with React Hook Form within a Javascript environment

Can Mantine dropzone be used with React hook form in JavaScript? I am currently working on a modal Upload using Tailwind components like this import { useForm } from 'react-hook-form'; import { Group, Text, useMantineTheme } from '@mantine/c ...

Having trouble with Web API 2 not accepting JSON requests?

In the MVC Web API controller, there seems to be an issue with the JSON request parameter when it contains square brackets [ ]. The headers are set to accept application/json type. Sample Request Object Definition public class Sample { public int Id ...

Is it possible to set all UI forms to a readonly/disable mode?

We have a specific requirement where, if the user's access level is set to "READ ONLY", all form input elements should be made readonly. Our coding approach involves using a template HTML that contains widgets which are referenced in the correspondin ...

What is the process for incorporating the !important declaration into a CSS-in-JS (JSS) class attribute?

I'm currently exploring the use of CSS-in-JS classes from this specific response in conjunction with a Material UI component within my React project. In order to override the CSS set by Bootstrap, I've decided to utilize the !important modifier. ...

"Customizing FusionCharts: A step-by-step guide to changing the background color

Is there a way to modify the background color of fusionchart from white to black? Additionally, how can I change the font color in the chart? https://i.sstatic.net/MMuIq.png ...

Preventing long int types from being stored as strings in IndexedDB

The behavior of IndexedDB is causing some unexpected results. When attempting to store a long integer number, it is being stored as a string. This can cause issues with indexing and sorting the data. For instance: const data: { id: string, dateCreated ...

angularjs dynamically display expression based on controller value

I'm not the best at explaining things, so I hope you all can understand my needs and provide some assistance here. Below is a view using ng-repeat: <div ng-repeat="item in allitems"> {{displaydata}} </div> In my controller, I have the f ...

How can I customize the visibility toggles for the password input field in Angular Material?

Currently immersed in the Angular 15 migration process... Today, I encountered an issue with a password input that displays two eyes the first time something is entered in the field. The HTML code for this is as follows: <mat-form-field appearance=&qu ...

Each time I perform an INSERT operation, I momentarily lose the structure property of my datatable

gif image for reference https://i.sstatic.net/MiWL4.gif I encountered an issue when adding a new record to the data table. I have included a gif image for better understanding. Below is my display function: function display_record() { table = $(&apo ...

Using the Croppie plugin to crop an image before uploading via jQuery Ajax in PHP

I've successfully implemented a code snippet that allows image cropping using PHP, jQuery, and Ajax with the Croppie plugin. Currently, I'm facing an issue while trying to include additional input values along with the image upload process. I ...

What is preventing my Three.js object from responding to my commands to move?

I'm currently working on a three.js project where I want to create a block that moves when different keys are pressed. I've managed to set up a functional event listener, used console.log() for checking purposes, and successfully moved the block ...

Analyzing the value of a tab with Protractor测试

Below is my HTML code showcasing a list of tabs: <mat-tab-group> <mat-tab label="A"> <app-A></app-A> </mat-tab> <mat-tab label="B"> <app-B></app-B> </mat ...

Tips on sending asynchronous requests to a PHP page using jQuery AJAX

As a newcomer to web development, I am working on creating a social networking website for a college project. One feature I want to implement is updating the message count in the menu every time there is a new message in the database for the user (similar ...

What is the best way to retrieve all the listed TV and film ratings in descending order? Using Django

Our Goal I aim to organize movies based on their star ratings and filter out those with ratings lower than a specified threshold. 2. Retrieve the IDs of Movies and TV shows mentioned in the view, fetch the data and score through URLs one by one. 3. Presen ...