Skip to content

Mohcin Bounouara

Thoughts about software engineering and life

Handling Multiple Forms with Different Field Names Using a Single Endpoint

The Problem:

Suppose you have an endpoint to send data to the database, and in your project, you have two forms with the same field(s), let’s say a field named “name”. How can you manage this without creating redundant and complex code?

The Initial Solution:

A quick solution might be to create two separate forms and duplicate the endpoint POST call. For example, you would have ‘/save-name‘ and ‘/save-name-2‘.

While this works, it’s not clean and leads to code redundancy and complexity.

The Clean Solution:

You can use a single endpoint ‘/save-name‘ that expects the “name” field and create two HTML forms with different field names. Then, transform the data in your frontend before sending it to the endpoint.

HTML Forms:

<form id="name-form-1">
    <input type="text" name="name" id="name">
    <button type="submit">Save Name</button>
</form>

<form id="name-form-2">
    <input type="text" name="name_2" id="name_2">
    <button type="submit">Save Name 2</button>
</form>

Javascript:

I will use jQuery, you can use any JS framework or even Vanilla JS.

function saveTheName() {
    jQuery('#name-form-1').on('submit', function (e) {
        e.preventDefault();

        let formData = jQuery(this).serializeArray();
        let data = {};
        formData.forEach(function (item) {
            data[item.name] = item.value;
        });

        jQuery.post('/save-name', data, function (response) {
            if (response === 'OK') {
                alert('Name saved!');
            } else {
                alert('There were errors with the submission.');
            }
        }).fail(function () {
            alert('Submission failed.');
        });
    });

    jQuery('#name-form-2').on('submit', function (e) {
        e.preventDefault();

        let formData = jQuery(this).serializeArray();
        let data = {};
        formData.forEach(function (item) {
            if (item.name === 'name_2') {
                data.name = item.value; // Map name_2 to name
            } else {
                data[item.name] = item.value;
            }
        });

        jQuery.post('/save-name', data, function (response) {
            if (response === 'OK') {
                alert('Name saved!');
            } else {
                alert('There were errors with the submission.');
            }
        }).fail(function () {
            alert('Submission failed.');
        });
    });
}

saveTheName();

So by doing this approach you will have a clean code and easy-to-change.

Hope this help 🙂