What could be causing the form DOM object values to not update in this specific instance?

I'm currently using JavaScript to create a password checksum by utilizing the SubtleCrypto.digest() function. This function produces the result as a promise object, which is then fed into an inline function to convert the outcome to a text representation of the hexadecimal bytes. However, the issue arises when the inline text conversion function digToHex() fails to update the hidden fields within the DOM before being submitted to the server via a POST request.

The function is triggered through an onclick() event tied to the form's button. It captures the user's input password from the form and forwards it to the digestMsg() function to create the hash.

It should be noted that while I acknowledge the security concerns surrounding SHA-1, this is currently only a proof of concept.

Upon observing the output in the Chrome developer tools, across both the console and network tab, I noticed that the submitted values always end up as null. Even though the hash does seem to get generated by the digToHex() function (as shown by the value of chk.value in the console tab), the hidden fields don't get updated as expected. I've tried changing assignments and submitting the form inside and outside the digestMsg() promise handler context as seen in the code snippet below.

... (Code Snippet) ...

Uncommenting either of the two submit() lines only results in null values being received on the server, despite the correct values showing up in the console output of the Chrome developer tools. Further investigation into the network output tab of the developer tools confirms that only null values are being transmitted. Ideally, I should be seeing "opt" with a value of 3 and chk1 showing the hash value.

Below is the HTML code that triggers the JavaScript functionalities:

... (HTML Snippet) ...

Following additional tests conducted by Marius, it was found that the code does work correctly on a static HTML page. Therefore, the issue seems to be linked to how the HTML is being dynamically loaded for each form. The HTML for the main (parent) page is appended below:

... (Parent HTML Snippet) ...

Answer №1

Based on your code, it appears to be correct. I have taken your code, modified it slightly, and added some HTML elements for testing purposes. Ensure that the input fields are not disabled.

reinitialize();

function reinitialize() {
    var message = document.querySelector('#pwd1').value;

    // For testing purposes
    var option = document.querySelector('[name = "opt"]');
    var checkbox = document.querySelector('[name = "chk1"]');
    // For testing purposes

    digestMessage(message).then(result=>{
        var option = document.querySelector('[name = "opt"]');
        var checkbox = document.querySelector('[name = "chk1"]');
        option.value = 3;
        checkbox.value = convertToHex(result);

    console.log(option.value);
    console.log(checkbox.value);

    });

}

function convertToHex(buffer) {
    const bytes = new Uint8Array(buffer);
    const hexCodes = [...bytes].map(value => {
        const hexCode = value.toString(16);
        const paddedHexCode = hexCode.padStart(2, '0');
        return paddedHexCode;
    });
    return hexCodes.join('');
}

function digestMessage(message) {
    const encoder = new TextEncoder();
    const data = encoder.encode(message);
    return window.crypto.subtle.digest('SHA-1', data);
}
<input type="password" id="pwd1" value="test" />
<input type="text" name="opt" />
<input type="text" name="chk1" />

Answer №2

I have successfully discovered a solution!

Originally, I utilized querySelector() to grab a reference to the form object and then immediately submitted it after processing:

document.querySelector('form').submit();

However, the form was submitted with the "opt" value set to '0', the specific numeric value I had assigned. It seemed like this command was referencing the original unaltered form being submitted right away.

To troubleshoot this issue, I created a reference to the form within the digestMsg() handler prior to processing:

var formObj = document.querySelector('form');

After updating the form values, I finally submitted it using the newly created reference:

formObj.submit();

This time, the form was submitted with the correct updated values. The revised code (without the test alerts) now appears like this:

function reboot() {
    var msg = document.querySelector('#pwd1').value;
    digestMsg(msg).then(result=>{
        var formObj = document.querySelector('form');
        var opt = document.querySelector('[name = "opt"]');
        var chk = document.querySelector('[name = "chk1"]');
        opt.value = 3;
        chk.value = digToHex(result);
        formObj.submit();
    });
}

I'm curious to understand why the initial command referenced the original form and ignored the updated values. Both scenarios seem to follow the same steps - form loading, value updates, and form submission. Also, why did the original version work on a static HTML page but not with a dynamically loaded form? I would appreciate any insights on this matter.

Thank you for the valuable comments that assisted me in finding a resolution.

This serves as a proof of concept, and further testing and adjustments are necessary to achieve a fully functional form.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Collaborative spreadsheet feature within a browser-based software platform

I am using an Angular-based SPA for my web application. My goal is to be able to open an Excel file within the application itself. Currently, I have a menu button or link that is linked to a specific path, for example //192.168.10.10/sharedExcels/myExcel. ...

Guidance on establishing an Array data type for a field in GraphQL Type declarations

Hey there! Currently, I'm working on my Nodejs project and facing a little dilemma. Specifically, I am trying to specify the type for graphQL in the code snippet below. However, I seem to be struggling with defining a field that should have a Javascri ...

Include the array in the 'content' property of the CSS using Jquery

I need help formatting data in CSS. The code I have is as follows: if (ext){ switch (ext.toLowerCase()) { case 'doc': pos = 'doc'; break; case 'bmp': pos = 'bmp'; break; ...

Unshifting values in a JavaScript array only if they exist in another array

I have two arrays of objects - one containing selected data and the other containing general data that needs to be displayed General data for display const arr = [ { id: "1", name: "Skoda - Auto" }, { id: "2" ...

Troubleshooting the Expanded Row Problem in 'angular-ui-grid'

Following a recent update, the expanded row feature in Google Chrome (version 77) is not functioning correctly compared to version 76. Prior to the update, the expanded rows in 'angular-UI-grid' worked well on all browsers including Mozilla Firef ...

Implementing a Search Box feature in React-leaflet version 3.1.0

Struggling to incorporate a searchbox feature into my react app. Encountering the error message "Attempted import error: 'MapControl' is not exported from 'react-leaflet'" with the latest version of react-leaflet. import { MapContainer, ...

Increment field(s) conditionally while also performing an upsert operation in MongoDB

I need to perform an insert/update operation (upsert) on a document. In the snippet below, there is a syntactical error, but this is what I am attempting to achieve: $inc: { {type=="profileCompletion"?"profileCompletion":"matchNotification"}: 1}, If the ...

What are the steps for implementing responsive design animation in my particular scenario?

Can someone please help me with a strange bug in Chrome? I am trying to create a responsive design for my app. The width of the 'item' element should change based on the browser's width. It works fine when the page first loads in Chrome, b ...

The property this.props.Values is not defined

I'm facing an issue with a page. Specifically, I am working with the value: this.props.CategoriesList. This value represents a list of categories. The problem is that when I click on a button to navigate to the page where this value is used, it shows ...

Obtaining a string from the String prototype can be achieved by using

My goal is to create a custom log method for the String object that will print out the actual string value, but I'm facing some difficulties in getting it to work correctly. String.prototype.log = function() { console.log(this.valueOf()); } &apos ...

Display JSON on the screen so it can be easily copied and pasted

I have a unique challenge where I need to output some Javascript code on the browser screen for easy transfer to another program. Currently, I am utilizing JSON.stringify() from the json2.js library. However, this method is not correctly escaping characte ...

AngularJS synchronous $resource functionality allows for the ability to make parallel API

I'm facing a dilemma because I understand that Javascript isn't designed for synchronous work, especially in the case of AngularJS. However, I find myself in a situation where I require it. The main page on the "www" domain (built with AngularJS ...

Ways to determine if prototype methods vary

Is there a technique to verify if functions are distinct despite originating from the same prototype? I'm inquiring because I want to save functions in an array, and when attempting to delete one, it removes all functions due to sharing prototypes. ...

Error encountered: Parsing error in Typescript eslint - The use of the keyword 'import' is restricted

My CDK application is written in typescript. Running npm run eslint locally shows no errors. However, when the same command is executed in a GitLab pipeline, I encounter the following error: 1:1 error Parsing error: The keyword 'import' is r ...

position text to the right side of a slider gallery created with JavaScript

I'm currently utilizing a WordPress plugin known as Slideshow Gallery and I want to position the text below it to float next to the gallery on the right side. I've attempted the following: .bioText{ font-size: 14px; font-size: 1.428571429rem; ...

"Can you explain the concept of an undefined id in an AJAX request

Within my mongodb database, I have two Tables: GstState Store While working on my Store form, I encountered an issue where the JSON response was returning an undefined id when trying to select a state based on country via an ajax call to fetch GstStates ...

I'm encountering a RangeError in nextjs when trying to pass props to a child component

I'm a beginner with Next.js. I've been attempting to pass props to a child component that is a response from an API call. However, every time I try to add the props in the child component, I encounter a RangeError: Maximum call stack size exceed ...

Unlocking the Potential of NextJS with Dynamic Page Export - Say Goodbye to Static HTML!

I am attempting to export my NextJs project based on the official documentation provided. However, it seems that I can only export it into static HTML. Is there a way to export it into dynamic pages where user-submitted data is updated in real time, simil ...

Resolve the flexible width problem when inserting text in pptxgenjs

I am attempting to replicate a layout similar to this https://i.sstatic.net/HDUhV.png However, the text width is taking up more space than anticipated. https://i.sstatic.net/CnKIB.png The current text behavior resembles that of a div, but I would like ...

A problem arises when utilizing jQuery's $.isArray functionality

Successfully executing an AJAX post, the function test is utilized to process the passed data. $("#formID").submit(function (event) { $('#postError').html('').hide(); $('#postInfo').html('loading results').s ...