Using Javascript, send text from a textbox to an ActionResult in ASP.NET MVC using AJAX

Html

<input type="password" id="LoginPasswordText" title="Password" style="width: 150px" />


<input type="button" id="LoginButton1" value="Save" class="LoginButton1Class" onclick="LoginButton1OnClick" />

Json

var TextBoxData = {
Text: LoginPasswordText.GetValue(),
};


   function LoginButton1OnClick() {
        $.ajax({
            url: "/Home/MyActionResult",
            type: "POST",
            dataType: "json",
            contentType: 'application/json',
            data: JSON.stringify(TextBoxData),

            success: function (mydata) {
               alert("Success");
            }
        });
        return true;
    }

MyActionResult

public ActionResult MyActionResult(string Text)
{
 return view();
}

The above code snippets for Html, Json, and MyActionResult are functioning correctly with json data.

I am attempting to send the above codes as ajax data. I have tried the following code but it is not working. When I click the button, no data is sent. What could be the issue?

<script>
    function LoginButton1OnClick() {

         var TextBoxData = {
    Text: LoginPasswordText.GetValue(),
    };


        $.ajax({
            type: "POST",
            url: "Home/MyActionResult",
            data: TextBoxData,
            success: function () {
                alert('success');
            }
        });

    }
</script>

Answer №1

Wrapping the code in an additional object is unnecessary. Additionally, there is invalid JavaScript present with a trailing comma after the LoginPasswordText.GetValue() call, causing a JavaScript error. To properly retrieve the value of the input field, you can use the .val() function.

To fix this issue, simply send the value as-is:

<script>
    function LoginButton1OnClick() {
        var text = $('#LoginPasswordText').val();

        $.ajax({
            type: "POST",
            url: "Home/MyActionResult",
            data: text,
            success: function () {
                alert('success');
            }
        });
    }
</script>

This code will successfully send the string value to the following controller action:

[HttpPost]
public ActionResult MyActionResult(string text)
{
    return View();
}

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

Rotate Chevron icon downwards on mobile devices in a Multilevel Dropdown Bootstrap 4

Bootstrap 4 is being utilized for my current project, I am looking to modify the rotation of the chevron icon in a multi-level dropdown menu specifically on mobile devices when the parent link is tapped, Here is the code snippet for the multi-level dropd ...

Executing several Ajax requests on a single page

Utilizing an ajax call, I have implemented a feature for users to vote and unvote on the same choice. When a user clicks for the first time, the image is replaced with a voted status. Subsequently, if the user clicks the same choice again to unvote, the im ...

What is the best way to incorporate variables into strings using JavaScript?

Can someone help me achieve the following task: var positionX = 400px; $(".element").css("transform", "translate(0, positionX)"); Your assistance is greatly appreciated! ...

Creating TypeScript Classes - Defining a Collection of Objects as a Class Property

I'm trying to figure out the best approach for declaring an array of objects as a property in TypeScript when defining a class. I need this for a form that will contain an unspecified number of checkboxes in an Angular Template-Driven form. Should I ...

Transferring JSON data from an iOS device to a PHP server

I've run into an issue while attempting to transmit JSON data from an iOS application to a mySQL database by means of a php page. Unfortunately, it seems that the POST data is not being received on the php page. - (IBAction)jsonSet:(id)sender { ...

How can I move a TableItem from one material UI component to another using drag-and-drop?

I am facing an issue where I need to drag a ListItem from one List component to another. I am uncertain about how to accomplish this in Material UI. ...

Why is it that masonry is typically arranged in a single column with overlapping

I have been using the appended function in my code to add elements to a masonry instance that has already been initialized. However, I am facing an issue where all the tiles are being laid out in a single column and some of them are overlapping each oth ...

Transferring an array from JavaScript to PHP, encountering an issue with determining the length

I'm having an issue passing an array from my .js file to a PHP file. In JavaScript, the array is structured as follows: theBlock[0 - 79] with color, x, and y values. For example, theBlock[10].color or theBlock[79].x The data is sent using the follow ...

Troubleshooting a JavaScript project involving arrays: Let it pour!

I'm a beginner here and currently enrolled in the Khan Academy programming course, focusing on Javascript. I've hit a roadblock with a project called "Make it rain," where the task is to create raindrops falling on a canvas and resetting back at ...

NextJS: Issue: Accessing a client module from a server component is not allowed. The imported name must be passed through instead

My current NextJS setup is structured as shown below: app/page.js 'use client'; import React from 'react'; export default function Home() { return (<div>Testing</div>); } app/layout.js export const metadata = { title ...

The prototype object of the Datatable request parameter is missing

When attempting to make a datatable ajax request, I encountered an unexpected result on the server side. The console is logging the data as shown below: [Object: null prototype] { draw: '1', 'columns[0][data]': 'no', &ap ...

Server side pagination in AngularJS allows for dynamic loading of data

I am currently facing issues with slow application performance when retrieving large data from the database using Spring MVC and REST. I would like to implement server-side pagination in AngularJS to load only a subset of records. Could anyone provide gu ...

The npm system is encountering difficulties in parsing the package.json file

Having recently started using npm and node, I decided to create a react app with truffle unbox react using npm init react-app. Despite attempting to reinstall npm and clear the cache multiple times, I consistently encounter an error when trying to run sudo ...

In what way does s% access the title attribute within the Helmet component?

I am seeking clarification on how the reference to %s is connected to the title attribute of the <SEO /> component within the <Helmet /> component in the gatsby starter theme. Can you explain this? Link to GitHub repo On Line 19 of the code: ...

Is there a way to identify whether the image file is present in my specific situation?

I have a collection of images laid out as shown below image1.png image2.png image3.png image4.png … … image20.png secondImg1.png secondImg2.png secondImg3.png secondImg4.png secondImg5.png ……. …….. secondImg18.png My goal is to dynamically ...

Issue with refreshing a material

When updating a transaction, I am encountering the issue of inadvertently deleting other transactions. My goal is to update only one transaction. Can someone review my backend logic to identify the root cause? Schema Details: const mongoose = require(&apo ...

AngularJS ui-select not responding correctly to selected items

Currently, I am utilizing the ui-select module within AngularJS. <ui-select ng-model="tipData.category" search-enabled="false" name="category" required="required" class="orange-site-color-select custom-select"> <ui-select-match><span clas ...

How to choose between GET/POST and USE in ExpressJS for URL filtering

router.get('/',(req,res,next)=>{ console.log('initial middleware function'+req.originalUrl) }) VS router.use('/',(req,res,next)=>{ console.log('initial middleware function'+req.originalUrl) }) Could someon ...

Eliminate the prefixes of object keys in Node.js

This is my first time reaching out for help on a forum. I've been struggling with an issue for days and haven't been able to find a solution. It all started with a database query that returned the following data: { "prod_format": "400 ml", "pro ...

Tips for transforming a JSON array into a JavaScript 2D array

I am struggling to figure out how to convert the given JSON data into a JS 2D array directly from HTML. [{"fields": {"diameter": 23.0, "neighbourhood": "WEST END"}, "model": "hug.tree", "pk": 345}, {"fields": {"diameter": 14.0, "neighbourhood": "MOUNT P ...