user1584421
user1584421

Reputation: 3843

Node.js : Make a response on the same page (update the page)

I have this scenario: The client submits a form. The node.js "catches" the form submission with its appropriate route and starts a slow computation. The computation creates some data that have to be passed to the client.

Here i have the option of doing a res.render() and render a new html file to the client.

What if i want to make the data (string or array of strings) visible to the client on the same page?

Can i somehow do this with res.json()? If yes, how will the structure of the code look like, both in client and server side?

Upvotes: 1

Views: 2439

Answers (1)

t hj
t hj

Reputation: 93

  • Client side (jquery)
$(".submit").click(function(){
    var status = "submit";
    var userObject= {
        firstName: "<%= ['firstName'] %>",
        lastName: "<%= ['lastName'] %>",
        subject: "<%= ['subject'] %>"
    }
    $.ajax({
        url: "http://localhost:3000/yourUrl",
        type: "POST",
        data: JSON.stringify({status:status, userObject:userObject}),
        dataType: "json",
        contentType: "application/json",
        success: function(result){
            alert(result.status);
        },
        error: function(result){
            alert("error");
        }
    })
})
  • Server side (node.js)
app.post("/yourURL", function(req,res){

    console.log("working")

    var status = JSON.stringify({
        status: req.body.status,
        userObject: req.body.userObject
    })

    console.log("status: " + req.body.status)

    const options = {
        hostname: "localhost",
        port: 3000,
        path: '/postWhichRenderthePage',
        method: 'POST',
        headers: {
            'content-type': 'application/json',
            'accept': 'application/json'
        }
    };

    console.log(status);

    const reqs = http.request(options, (res) => {
        res.setEncoding('utf8');
        res.on('data', (chunk) => {
            console.log(`BODY: ${chunk}`);
        });
        res.on('end', () => {
            console.log('No more data in response.');
        });
    });

    reqs.on('error', (e) => {
        console.error(`problem with request: ${e.message}`);
    });

    // write data to request body
    reqs.write(status);
    reqs.end();
    res.status(200).send(JSON.stringify({status: req.body.status}));
})

For your reference of how to use ajax https://www.w3schools.com/xml/ajax_xmlhttprequest_response.asp

Upvotes: 1

Related Questions