Sending data using jQuery to a web API

One thing on my mind: 1. Is it necessary for the names to match when transmitting data from client to my webapi controller?

In case my model is structured like this:

public class Donation
{
    public string DonorType { get; set; }
    //etc
}

But the form on my webpage looks like this:

<div class="button-group grid-x align-center" id='sz-gift-source-group'>
    <a class="hollow button cell small-6" id="sz-donate-individual" sz-data-toggle-button required>A family or individual</a>
    <a class="hollow button cell small-6" id="sz-donate-corporate" sz-data-toggle-button>A business or company</a>
</div>

Along with an event handler like this:

$('form button[type=submit]').on('click', () => {
const donation = getDonation();

$.post(
    '//localhost:61012/api/Donation',
    $("#sz-donate-form").serialize(),
    (data) => {
        console.log(`post succeeded:[${JSON.stringify(data)}]`); 
    })
    .fail((data) => {
        console.log(`post failed:[${JSON.stringify(data)}]`);
    })
    .always((data) => {
        console.log(`post complete:[${JSON.stringify(data)}]`);
    });

return false;
});

Additionally, how can I extract the data from the form and place it into the Donation object?

I've noticed that many tutorials overlook my initial question, leaving me wondering if my form is incomplete...

Answer №1

Remember to wrap your inputs inside a form tag to serialize data:

<form action="/" method="post" id="sz-donate-form">
    <input name="DonorType" type="text">
</form>

Keep in mind that when using serialize(), form data is serialized based on input names!

Make sure the name attribute matches the Donation class property.

I see you are working with typescript.

Your javascript code looks good.

Please provide your action code for webapi guidance.

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

Unraveling the Mystery of jQuery Syntax

Upon reviewing jquery.ui-1.8.11.js: $.extend(Datepicker.prototype, { /* A unique class name appended to elements indicating they are configured with a date picker. */ markerClassName: 'hasDatepicker', /* For debugging purposes (if e ...

Material UI AppBar displaying custom colors instead of theme colors

Currently, I am utilizing Material UI version 4.7.0. In my project, I have established a customized theme (shown below) by utilizing createMuiTheme() method with personalized primary and secondary colors set. Within my AppBar component (also displayed be ...

How can data be displayed in AngularJS/Json without using ng-repeat?

It seems like I am required to use ng-repeat in order to display the data, but I would prefer to avoid using it. angular: App.controller('aboutLongCtrl', function ($scope, $http) { $http.get('test_data/ar_org.json') .then(func ...

Node.js AJAX post causing HTML page to not load properly

When using express.js, I want to be able to redirect to an HTML page after clicking on a table element. Currently, the output in the console.log is the HTML source instead of being redirected and interpreted as an HTML page. Here is my click function usin ...

Error Alert: Request missing connection details while trying to connect to Sql server via express.js

I am currently utilizing the most recent versions of node, express, and mssql module. My objective is to establish a connection with the local instance of SQL Server 2014 through express.js. Following the guidelines provided in the official documentation, ...

How can I redirect after the back button is pressed?

I am currently working with a trio of apps and scripts. The first app allows the user to choose a value, which is then passed on to the second script. This script fetches data from a database and generates XML, which is subsequently posted to an Eclipse/J ...

Executing multiple functions with onPress in React Native

When I press onPress using TouchableOpacity, I am attempting to invoke multiple functions. Here's an example: functionOne(){ // perform an action } functionTwo(){ // execute something } <TouchableHighlight onPress{() => this.functionOne()}/& ...

Collect form input data containing a binary image and showcase it in a view using webapi

I am currently working on a webapi project using MVC architecture. The project involves converting a jpg image to binary data, sending it to a SQL server, and then retrieving the form data along with the image back as a jpg for display on the view. Althoug ...

Switch up image origin when image reaches screen boundary

I am trying to create a DVD screensaver with changing images each time it hits the edge, but I can't seem to get it to work. I've attempted using the code snippet below: var img = document.getElementById("myImage"); img.src = 'img/new-image. ...

The debate between centralization and specification: the ultimate Javascript/jQuery best practice for web applications

Picture a scenario where a web application consists of numerous page groups (pg1, pg2, ...) and some of these page groups require specific JavaScript code that is only relevant to them, not the entire app. For instance, certain visual adjustments on window ...

Include the attribute exclusively for the initial division within a group of corresponding elements

Looking to change the appearance of this HTML code without being able to edit it directly? <form method="POST" id="go123pago"> <div align="center" style="width:220px"> <div style="float:left;padding:10px;width:190px"> ...

Develop Connective Plugins using Angular 12

I am working on implementing a new feature for my app that involves storing certain modules on the backend and loading them dynamically based on user demand. Instead of loading all modules at once, I want to only load the necessary modules just before the ...

When I switch to a different navigation system, the css class gets removed

Let me clarify what I am looking for: Upon entering the index.php page, LINK_1 button is active. When I switch to LINK_2, it becomes active. I have only one index.php page where I include parts of external pages using PHP. Page_1 With the code I found, ...

Enhancing User Experience: Real-Time Preview in Text Area using Jquery

I have a code snippet here that allows me to insert images into a textarea and display a live preview when I click on a div. However, there is a small issue with the image not appearing instantly in the textarea; instead, I have to type a character for it ...

Tips for moving text within a Canvas using a button to trigger the function that displays the text in a Javascript environment

Within my HTML, there is a canvas element with the id="myCanvas". When a button is clicked, it triggers this particular function: function writeCanvas(){ var can = document.getElementById("myCanvas"); var ctx = can.getContext("2d"); va ...

How to link observables in HTTP requests using Angular 5?

I'm currently developing an application using Angular 5, and I want to segregate raw http calls into their own services so that other services can modify the responses as needed. This involves having a component, component service, and component data ...

The attempt to install "expo-cli" with the command "npm install -g expo-cli" was unsuccessful

Encountered an issue while trying to install expo-cli for creating android applications using npm install -g expo-cli. NPM version: 7.19.1 Node version: v15.14.0 Upon running npm install -g expo-cli, the installation failed with the following error mess ...

Develop a constructor that can be injected

Delving into the world of AngularJS as a beginner, I am starting to grasp the intricacies and distinctions between factory, service, and controller. From my understanding, a factory serves the purpose of returning a "value object" that can be injected. Mos ...

Capturing errors during function declaration in JavaScript

A problem has arisen in the below function definition due to a script error function foo () { try { var bar = function() { ERROR } } catch (exception) { console.debug("exception"); } } foo(); However, th ...

Is there a way to obtain a unique response in TestCafe RequestMock?

With Testcafe, I have the capability to simulate the response of a request successfully. I am interested in setting up a caching system for all GET/Ajax requests. The current setup functions properly when the URL is already cached, but it fails to prov ...