简体   繁体   中英

Node.js Express POST only changed inputs to router

Here is the case - I have a node.js + Express app using MySQL database. I read data from a table (example Employee). I show the necessary data in a HTML form. So employee name, email, phone, address etc.

In the form the user can update all or selected fields and hit submit to update the record.

On update I call my router and read the form inputs using body-parser:

<form role="form" action="/employee/update" method="post">
    Name : <input type="text" name="ename"/>
    Email : <input type="email" name="empEmail"/>
    .
    .
    .
</form>

Now the user can either change all the inputs or just one. However when I do the sql update I only want to update the fields that were changed.

My Current Solution

What I do right now is that I have a hidden input in the form that stores the name of any input that was changed by the user. So on my public js file, the jquery code onchange of input, reads the "name" property of the changed input and creates a comma separated string which it then assigns to the hidden input as value.

So if the user changes the name and email, the hidden input will look like:

<input type="hidden" name="FormHiddenInput" value="ename,empEmail"/>

So when the user clicks submit, on my router I just do:

var fieldName = req.body.FormHiddenInput;

Then I split it and extract names of the individual fields that were change and perform req.body on them again.

This process works just fine but I do not like it. It takes too much code and for loops go through.

Is there another way I can only get the names of the inputs/textarea/select etc that were actually changed in the form directly in the router?

You should update the whole row. It reduces verbosity and complexity in your code and the overheads are negligible.

mysql UPDATE statement - overhead for same values?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM