Transferring a uint8clampedarray Array to C# using JavaScript via ajax after extracting getImageData from the Canvas

Currently, I am facing an issue while attempting to create a signature using client-side javaScript and then forwarding the result to the back-end (c#) via ajax. The array I am trying to transmit is of the type uint8clampedarray, but unfortunately, the SetSignature method in the code behind is not being triggered, even though the Page Load method is working as expected.

Client-side javaScript

var signatureByteArray = signature.getSignatureImage();
SendArrayViaAjax(signatureByteArray);

function getSignatureImage() {
    return ctx.getImageData(0, 0, canvas.width, canvas.height).data;
}

function SendArrayViaAjax(signatureArray) {
    var sigArray = JSON.stringify(signatureArray);
        $.ajax({
            type: "POST",
            data: { array: sigArray },
            dataType: "json",
            contentType: "application/json; charset=utf-8",
            url: "/Intranet/OHS/SOP/SOPSignOffs.aspx/SetSignature",
            success: function (msg) {
                alert(msg.d + "success");
            },
            error: function (response) {
                alert("an error has occurred");
            }
    });
}

Code behind

[WebMethod]
public static string SetSignature(string[] array)
{
    var x = array[2];
    return "success";
}

My question lies in how I can transmit the array directly as uint8clampedarray through ajax and how it can be retrieved in c#. Alternatively, is there a more efficient approach?

ctx = canvas.getContext("2d");` 

This code snippet depicts how I am obtaining the Canvas element. Whilst the signature generation process is functioning properly, the challenge lies in sending it back to C#.

Answer №1

I came up with a solution by changing the way the canvas image data is generated (old method).

New Image Generation Method

function getSignatureImage() {
    //return ctx.getImageData(0, 0, canvas.width, canvas.height).data;
    var pic = canvas.toDataURL("image/png");
    pic = pic.replace(/^data:image\/(png|jpg);base64,/, "")
    return pic;
} 

Next, in the ajax call

$.ajax({
    type: "POST",
    data: '{"imageData" : "'+ signatureImage + '" }',
    ....

Lastly, in the backend code

public static string SetSignature(string imageData)
{
    string filePath = HttpContext.Current.Server.MapPath("Signature.png");
    using (FileStream fs = new FileStream(filePath, FileMode.Create))
    {
        using (BinaryWriter bw = new BinaryWriter(fs))
        {
            byte[] data = Convert.FromBase64String(imageData);
            bw.Write(data);
            bw.Close();
        }
    }
}

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

Error: Unable to retrieve data due to null value (property 'detail' is undefined)

When I use useEffect() function to set the document title to 'View Orders | Bothub' and fetch data from a backend URL, I encounter an error. The error message reads: Unhandled Rejection (TypeError): Cannot read properties of null (reading 'd ...

Including input within a component causes the input to capture all click events

I've been working on a project where I need to create a color picker component. When you click on the .swatch element, a popover opens up with a .cover div that covers the whole screen. Clicking on the cover closes the popover, following standard beha ...

Data retrieval on dashboard through ajax is not functioning properly

I have a dashboard with a partial view called SIM Balance. This view is intended to display the number of SIM cards issued to users on a daily basis. I have configured the controller as follows: public function actionSimbalance() { // SQL query to fe ...

What could be causing the readTextFile function to return undefined?

var XMLHttpRequest = require("xmlhttprequest").XMLHttpRequest; function readFile(file) { let fileContents = new XMLHttpRequest(); fileContents.open("GET", file, false); fileContents.onreadystatechange = function () { ...

Is there a way to display one of the divs in sequence each time the page is reloaded?

Is there a way to display the divs sequentially when the page is refreshed? For instance, on the initial load, only div 1 should appear, and with each refresh it should cycle through divs 2, 3, 4, and 5 before starting over. Below is an example I'm c ...

Optimizing the JSON date structure

After receiving a datetime value in JSON with the format: Created "/Date(1335232596000)/" I developed a JavaScript function to display this value on the front end. Here's the code snippet: return new Date(parseInt(date.substr(6))); However, the c ...

ES6 Promises have a curious ability to accurately retrieve values from custom JavaScript objects

I have developed a unique library that functions independently from the Promise API, yet achieves similar objectives. It utilizes window.requestAnimationFrame and fallbacks to setTimeout, having no similarities with Promises. Interestingly, it is compatibl ...

Capture the current state of a page in Next.js

As I develop my Next.js application, I've encountered an architectural challenge. I'm looking to switch between routes while maintaining the state of each page so that I can return without losing any data. While initialProps might work for simple ...

Eliminate parameter from URL

Here is the URL I am working with: http://my.site/?code=74e30ef2-109c-4b75-b8d6-89bdce1aa860 My goal is to redirect to this URL: http://my.site#/homepage To achieve this, I use the following code snippet: import { push } from 'react-router-redux& ...

Recording JavaScript Cookie Visit Counts and Tracking Last Login Dates

I am a beginner in JavaScript and cookies, and I am attempting to create a cookie that can show the number of times someone has visited a website, the date of their last visit, and the expiration date of the cookie. Initially, I tried modifying code from ...

Tips for accessing user input in JavaScript functions

In my ASP.NET code, I have created a dynamic image button and panel. Here is the code: Panel panBlocks = new Panel(); panBlocks.ID = "PanBlockQuestionID" + recordcount.ToString(); panBlocks.Width = 1300; panBlocks.Height = 50; panBlocks.BackColor = Color. ...

Encountering an error: "Unable to assign the 'id' property to an undefined object while attempting to retrieve it"

I'm running into an issue while attempting to retrieve a specific user from Firebase's Firestore. export class TaskService { tasksCollection: AngularFirestoreCollection<Task>; taskDoc: AngularFirestoreDocument<Task>; tasks: Obs ...

When querying a MongoDB object in Node.js, the inner value may sometimes return as undefined

After retrieving a store object from MongoDB, my focus shifted to utilizing the value stored in store.comments. Upon logging the store value, here is what I found: store:{ _id: 57e246f73e63d635cce3d174, __v: 0, comments: 57e246f73e63d635cce3d177, l ...

How to retrieve the value of an observable from a regular JavaScript array in Knockout JS?

Context In my project, I am working with a plain JavaScript array that starts off empty but gets populated with Knockout observables later on. These values are numbers and I need to compare them with values in another Knockout observable array. The issue ...

Is there a way to retrieve the current state of a Material UI component in a React functional component without needing to trigger an event by clicking on

Seeking a way to retrieve current values of Material Ui components without the need to click on any event after page reloads or DOM changes. These values are pulled from a database. My goal is to confirm whether the values have been updated or not by chec ...

Tips for adjusting the order in which styles load in NuxtJS

I need to adjust the loading order of styles in my current project. In my custom stylesheet style.css, I've made some overrides, body { font-family: "Lato", sans-serif; font-size: 14px; font-weight: 400; font-style: normal; ...

Generate a dynamic vertical line that glides smoothly over the webpage, gradually shifting from one end to the other within a set duration using javascript

I have designed a calendar timeline using html. My goal is to implement a vertical line that moves from left to right as time progresses, overlaying all other html elements. This functionality is similar to Google Calendar's way of indicating the curr ...

I receive an [object HTMLCollection] as the output

I am currently working on recreating a login page and I want it so that when the button is clicked, it displays the name you entered, but instead, it returns [object HTMLCollection]. My expectation was to have the name displayed as entered. var nombre ...

Putting together Modular Client-side JavaScript

Is there a way in Node.js to dynamically "require()" javascript files similar to PHP's require function? It would be great to use this feature in my client-side code for development purposes without actually calling a specific javascript function. Rat ...

Encountering issues with Visual Studio Code following the integration of the MongoDB API Mongoose into my code

As I delve into the world of web development, I have been exploring databases with MongoDB Atlas and mongoose. Interestingly, my debugging process has hit a bump when using the node.js(legacy) debugger in VS code after importing mongoose with const mongoos ...