0

I'm making a simple server to send data to a .json file and receive that data from another page but I have problem how to store data in .json file

I used following code but it didn't work

<script src="jquery/jquery-3.4.1.min.js"></script>

<script>

     var _lname = "x";
    var _fname = "y";
    var _mname = "x";
      $.ajax({
                type: "POST",
                url: "data.json",
                data: "{'lastName':'" + _lname + "','firstName':'" + _fname + "','middleName':'" + _mname + "'}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function () {
                    }
                });

</script>
Alex
  • 878
  • 1
  • 10
  • 25
MRE
  • 37
  • 7

2 Answers2

1

Simply POSTing data to a JSON file won't work, as sending a POST request requires the server to listen for requests and do something with the payload you sent. You could make a simple NodeJS or PHP script (or any other server-side language for that matter) that could handle saving the payload to a JSON-file.

Fdebijl
  • 887
  • 5
  • 20
0

When you make a POST request, you send data to a web server.

The web server can do something with the data in the POST request.

By default, it does nothing. Imagine the problems that would be caused if anybody could make a POST request to anyone else's web server and write a new file to it. Google's homepage would be defaced every other second.

If you want to store the results of a POST request, then you need to write server-side code to do it (and you almost certainly will want to perform authentication and authorisation when you do so).


Note that the value of data: in your example code will never be valid JSON. Don't try to write JSON by mashing strings together. Use a library function like JSON.stringify.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • you mean json is a method to help you send your data to server side easier – MRE Jun 06 '19 at 12:06
  • @Programmer — I didn't say that. JSON is just a data format. It is irrelevant to your problem. – Quentin Jun 06 '19 at 12:07
  • i don't say data format , i mean a way to send data to server side – MRE Jun 06 '19 at 12:16
  • 1
    @Programmer — JSON is a data format even if you say it is not. The problem "servers won't write just anything you send them to arbitrary files selected by the client" is going to remain the same no matter what data format you use. Therefore your choice of data format is irrelevant to the problem. – Quentin Jun 06 '19 at 12:17