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!