The ajax keypress event is malfunctioning and the ActionResult parameter is failing to capture any data

I am facing an issue where I want to update the value of a textbox using AJAX on keypress event, but the controller is not receiving any value to perform the calculation (it's receiving null).

 <script>
    $('#TotDiscnt').keypress(function () {           
        //var data = $('#totDiscnt').val();
        $.ajax({
            type: 'Post',
            url: '/Whatever/Discount',
            data: $('#totDiscnt').val(),
            success: function (response) {
                $('#TotPurAmt').val(response);
            }
        });
    });
</script>

On the controller side

public ActionResult Discount(string text)
    {

       // Perform calculation

        return Json(sum, JsonRequestBehavior.AllowGet);

I have also tried this approach

data: { text: request.term },

However, when I do that, the AJAX call does not trigger the controller method. Another question I have is how to send two double values as parameters to the ActionResult method from an AJAX call like this:

 <script>
$('#TotDiscnt').keypress(function () {           
    //var data = $('#totDiscnt').val();
    $.ajax({
        type: 'Post',
        url: '/Whatever/Discount',
        data: {num1:$('#totDiscnt').val(),
                     num2:$('#Discnt').val() },
        success: function (response) {
            $('#TotPurAmt').val(response);
        }
    });
});

And then receive them as double values in the parameter like

 public ActionResult Discount(double num1, double num2)
    {
        // Perform calculation

        return Json(sum, JsonRequestBehavior.AllowGet);

Answer №1

Absolutely, you have the flexibility to add an event trigger using either keyup or keypress in your code. Just make a slight adjustment to your existing code.

<script>
$('#TotDiscnt').keyup(function () {           
    //var data = $('#totDiscnt').val();
    $.ajax({
        type: 'POST',
        contentType: 'application/json; charset=UTF-8',  //send type of data to sever
        dataType: 'json', //retrun type of data from server
        url: '/Whatever/Discount',
        data: JSON.stringify(text:$(this).val()),

       // data: $('#totDiscnt').val(),
        success: function (response) {
            $('#TotPurAmt').val(response);
        }
    });
});

Make sure your controller is set up like this:

public ActionResult Discount(string text)
{

   // calculation

    return Json(sum, JsonRequestBehavior.AllowGet);
}

Important Note: The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks have been removed in jQuery 3.0. Consider utilizing jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead. For more information, please refer to the official site here.

Please provide feedback in the comments on whether it is functioning correctly or not.

Answer №2

If you need to pass multiple values from an ajax call to the parameters of an ActionResults method, you can do so using the following code:

 <script>
    $(document).ready(function () {
        $('#btnCalculate').click(function () {
            $.ajax({
                type: 'Post',
                url: '/Sales/Calculate',
                data: { num1: $('#txtNum1').val(), num2: $('#txtNum2').val(),//and so on.... },
                success: function (response) {
                    $('#txtSum').val(response)
                }
            });
        });
    });
</script>

In your controller, you can handle this incoming data like this:

 public ActionResult Calculate(int num1, int num2)
    {
        int sum = 0;
        sum = num1 + num2;
        return Json(sum, JsonRequestBehavior.AllowGet);
    }

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

Tips on utilizing recursive Promises within a loop while transferring arguments to another function

Despite searching other threads on SO, I couldn't find a satisfactory answer to my problem. Every solution seems to be missing something essential for my case, especially since none of them address Apple Music specifically. The Apple API relies heavil ...

Executing a function when a specific element is triggered within an ng-repeat in AngularJS

Hey there, I've been grappling with changing the limitTo filter on a specific list, but I'm encountering an issue: whenever I trigger the filter change, it applies to all ng-repeated categories. The function within my main controller is as foll ...

Issue with transmitting Razor form data to API controller using fetch or AJAX

I have created a basic razor web project and defined it as follows: in program.cs I added builder.Services.AddAntiforgery(o => o.HeaderName = "XSRF-TOKEN"); In the controller, this is what I did: [Route("/api/[controller]")] [ApiCon ...

Normalization of Firebase Database

Recently, I developed a Tricycle Patrol app designed to address the prevalent issue of reckless tricycle drivers in our city. Users can log in and submit reports through a form that includes fields such as: - created_at - description - lat - lng - plateNu ...

Having trouble with nodeJS when running the command "npm install"?

Can anyone help me understand why I'm encountering issues when running "npm install"? Whenever I run npm install, I am bombarded with numerous errors. npm ERR! Windows_NT 10.0.10586 npm ERR! argv "C:\\Program Files\\nodejs&bsol ...

Learn the process of transmitting data from middleware to components and APIs in Next.js version 13

I've been experimenting with the Next Js 13 middleware feature and I'm a bit confused about how to pass data from the middleware to components/pages/api. For example, when trying to pass payload data or determine who the currently logged-in user ...

Utilizing Angular partials within specific views with the assistance of ui-router

I am currently working on developing a MEAN application and facing some challenges while handling ui-router. Within my index.html file, I have set up the template for the entire website including a header, sidebar, and content area where I have placed < ...

Ways to prevent prop changes from passing up the chain?

After some experimentation, I discovered that the props I passed to a component can actually be changed within the component and affect the parent. This behavior is discussed in the official documentation. While objects and arrays cannot be directly modi ...

When I click on a specific div, another div should be appended to the main_div

I am just starting to learn about jquery and have a simple application where I need its functionality. Within my layout, there are several small divs on the left side (such as div1, div2...), and one main div in the center of the page. My goal is to have ...

What is the best way to rearrange DOM elements using the output of a shuffle function?

Looking for a solution to shuffle and move around cards in an HTML memory game? Let's analyze the current setup: <ul class="deck"> <li class="card"> <i class="fa fa-diamond"></i> </li> ...

Leveraging webpack for requiring modules in the browser

I've been attempting to utilize require('modules') in the browser with webpack for the past couple of days, but I could achieve the same functionality with browserify in just 5 minutes... Below is my custom webpack.config.js file: var webp ...

Displaying Child Component in Parent Component After Click Event on Another Child Component: How to Implement Angular Parent/Children Click Events

After delving into Angular 7 for a few weeks, I find myself faced with the challenge of toggling the visibility of a child component called <app-child-2> within a Parent component named <parent>. This toggle action needs to be triggered by a cl ...

Trigger the ontextchanged() event for an asp:TextBox using Javascript

I have a specific asp:TextBox that is structured in the following way: <asp:TextBox runat="server" AutoPostBack="True" ID="txtG1" ontextchanged="txtG1_TextChanged" onmouseout="javascript:RefreshIt(this)"/> In addition to this, there is a Javascript ...

StartsWith() function failing when used in conjunction with takeWhile()

I'm trying to iterate over an Immutable List and create a new list containing only the entries that start with a specific string. In this case, I want to find all states that begin with the letter 'D'. However, instead of returning a list wi ...

Cease the execution of promises as soon as one promise is resolved

Using ES6 promises, I have created a function that iterates over an array of links to search for an image and stops once one is found. In the implementation of this function, the promise with the fastest resolution is executed while others continue to run ...

Can anyone explain to me why the data I'm passing as props to the React functional component is displaying as undefined?

I have encountered an issue with a pre-made React component where I am unable to see the data being passed as props when I console log it. I am unsure if I am passing the prop correctly, as I have used the same prop successfully in other class-based comp ...

Upon attempting to add a new component, an error was encountered: Uncaught SyntaxError: Unexpected token export

I have created a React test project and added modules to my package.json as follows: { "name": "untitled", "version": "0.1.0", "private": true, "devDependencies": { "babel-preset-node5": "^12.0.1", "react-scripts": "0.9.5" }, "depe ...

The PhoneGap integration causing issues with jQuery Slide Panel functionality

My code runs smoothly in browsers, but faces issues with PhoneGap compilation. The SCROLL FROM LEFT/SCROLL FROM RIGHT functionality doesn't seem to work as expected. Despite this, the LEFT/RIGHT menus can be accessed by clicking the button at the top ...

Struggling with integrating Bootstrap 4 Modals in Angular 2 environment

I attempted to incorporate a modal from into my navbar, but nothing happens when I click on it. <div class="pos-f-t fixed-top header"> <nav class="navbar navbar-inverse bg-inverse navbar-toggleable-md"> <button class="navbar- ...

Clear out the existing elements in the array and replace them with fresh values

Within my Progressive Web App, I am utilizing HTTP requests to populate flip cards with responses. The content of the requests relies on the selected values. An issue arises when I choose an item from the dropdown menu. It triggers a request and displays ...