Sending Ajax data to a controller function

I am looking for guidance on how to pass values from my view to my controller using ajax. As someone who is new to working with ajax, I would appreciate some assistance in understanding the process.

Full Page

@model ALSummary.Models.MonthReport

@{
    ViewBag.Title = "Index";
}

<h2><strong>Generate Monthly Report</strong></h2>

<br />
<hr />

@Html.BeginForm("Generate", "MonthReports", FormMethod.Post, htmlAttributes: new { id = "GenerateForm" }){
<div class="form-horizontal">
    <div class="form-group">
        @Html.Label("Choose AC:", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
        @Html.DropDownList("AC", null, "-- Select AC --", htmlAttributes: new { id = "AC", @class = "form-control" })
        </div>
    </div>
</div>


<div class="form-horizontal">
    <div class="form-group">
        @Html.Label("Choose Month:", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("Months", null, "-- Select Month --", htmlAttributes: new { id = "Month", @class = "form-control" })
        </div>
    </div>
</div>

<div class="form-horizontal">
    <div class="form-group">
        @Html.Label("Year:", htmlAttributes: new { @class = "control-label col-md-2" })
        <div class="col-md-10">
            @Html.DropDownList("Years", null, "-- Select Year --", htmlAttributes: new { id = "Year", @class = "form-control" })
        </div>
    </div>
</div>

<br />

<input type="submit" id="SendToController" class="btn btn-primary" value="Generate" />
}


<script type="text/javascript">
    $('#SendToController').on('click', function() {
        sendToController();
        return false;
    });
    function sendToController(){
        var selectedAC = $('#AC').val();
        var selectedMonth = $('#Month').val();
        var chosenYear = $('#Year').val();
        $.ajax({
            url: @Url.Action("Generate", "MonthReports", null),
            data: { 'id' : selectedAC, 'monthValue' : selectedMonth, 'year' : chosenYear },
            type: 'GET',
            cache: false,
            success: function(data){},


        });
    }


</script>

Error Message:

https://i.stack.imgur.com/xR1aB.jpg

The red squiggly lines appear at this position when I encounter the error message:

https://i.stack.imgur.com/VCAVt.jpg

Answer №1

Everything seems to be in order with your AJAX and Controller. The error message you're receiving is likely because the JavaScript function cannot be found when the HTML is loaded for the Submit input. This often happens when the JS is loaded after the DOM has been created. My hunch is that your script block is located at the end of the body rather than in the head, which is perfectly fine, but requires a different approach.

In my experience, I find it more effective to bind events using JavaScript instead of directly in the HTML. You can remove the onclick="sendToController()" from your HTML code and add the following lines to your JavaScript:

$("#FormID").on('submit', function(event) {
    event.preventDefault();
    sendToController();
    return false;   // prevent submit from sending
});

function sendToController() {
    // insert your additional code here
}

Remember to replace FormID with the actual ID of your form as needed.

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

Fill the list items with values from the given array

I have an array called var array = ["one", "two"]; and I want to display each element in a separate list item. The desired output is: <li>Number one</li> <li>Number two</li> However, the current output is: <li>Number onetw ...

Can you provide me with a variable that will give me the total size of the scrollbar?

How can I determine the maximum number of pixels scrolled on a webpage? I attempted using window.pageXOffset, but it only gives the current scrolled amount. I require the total size at all times. ...

What is the best way to send a JQuery variable using JSON.stringify and retrieve it on the server-side?

I need to pass the value in JSON.stringify and receive it on the Server side. Please note: When I attempt to pass the value directly without utilizing a JQuery variable, everything works smoothly. Without using a JQuery variable (it's functional) d ...

Generate barcodes using Angular 2

Can anyone point me in the direction of an Angular 2 Barcode Generator capable of creating code 128 barcodes? I've been searching but haven't had any luck finding one. If you have any suggestions or can offer assistance, it would be greatly appr ...

create a sapper route using JSON data

Beginning with the official Sapper template, I am keen on implementing export default as recommended by eslint: export default function get(_, res) { res.writeHead(200, { 'Content-Type': 'application/json', }); res.end(conte ...

Prevent leaving the body empty while populating a page with Ajax requests

I'm currently facing a dilemma at work. Our team is utilizing Bootstrap, jQuery, and a REST API to populate our web pages. Here's the sequence of events during page loading: The server receives a request A template is served which loads all ne ...

Is it possible to update JavaScript on mobile devices?

I'm currently working on a mobile site where I've implemented JavaScript to refresh a message counter. However, despite having JavaScript enabled on the device, the counter doesn't update on my Nokia e90. Interestingly, it works perfectly fi ...

Vue's beforeRouteEnter hook patiently awaits for the child component to complete its request

My Vue app utilizes beforeRouteEnter to load data and prevent the undesirable "flash of unloaded content." Loading data on some pages is straightforward: async beforeRouteEnter(to, from, next) { const newestPosts = await getNewestPosts(); next(vm ...

Angular 1: Handling Multiple Conditions and Exclusions Based on Other Conditions

I have currently added an additional span to accommodate one condition. <div ng-repeat="(key, resultLinks) in resultGroup.resultLinks"> <div ng-if="key < 4 || viewMore" ng-repeat="(subKey, linksWrap) in resultLinks.linksWrap"> & ...

What is the best way to convert a locale code into a language name with i18next?

In the application I'm working on, there is a language selector feature that allows users to choose the display language for the app. Currently, we only have limited options available, but there are plans to expand the list in the future. My goal is t ...

What is the best way to send a JSON Object containing option parameters in order to open a new window?

Have you noticed the interesting parameter list for the window.open() object? Is there a possibility to use window.open({options..}); instead? What are your thoughts on this matter? ...

Error in hook order occurs when rendering various components

A discrepancy was encountered in React when attempting to render different components Warning: React has detected a change in the order of Hooks called by GenericDialog. This can result in bugs and errors if left unresolved. Previous render Next ren ...

The AJAX request encountered an error due to an Unexpected End of JSON Input

My AJAX code is encountering an error message. parsererror (index):75 SyntaxError: Unexpected end of JSON input at parse (<anonymous>) at Nb (jquery.min.js:4) at A (jquery.min.js:4) at XMLHttpRequest.<anonymous> (jquery.min.js: ...

What could be causing the invisibility of my drop down list items?

I am having trouble creating two cascading drop-down lists. The first one is functioning correctly; however, when I move to the second drop-down list, I can see that the correct number of options are being generated based on the items in the database, but ...

Handling errors in chained promises and routes in Node.js/ExpressJS

I'm currently dealing with some confusion regarding how to handle errors when making function calls. To demonstrate this, I'll be using sequelizeJS as an example. Usually: First.Ctrl var second_ctrl = require( '../ctrl/second'); testC ...

Error connecting to Firebase Cloud Functions - connection issue

Whenever I call my cloud function, I see the following message in the logs: Function execution took 5910 ms, finished with status: 'connection error'. It seems to be related to promises and returning or !d.exists, but I haven't been able to ...

Store a JSON String produced by Javascript as a file in web2py

[Log] {"image":"/SAS/default/download/uploads.image.85f2588e34848596.30362d32353033392e746966.tif","filename":"/SAS/default/download/06-25039.tif","start":1437444049436,"width":1080,"height":734,"events":[{"colour":"#0000ff","width":3,"erased":false,"point ...

The call is not being answered by the server route (NodeJS + express)

I have encountered an issue while setting up a server using NodeJS and Express. When I attempt to make a get request to the basic route ('http://localhost:3000/'), the request seems to hang indefinitely. Despite thoroughly reviewing my code multi ...

Changing the structure of a webpage in real-time and inserting new elements into the document

I have a custom x-template filled with a survey element (including a text field and radio button). Upon loading the screen, the database sends a JSON object to the UI based on previously stored sections. This JSON object is then used to populate the survey ...

What improvements can I implement to enhance the clarity and functionality of this form handler?

As a beginner working on my first Next.js app, I'm facing some challenges that seem more React-related. My app allows users to add and edit stored food items and recipes, requiring me to use multiple submit form handlers. Each handler involves: Che ...