0

I have created a html page having a form and what I need is to take user input and save it in a json file, and I have messed up thing!..

I have used express module to create a server. I messed up all the things in my mind together like ajax and node js and p5.js all these...

lets see my code:

var express = require('express');
var app = express();
var server = app.listen(3000);
app.use(express.static('public'));
console.log('Server Running... at:\nhttp://localhost:3000/  or,\nhttp://127.0.0.1:3000/\nPress ctrl+c to quit!\n');

var fs = require('fs');
var data = fs.readFileSync('public/json/receive.json');
var allForms = JSON.parse(data);
console.log(allForms);

// here in server i need the raw object, to process the file with raw object's dara...
//console.log('raw: ' + raw)

//allForms = allForms + raw

//data = JSON.stringify(allForms, null, 2)
//fs.writeFile('public/json/receiving.json', data, log);
//function log(end) {
//  console.log('File is successfully saved!')
//}
<form method="POST" onsubmit="return put_json(this);">
  <label style="margin-left: 6em;"> M/s: </label>
  <input type="text" name="company" style="margin-left: 7em;" />
  <label style="margin-left: 17.7em;"> Part Number: </label>
  <input type="text" name="part_no" style="margin-left: 3.4em;" />
  <br>
  <hr width="80%" align="center" color="#0070d6">

  <label style="margin-left: 6em;"> Receiving Date: </label>
  <input type="Date" name="date" style="margin-left: 0em;" />
  <label style="margin-left: 17.5em;"> Quantity(Meter): </label>
  <input type="Number" name="quantity_meter" value="0" style="margin-left: 1em;" />
  <br>
  <hr width="80%" align="center" color="#0070d6">

  <label style="margin-left: 6em;"> Amount Paid: </label>
  <input type="Number" name="amt_paid" value="0" style="margin-left: 1.8em;" />
  <label style="margin-left: 17.5em;"> Status: </label>
  <input type="text" name="status" value="Pending!" style="margin-left: 8em;" />
  <br>
  <hr width="80%" align="center" color="#0070d6">

  <label style="margin-left: 6em;"> Vehicle Name: </label>
  <input type="text" name="vehicle_name" style="margin-left: 1em;" />
  <label style="margin-left: 17.4em;"> Vehicle Number: </label>
  <input type="text" name="vehicle_no" style="margin-left: 1.5em;" />
  <br>
  <hr width="80%" align="center" color="#0070d6">

  <label style="margin-left: 6em;"> Add Notes: </label>
  <textarea name="notes" style="margin-left: 2.7em;">(If Any..)</textarea>
  <br>

  <input id="submit" type="submit" value="Save" style="margin-left: 75em;" />
</form>
<script>
  function requestHandler(data) {
    var Request = new XMLHttpRequest();
    var url = '/server.js';
    Request.open('POST', url, true);
    Request.onreadystatechange = sendData(Request, data);
  }

  function sendData(rqst, DATA) {
    if (rqst.readyState == 4 && rqst.status == 200) {
      alert('Sending Data To Server ...');
      packet = JSON.stringify(DATA, 0, 4);
      console.log('packet: ' + packet);
      rqst.send(packet);
    } else {
      alert('Connection FAIL,\nCheck connection and Retry !!!');
      console.log(rqst);
    }
  }


  var raw;

  function put_json(form) {
    raw = {
      'company': form.company.value,
      'part_no': form.part_no.value,
      'date': form.date.value,
      'quantity_meter': form.quantity_meter.value,
      'amt_paid': form.amt_paid.value,
      'status': form.status.value,
      'vehicle_name': form.vehicle_name.value,
      'vehicle_no': form.vehicle_no.value,
      'notes': form.notes.value
    }
    console.log('raw: ' + raw);

    requestHandler(raw);

    return false;
  }
</script>

And I want to save it in a json file like:

{ "company": "xyzcomp.", "part_no": "xyz001", "date": "01/01/18", "quantity_meter": "0", "amt_paid": "000", "status": "Pending!", "vehicle_name": "farrari", "vehicle_no": "xyxyxyxyxyx", "notes": "problem in saving data!!!" }

NOW: i have created html form connect it with client.js and then connect them with server.js ok... but i can retrieve form data values inside client script and i can save the data through server side, and i don't know how to send client object raw = {...} to server programme how to retrieve the data in server so i am messed with all this cluster... is there anyone who can help!

5
  • 3
    So... uhm... Where's the node.js server that would handle this request? Commented Feb 9, 2018 at 18:43
  • @KevinB i am writing the server side code but don't know what to do in that i mean i am confused that does it needs something called socket to handle the request? sorry dear but i am just a newbie for the server and client side requests.. do u please help me writing the server side script!! Commented Feb 9, 2018 at 18:51
  • 1
    you wouldn't need socket.io to handle a post request that writes a file to a folder. Commented Feb 9, 2018 at 18:52
  • @kevinB i have posted my server.js now and corrected all the mistakes in the post. Please re-read all the stuff to be clear what the problem is and help the project :-) Commented Feb 10, 2018 at 6:37
  • is there anyone who can help !... Commented Feb 10, 2018 at 14:57

2 Answers 2

3

Firstly understand

A new XMLHttpRequest object starts in state 0

When you successfully call .open() on the obect, the status changes to 1

When you successfully call .send() on the object, an HTTP request goes off to the server defined in .open(). Once the HTTP response headers have been received and processed the status changes to 2

Eventually, the actual content of the response from the server will start coming in. When this begins, the status changes to 3

Finally, once all of the content is downloaded and is ready to be used, the status changes to 4

There are missing pieces as per what I see: in your client side

var Request = new XMLHttpRequest();
    function requestHandler(data) {
        var url = '/server.js';
        Request.open('POST', url, true);
        Request.onreadystatechange = sendData;
        Request.send(data);
    /*unless .send() is called, nothing moves forward..there will be no communication between the client and server,so here it also means when the request ready state changes from 1 to 2 , call sendData, similarly when it goes from 2 to 3 call sendData, and similarly for 3 to 4 , unless you dont call Request.send how will the readystate change, if readystate is not changing why will sendData be called at all.*/
      } 
       function sendData() {
        /*4 means request is complete , if you don't call `Request.send(data)` like I have in the previous function, in the line above ,then it means you have not even started the request (which is 1), if 1 is not even reached in the ready state, how can you check for 4 or for status 200. You must send first , so that ready state changes and sendData is called*/
        if (Request.readyState == 4 && Request.status == 200) {
          alert('Data sent ...');
        } else {
          alert('Connection FAIL,\nCheck connection and Retry !!!');
          console.log(Request);
        }
      }

in your server side code.You are submitting to url /server.js But in your server side code you do not have a handler, moreover you are issuing a POST request, which is good. In your server what you need to add is

app.js

var express = require('express');
var app = express();
app.listen(3000);
app.use(express.static('public'));
console.log('Server Running... at:\nhttp://localhost:3000/  or,\nhttp://127.0.0.1:3000/\nPress ctrl+c to quit!\n');
//let's say we make a file to handle this request
const serverRouteHandler = require("./serverRouteHandler")
app.use('/server.js',serverRouteHandler)

serverRouteHandler.js

const router = require('express').Router();
router.post('/',function(req,res){
  const rawBodyFromClient = req.body
  console.log(JSON.stringify(rawBodyFromClient,null,2))//this will print the JSON to your server console, not the stringify here is just for representational purposes.
 res.send()//do not forget this line, if you miss this then it means on your client side the readyState will never reach 4 and will be stuck at 3 and you will get a blank HTTP status coz your request never completed in the first place.
})
module.exports = router;

Here I am assuming for brevity that your app.js and serverRouteHandler.js are in same directory. If you want to monitor the progress of your request I suggest you take a look at this article. https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest#Monitoring_progress

Sign up to request clarification or add additional context in comments.

4 Comments

Thank you very much @sidd.rc to make me correct, i will do the recommended changes to the file.. :-)
If i am not wrong, I think you forgot to write termination sign ( ; ) at the end some statements....
yes, the code is just for your idea, you can add ; on your own .. :)
made a few more, ready-to-go changes..sorry for that...it's been quite a while since I used this method of doing ajax...btw you should resort to using some library to implement ajax, we do not use XmlHttpRequest object anymore to do ajax, it's always some library like Angular or jQuery or Fetch etc...
2

please use this function if you just want to write your json in a text file. this will work for sure.

function saveFile(text, name, type) {
    var a = document.createElement("a");
    var file = new Blob([text], {type: type});
    a.href = URL.createObjectURL(file);
    a.download = name;
    a.click();
}

 saveFile(JSON.stringify(jsonData), 'test.txt', 'text/plain');

1 Comment

sorry @Negi_Rox but yesterday i was not cleared with all the stuff. Please re-read the post to help in resolving the problem!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.