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

Selecting random numbers in React.js

I am working on creating a Netflix Clone and I want to change the banner image every time the page refreshes. I have integrated movie details from TMDb and have an array containing these details. My goal is to select a random number between 0 and 19 and us ...

What is the method for configuring environment variables in the Lumber framework?

Installing Lumber CLI npm install -g lumber-cli -s Next, lumber generate "adminpanel_test" --connection-url "mysql://root@localhost:3306/admin-dev" --ssl "false" --application-host "localhost" --application-port "3310" Error: lumber is not recognized a ...

Effortlessly sending information to the Material UI 'Table' element within a ReactJS application

I have integrated a materialUI built-in component to display data on my website. While the code closely resembles examples from the MaterialUI API site, I have customized it for my specific use case with five labeled columns. You can view my code below: h ...

The button I have controls two spans with distinct identifiers

When I press the player 1 button, it changes the score for both players. I also attempted to target p2display with querySelector("#p2Display"), but it seems to be recognized as a nodeList rather than an element. var p1button = document.querySelector("# ...

I am unable to achieve negative X degree rotation of the image while using mousemove to rotate it

I need assistance with moving a picture in 3D. I want the offsetX of the mouse to be positive when it's past half of the picture, and negative otherwise. How can I achieve this effect for rotation degrees? This is what I have tried: $('#img ...

The ability to update a variable passed through the state in Link is restricted

Currently, I am in the process of updating the theme in my App using useState. The updated theme is passed to the Topbar Component as a prop, triggering console.log() every time it changes. The theme is then passed from the Topbar to the AboutMe Component ...

Using jQuery and AJAX to prevent the default behavior of a link, initiate an AJAX request, and then navigate to the link afterwards

Attempting a seemingly 'simple' task has turned into quite the challenge for me. My goal is to have a user click a link, prevent the default action, execute an AJAX function, and then proceed to follow that link. So far, my attempts have only re ...

Using Q to conduct polling asynchronously with promises

I am facing a situation similar to the one discussed in this blog post: Polling with promises. The author explains using promises for polling until a JobID is returned. I intend to implement this using Q. I want to chain promises together but my attempts ...

Obtain the node identifier within the Angular UI Tree component [angular-ui-tree]

Utilizing Angular UI tree to create a relationship between items and categories has been successful in the default setup. However, a new requirement has emerged to incorporate node/section numbering within the tree for managing hierarchy. I attempted to i ...

Clicking on a specific month results in displaying only one row from the database rather than showing all rows associated with that particular month

I am facing an issue with my calendar feature on the website. The problem is that when I click on a specific month, it should display all the data associated with that particular month. However, the current code does not seem to work as expected. For insta ...

Link Google Map Marker Click Event with Dynamic Binding

I'm currently working on binding a click event to a link that is positioned outside the Google Map Canvas. The goal is to open an "infowindow" on a map marker when this link is clicked. While I know how to achieve this for a specific point, I need a d ...

Encountering a getMacChromiumEdgeDriverArchitecture error while using wdio/selenium-standalone-service

As I continue to learn WebDriverIO and adjust to MacOS, I encountered an error while trying to execute a spec file using "npm run test:wdio". The error message is as follows: > [email protected] test:wdio /Users/vinicius.correia/Desktop/dev/automat ...

The React application is experiencing difficulties in receiving the response data (JSON) from the Express server, despite the fact that

When making POST or GET requests to our Express server, served through PM2 on EC2, Postman receives the complete response with JSON data. However, our front end React app (both locally and deployed via CF) only gets the response status code and message. Th ...

Using brush strokes to create a unique design on the canvas page

Currently, I am working on implementing a brush-like effect on a web page. The task involves providing multiple patterns/textures in the background and allowing users to drag their mouse to create the pattern effect on the page. If you want to see the st ...

Implementing jQuery autocomplete on dynamically generated fields post page load

I have successfully implemented jQuery UI Autocomplete to fetch data from a DB and populate a form dropdown. However, I am faced with the challenge of adding more form fields dynamically that also need to have the autocomplete feature applied to them. Is ...

Unable to transfer a function to a component using <Route /> tag

In the Erm component, the function setErm is undefined even though it is received by the App component. When passing something like something='foo', the ERM component receives it but not setErm={props.setErm} const App = props => { console. ...

I encountered a RangeError with code [ERR_HTTP_INVALID_STATUS_CODE] due to an invalid status code being undefined

I have encountered a specific error while running my note-taking app. The error seems to be related to the following piece of code - app.use((err,req,res,next)=>{ res.status(err.status).json({ error : { message : err.message ...

Generating a list of values separated by commas from a Microsoft Excel column after applying regular expressions

I have an Excel column that I need to convert into CSV format. A JavaScript regex has been provided to apply on the column values: var regex = new RegExp("[^a-z0-9',.]+","gi"); return input.replace(regex, "_").replace(/_+/g, "_").replace(/^_|_$|^&bso ...

When attempting to send data to the ServiceStack RESTful service, an error message of 'Access is denied' was received

I created a RESTful service using ServiceStack to send data to a database. It worked perfectly when tested locally. However, after deploying it to a server and running the same jQuery $.ajax call code, I encountered an 'Access is denied' error. I ...

What is the equivalent of jQuery's blur event in AngularJS?

I need to implement a functionality in AngularJS where any opened component is closed when clicking outside of it. Is there an existing Angular directive for handling blur events, or do I need to come up with a custom solution? ...