CIOC
CIOC

Reputation: 1427

Pass variables from JavaScript to Node.js

I have a simple HTML like this:

<html>
    <head><title></title></head>
    <body>
        <script>var testVariable = "Hello"</script>

        <form method="post" action="/">
            <input type="submit" name="submit" value="Submit">
        </form>
    </body>
</html>

And my Node.js looks like this:

app.post('/', function(req, res) {
    Console.log(req.body.testVariable);
});

What I need to do is when the form is submitted the testVariable needs to be passed to the Node.js function, I'm trying with hidden fields but I'm still having problems with that, i.e:

<input type="hidden" name="chat" value="<script>testVariable</script>">

But as you can imagine it pass all the script as a string, and not the value of the variable.

Does someone knows how to do that? Sorry if this is a silly question, I'm new to JavaScript and Node.js in general and I can't find answers in Google.

Thanks.

-----EDIT------

My form now looks like this:

<form method="post" action="/">
    <input type="hidden" name="chat" id="hiddenInput" />

    <script>
        var input = document.getElementById('hiddenInput');
        input.value = $('#conversation');
    </script>

    <input type="submit" name="submit" value="Submit">
</form>

And on my Node.js I'm printing the object like this:

console.log(JSON.stringify(req.body.chat));

and it prints "[object Object]" (including the quotes).

I verified that the variable received is a string with:

console.log(typeof req.body.chat);  // prints "string"

Upvotes: 2

Views: 7928

Answers (2)

Jordan Foreman
Jordan Foreman

Reputation: 3888

Use javascript to target the hidden input and set the value before submitting the form:

HTML

<input type="hidden" name="chat" id="hiddenInput" />

JS

var input = document.getElementById('hiddenInput');
input.value = testVariable.toString();

Also, on your Node server, you need to access req.body.chat - the body property you want corresponds to the name of the input element

Upvotes: 4

Sergio
Sergio

Reputation: 28845

You need to use the input name attribute. And that input must be inside the form so you can catch it in Node:

<input type="hidden" name="testVariable" value="the value string">

Try:

    <form method="post" action="/">
        <input type="hidden" name="testVariable" value="the value string">
        <input type="submit" name="submit" value="Submit">
    </form>

And it should log "the value string" in Node.

Upvotes: 1

Related Questions