What is the best way to transfer JSON objects from JavaScript to a C# server?

Can JSON objects be sent from JavaScript to a C# server using a Peer to Peer network? Is there an alternative method for sending data in real-time to a C# server? Below are the functions from my JavaScript code:

Peer To Peer Code

function establishPeerServer(evt) {
    console.log('Creating new peer server');
    createNewPeer = true;
    evt.preventDefault();
    myPeerId = document.getElementById('newpeerid').value;
    var peerNetTemp = document.getElementById('peernet').value;
    peerNet = JSON.parse(peerNetTemp);

    // Destroy default peer before creating a new one
    peer.disconnect();
    peer.destroy();

    // Show new peer credentials. Hide default IP address
    document.getElementById("connectionopen").style.display = 'none';
    document.getElementById("newpeercreated").style.display = 'block';
}

function sendToPeer(evt, data) {
    var dataToSend = {"event": evt, "data": data};
    peer_connections.forEach(function(connection) {
        connection.send(dataToSend);
    });
}

Skeleton Tracking Code

function initializeSkeletonTracking() {
    console.log('Initiating skeleton tracking');

    var skeletonCanvas = document.getElementById('skeleton-canvas');
    var skeletonContext = skeletonCanvas.getContext('2d');

    resetCanvas('depth');
    canvasState = 'depth';

    if(kinect.open()) {
        kinect.on('bodyFrame', function(bodyFrame){
            if(sendAllBodies) {
                sendToPeer('bodyFrame', bodyFrame);
                if (doRecord) {
                    bodyFrame.record_startime = recordStartTime;
                    bodyFrame.record_timestamp = Date.now() - recordStartTime;
                    bodyChunks.push(bodyFrame);
                }
            }
        });
        kinect.openBodyReader();
    }
}

Answer №1

To simplify the process, you can utilize ajax in conjunction with jQuery:

$.ajax({
    type: 'POST',
    url: 'insert-your-url-to-csharp-method-here',
    data: {
        id: 3,
        name: 'Jeff',
        age: 33
    },
    success: function(result) {
        console.log(result);
    }
});

While there are alternative methods for transmitting data (like websockets), AJAX remains a straightforward option for sending JSON to a server.

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

Can anyone explain how to pass a toggle state along with its onChange function in Ionic React?

Imagine I have this toggle element: <IonToggle id="IonToggleDarkMode" slot="end" checked={vars.darkMode} onChange={darkModeToggle}></IonToggle> The value of vars.darkMode represents the current state of the toggle, which is ...

Modify the state's value by updating it when your information is stored in an array

I am currently working with contact numbers stored in an array and utilizing native-base for data viewing. this.state = { leadProfile: { contactNumber: [ { "lead_contact_number": "0912 312 412312", "lead_contact_nu ...

Can MSTest be executed on a remote server without the need to install Visual Studio 2013 or Visual Studio 2015?

Currently, I have a C# and Selenium automation test project that I would like to run using MSTest on a remote server. This will allow me to seamlessly integrate it with my CI server to ensure that the tests run after each new change is submitted. Since I a ...

Set Covering: Identify an array combination that intersects with all elements of a specified target array

Suppose there is an array, A, which can be sorted if that information helps. We have multiple arrays, B, C, D, etc., all sortable and potentially overlapping with array A. The objective is to identify the smallest combination of arrays B, C, D, etc., whi ...

Troubleshooting: React Testing Library Issue with Updating Material UI DatePicker Input Content

I'm attempting to update the value of the Material UI Datepicker Input using React Testing Library. Unfortunately, I have not been successful with the fireEvent.change() method. import React from "react"; import { render, screen, waitFor, fi ...

Using ReactJS and Electron to run a function that is passed as a string variable

Imagine having a variable called foo='someFunc' and being able to call someFunc() afterwards. If you're interested, there is an article discussing how to achieve this in pure javascript here. Unfortunately, I'm facing challenges achie ...

"Exploring the world of digital art with JavaScript through canvas and canvas

How can I adjust the value of a canvas arc? The input accepts larger values, but not smaller ones. var btn = document.querySelector(".btn"); btn.addEventListener("click", () => { var inputVal = document.querySelector(&q ...

Issue with ASP.NET MVC Attribute Routing: parameter is consistently returning null

Recently, I encountered a specific issue. Consider the controller below with a GET method: [RoutePrefix("admin-panel")] public class AdminPanelController : Controller { [Route("places/edit/{placeId}")] public ActionResult EditPlace(int? placeId) ...

Issue with firing the React-Redux action has been encountered

I am currently utilizing React along with react-redux, redux and redux-actions. Within my application, I have a specific action that is responsible for verifying the validity of the token stored in localStorage to ensure it is not expired. This action loo ...

Unclear outcomes from iterative loops

I have a question about this particular for loop: for (var i=0,j=0;i<4,j<20;i++,j++) { a=i+j; } console.log(a); Can someone explain why the output is 38? I initially expected it to be 6. ...

Reprogramming data with ajax

Seeking assistance on updating gridview data using AJAX. Anyone able to assist? Looking to update the gridview with new changes after saving entered values from textboxes into the database, but without utilizing an ajax updatepanel. ...

Stop the automatic page refresh in Struts 2

Currently, I'm developing a small web application and it's my first time utilizing Struts2. My goal is to create a Struts2 JSP page that, upon form submission, calls a struts action. After the action completes its task, I want to return to the or ...

Angular does not allow the transfer of property values from one to another

As of late, I have delved into learning Angular but encountered an issue today. I have the following Component: import { Component, OnInit } from '@angular/core'; import { SharedService } from '../home/shared.service'; import { IData } ...

Passing a variable by copy in a done call with Ajax

Here's the code snippet I'm working with: for (var i = 0; i < list.length; i++) { $.when( $.ajax({url: "./dorequest.php?id=" + list[i], success: function(response){ jsonFriendlist = response; }}) ).done( ...

Using Object.create to establish multiple prototypes in JavaScript

I am trying to have my child object inherit the prototypes of multiple parents, but the following methods do not seem to work: child.prototype = Object.create(parent1.prototype, parent2.prototype); and also this: child.prototype = Object.create(parent1 ...

Issue with the alphabetical ordering of subpages

My PageSidebar.js component lists child pages alphabetically. https://i.sstatic.net/DZro1.png However, when I navigate to a child page, the alphabetical order is not maintained. https://i.sstatic.net/fRVgO.png I've tried multiple solutions but hav ...

Make sure to finish the call before proceeding to the success section when using jQuery AJAX

I have created a jQuery script to download a file and then delete it from the server. Below is the code I am using for this functionality. if (method == "ValueAddedReportExportToExcel") { $.ajax({ async: false, type: "p ...

The TipTap Editor does not properly register spaces

In our project, we are utilizing the TipTap rich text editor. However, we are encountering an issue where spaces are not being recognized correctly - a space is only created after every 2 clicks. Our framework of choice is Vue.JS. import { Editor, EditorC ...

Once the print dialog is canceled or saved, the current window remains open

Whenever I try to print the data, a new window opens displaying all the respective data of the HTML page. The print dialog then quickly appears, but if I cancel or close the dialog, the current window does not close. Can someone please provide suggestions ...

Does my method need adjustments or is it fundamentally flawed?

<html><head></head> <body><script> function calculateGreatestCommonDivisor(a, b) { if (a == 0) { return b; } return calculateGreatestCommonDivisor(b % a, a); } function getDifference(array) { for ( ...