How to save JSON Data to a file using fetch() api?


Joined
Apr 28, 2022
Messages
2
Reaction score
0
index.html file placed in a folder and same folder has save.json file. Im running sublime text with server extension.

Console Error: save.json 404 not found.

It can read from the same file but 404 when trying to write !


HTML:
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
</head>

<body>
<div id="hide" style="display:none;">
<p id="title">111</p>
<p id="body">222</p>
<p id="userid">333</p>
</div>

<script>

var OBJ = {

title: document.getElementById("title").innerHTML,
body: document.getElementById("body").innerHTML,
userId:  document.getElementById("userid").innerHTML,

};

fetch('/save.json', {
  method: 'POST',
  body: JSON.stringify(OBJ),
  headers: {
    'Content-type': 'application/json; charset=UTF-8',
  },
})
  .then((response) => response.json())
  .then((json) => console.log(json));



</script>
</body>

</html>
 
Ad

Advertisements

Ad

Advertisements

Joined
Mar 11, 2022
Messages
181
Reaction score
24
im doing this for many years now, but i never heard of "writing with pure Javascript". I maybe missed this. But it would be a horrible game if that's actually possible. But as i've mentioned. Maybe i missed that.

So the only way i know to write (into a file e..g. mynewfile.something) is using ajax and a server language.
Or are you talking about "write" according to "write out, splash of just innerHTML =").

You include Jquery. Well i don't work with JQ because i hate it. But maybe there is some "AJAX Write to server" stuff on board that im not aware of. If so, im pretty sure it needs a serverside script file on your server to work with. As i said. I have no clue.

Come back to me if you're good with a AJAX to serverfile.php solution. I can help you with that.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top