Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

340
Views
How to pass variable from webpage javascript to node JS

I have a variable in Javascript that I'm trying to pass to node js so that it can be put in a JSON file but it is not writing to the file. I think have made a mistake in either the AJAX Post request or in the node JS routing.

The javascript running on a HTML page

   function WriteToJSON() {
    var floors = document.getElementById("floor-number").value;
    $.ajax({
        type: "POST",
        url: "http://localhost:8080/getfloors",
        dataType :"text",
        data: {Floors: floors},
    })
    }

The Node JS

var http = require('http');
var fs = require('fs');
var url = require('url');
const path = require('path');
var express = require('express');
var serveStatic = require('serve-static');
const { Router } = require('express');
const app = express();
var bodyParser = require('body-parser')
const port = process.env.PORT || 8080;

 app.get("/", function(req, res) {
   res.sendFile(path.join(__dirname, '/welcome-page.html'))
 })

 app.get("/Question-1", function(req, res) {
  res.sendFile(path.join(__dirname, '/Question-1.html'))
})

app.post("/getfloors", (req, res) => {
  var floors = req.body.Floors;
  console.log(floors);
  fs.writeFileSync('Data.json', floors);
})

app.listen(8080);
about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

Is there a reason why you are using AJAX instead of the fetch method?

Try this solution (note, that I've used async function):

async function WriteToJSON() {
    const floors = document.getElementById("floor-number").value;

    const body = new URLSearchParams();
    body.append("Floors", floors);
    
    const response = await fetch('http://localhost:8080/getfloors', { method: 'POST', body });
}
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!