How to properly call an MVC Controller with AJAX

jquery ajax call to mvc controller with parameters
how to make ajax call in mvc using jquery
ajax call mvc controller action
how to send a model in jquery ajax post request to mvc controller method
jquery ajax post to mvc controller action
jquery ajax call to spring mvc controller with parameters
ajax call not hitting controller action
how to call controller using ajax

I am trying to make an AJAX call to an MVC controller ActionResult that I have. I have used ajax before but I am new to MVC. I have an AJAX call in a separate .js file that is triggered in an on click event attached to one of the buttons in a view. The AJAX call is being triggered as expected, but always returns with a "resource not found" error. Code shown below:

View Button:

<input type="button" class="btn btn-success" value="Download Pictures" id="btnGetPics"/>

AJAX Call:

    var ajaxURL = 'MMRController/TestAjax';
    $('#btnGetPics').on('click',
        function () {
            $.ajax({
                type: 'POST',
                url: ajaxURL,
                data: param = "this",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                beforeSend: function () {
                    console.log('firing ajax call');
                },
                success: function (data) {
                    alert(data);
                },
                error: function (ex) {
                    console.log('Error');
                    console.log(ex.responseText);
                    alert("Error downloading images.  Please contact IT.");
                }
            });
        });

ActionResult in Controller:

        [HttpPost]
        public ActionResult TextAjax(string param)
        {
            return Json(param + " works", JsonRequestBehavior.AllowGet);
        }

Below is the error I am getting:

<!DOCTYPE html>
<html>
    <head>
        <title>The resource cannot be found.</title>
        <meta name="viewport" content="width=device-width" />
        <style>
         body {font-family:"Verdana";font-weight:normal;font-size: .7em;color:black;} 
         p {font-family:"Verdana";font-weight:normal;color:black;margin-top: -5px}
         b {font-family:"Verdana";font-weight:bold;color:black;margin-top: -5px}
         H1 { font-family:"Verdana";font-weight:normal;font-size:18pt;color:red }
         H2 { font-family:"Verdana";font-weight:normal;font-size:14pt;color:maroon }
         pre {font-family:"Consolas","Lucida Console",Monospace;font-size:11pt;margin:0;padding:0.5em;line-height:14pt}
         .marker {font-weight: bold; color: black;text-decoration: none;}
         .version {color: gray;}
         .error {margin-bottom: 10px;}
         .expandable { text-decoration:underline; font-weight:bold; color:navy; cursor:hand; }
         @media screen and (max-width: 639px) {
          pre { width: 440px; overflow: auto; white-space: pre-wrap; word-wrap: break-word; }
         }
         @media screen and (max-width: 479px) {
          pre { width: 280px; }
         }
        </style>
    </head>

    <body bgcolor="white">

            <span><H1>Server Error in '/' Application.<hr width=100% size=1 color=silver></H1>

            <h2> <i>The resource cannot be found.</i> </h2></span>

            <font face="Arial, Helvetica, Geneva, SunSans-Regular, sans-serif ">

            <b> Description: </b>HTTP 404. The resource you are looking for (or one of its dependencies) could have been removed, had its name changed, or is temporarily unavailable. &nbsp;Please review the following URL and make sure that it is spelled correctly.
            <br><br>

            <b> Requested URL: </b>/MMR/MMRController/TestAjax<br><br>

            <hr width=100% size=1 color=silver>

            <b>Version Information:</b>&nbsp;Microsoft .NET Framework Version:4.0.30319; ASP.NET Version:4.7.3429.0

            </font>

    </body>
</html>
<!-- 
[HttpException]: A public action method &#39;MMRController&#39; was not found on controller &#39;MOHR.Controllers.MMRController&#39;.
   at System.Web.Mvc.Controller.HandleUnknownAction(String actionName)
   at System.Web.Mvc.Controller.<>c.<BeginExecuteCore>b__152_1(IAsyncResult asyncResult, ExecuteCoreState innerState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Controller.EndExecuteCore(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.<>c.<BeginExecute>b__151_2(IAsyncResult asyncResult, Controller controller)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.Controller.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.Controller.System.Web.Mvc.Async.IAsyncController.EndExecute(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.<>c.<BeginProcessRequest>b__20_1(IAsyncResult asyncResult, ProcessRequestState innerState)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncVoid`1.CallEndDelegate(IAsyncResult asyncResult)
   at System.Web.Mvc.Async.AsyncResultWrapper.WrappedAsyncResultBase`1.End()
   at System.Web.Mvc.MvcHandler.EndProcessRequest(IAsyncResult asyncResult)
   at System.Web.Mvc.MvcHandler.System.Web.IHttpAsyncHandler.EndProcessRequest(IAsyncResult result)
   at System.Web.HttpApplication.CallHandlerExecutionStep.System.Web.HttpApplication.IExecutionStep.Execute()
   at System.Web.HttpApplication.ExecuteStepImpl(IExecutionStep step)
   at System.Web.HttpApplication.ExecuteStep(IExecutionStep step, Boolean& completedSynchronously)
-->

Any help would be greatly appreciated.

POST and GET Calls to Controller in AJAX JSON MVC Method, Controller method not being called by AJAX call. When you set type of button to “Submit” on page, then you have to set calling method on “using” statement with HttpMethod type as below. This is one type of AJAX call. <script type="text/javascript"> using (Ajax. We’re going to test this by placing a <div> on the screen with a button, and then capture the button click to invoke the jQuery.ajax command to call the MVC Controller and display the result back in the div. So we basically have:

You aren't setting the data property correctly.

data: param = "this"

should be

data: { param : "this"}, 

Also yyour url needs to have a forward slash before the controller (/) and remove the word controller so in full...

var ajaxURL = '/MMR/TestAjax';

//... etc..

$.ajax({
            type: 'POST',
            url: ajaxURL,
            data: { param : "this"},
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            beforeSend: function () {
                console.log('firing ajax call');
            },
            success: function (data) {
                alert(data);
            },
            error: function (ex) {
                console.log('Error');
                console.log(ex.responseText);
                alert("Error downloading images.  Please contact IT.");
            }
        });

How to use jQuery AJAX method to call an Action method in ASP , NET Core is based on Model View Controller (MVC) architecture where any Next I defined the .ajax() method of jQuery to call the 'Add' action method function that executes if the .ajax() method executes successfully. The Button has been assigned a jQuery click event handler and when the Button is clicked a jQuery AJAX called is made to the Controller’s action method. The following figure describes a jQuery AJAX call in ASP.Net MVC. The URL for the jQuery AJAX call is set to the Controller’s action method i.e. /Home/AjaxMethod.

Replace

    var ajaxURL = 'MMRController/TestAjax';
    data: param = "this",

with

var ajaxURL = '/MMR/TestAjax';
data: {param :"this"},

Using AJAX In ASP.NET MVC, Just Ignore the built-in Models and Controllers and make your own model. Here I am creating a model called "Students" having properties� its first calling the FirstAjax action with default HttpGet request and renders the blank Html view . (Earlier you were not having it) later on loading of DOM elements of that view your Ajax call get fired and displays alert. Earlier you were only returning JSON to browser without rendering any HTML.

Inserting Data Using jQuery Ajax POST Method In ASP.NET MVC 5, In this article, we will learn how to insert data using jQuery Ajax Post method in view and create the following jQuery Post method to call controller. Do a proper validation such as date input values when implementing. We can use normal form submission only for one button inside the form. To save as a draft we have to use an Ajax post to call the controller. First I have added a new controller “UserController” and implemented the methods to create a new user. Basically I added the Create get method and create post method.

[Solved] Ajax call in ASP MVC not working, So a few things to do/check. Based on your comments and your code, I believe your issue as to why its not even hitting the controller is 2 things: We can simply use the bootstrap class and call jQuery functions in ASP.NET MVC because during the project creation it will by default added to project and also linked to the template. Step 7 Now I will write the script for inserting the data as well as retrieving and displaying it to the view.

call controller method from jquery ajax, $.ajax({ async: false, cache: false, type: "POST", url: "@(Url.Action("YourAction", " YourController"))", data: { "id": ui.item.Id }, success: function� Once you click the Add button, it will create strongly typed view with Employee model. Now we need to create Razor/Html controls to get the user input. Here, I used the HTML controls to get user input and we made a jQuery Ajax Post to call MVC controller in the below code.

Comments
  • use just var ajaxURL = 'TestAjax';
  • The word "Controller" isn't part of the url even if it's part of the class, unless your class is named MMRControllerController. Try to access the url manually first. And the url should start with / if you specify the controller.
  • Try use url like this: var ajaxURL = '/MMR/TestAjax';
  • @sinitram this results in a new error: Invalid JSON primitive: this.
  • @the_lotus After changing var ajaxURL = '/MMR/TestAjax' I am still getting "The resource cannot be found" as an error. More specifically that a public action method TestAjax was not found on controller MOHR.Controllers.MMRController.
  • @sinitram Looking at it I think they've set up the request like that incorrectly and posted different code...