0

I have an Object into a .json file and it includes just an Array.

Now I would like to get a word from the user using prompt, and add it to this Array; you can see the codes below :

function addWord() {
    let myWords = getWords();
    let newWord = prompt("What word would you like to be added to your list?", "");
    myWords.push(newWord);
    let myWordsJson = JSON.stringify(myWords);
    let xhr2 = new XMLHttpRequest();
    xhr2.open("GET", "words.json?wordsArray=" + myWordsJson);
    xhr2.send();
}

And here is 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 debugged my code and there is no problem with receiving the Array from the server and adding the new word, but then I can not send the new Array to the words.json file.

here is words.json :

{"wordsArray" : ["hello", "pencil", "school", "tooth", "family", "class"]}
Amir7
  • 32
  • 8
  • What do you mean by cannot send the new array to the file? Do you own the backend that handles these requests? What does it do with your GET request? – tomerpacific May 01 '20 at 12:53
  • 1
    Are you trying to edit a file on the server using a simple GET request ? If the server doesn't provide capabilities for you to edit such file it is impossible – Rainbow May 01 '20 at 12:54
  • how can I handle that? is WebApi a good choice? – Amir7 May 01 '20 at 13:08

1 Answers1

-1

we have to push single single word into the array

 let newWord = "What word would you like to be added to your list?";
 myWords['wordsArray'].push(newWord);

or if we have another array of words to be pushed we can use a for loop to as shown below

 let newWord = ["What word would you like to be added to your list?"];
         
      for(let i = 0; i < newWord.length ; i++) {   
         myWords['wordsArray'].push(newWord[i]);
         }