user4185843
user4185843

Reputation:

Adding Datas via Javascript to existing JSON file on Server

I have following problem. I know that this is discussed quiet often, and i tried a lot of possibilities, but none is working up to now.

I have some datas in my javascript file, which i want to add to a already exsiting .json file on my server. I tried to do it the following way, but whenever i open the .json file after calling ajax_get_json(), no new datas are 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);

}

My myjson.json File has following structure:

{ "participant":[
{"user":"Steven", "message":" Hey,i m in!"}, 
{"user":"Tim", "message":" i wrote sth."},
{"user":"lukas", "message":"example"}
]}     

Does anyone have an Idea what the problem yould be or is there a better way doing it?

Thanks in advance!

Upvotes: 1

Views: 509

Answers (1)

Matti Mehtonen
Matti Mehtonen

Reputation: 1705

With javascript on client it's not possible to write JSON on server. If that would be possible, that would be kind of bad from the security perspective. You need to write JSON on server with what ever language you are using there (PHP, Java, javaScript). Then you call that server function from client with AJAX for example. It could go like this:

  1. Javascript on client side request for example url www.yourserver.com/writejson.php?u=steven&m=Hi

  2. On server you catch that request and write to JSON file. username is steven and message is Hi.

By the way, you have misunderstood XMLHttpRequest.send method. You are not sending data to be saved on server. You are firing XMLHttpRequest. Here is walkthrough how your code is executed:

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 is called every time XMLHttpRequest state changes
    var obj = JSON.parse(hr.responseText); // 9. this is called when XMLHttpRequest is completed and response is gotten
    obj['participant'].push({"user": us, "message": msg}); // 10.
    var sendingObj =JSON.stringify(obj); // 11.
    }
}
hr.send (sendingObj); // 7. sendingObj is undefined

Upvotes: 1

Related Questions