Tips for effectively invoking an MVC Controller using AJAX

I am currently working on initiating an AJAX call to a controller ActionResult within the MVC framework. While I have experience with AJAX, I am relatively new to MVC. I have set up an AJAX call in a separate .js file that is triggered by a button click event in one of the views. The AJAX call is executed as expected but consistently returns a "resource not found" error message. See the code snippet below:

Button in View:

<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('initiating ajax call');
                },
                success: function (data) {
                    alert(data);
                },
                error: function (ex) {
                    console.log('Error');
                    console.log(ex.responseText);
                    alert("Error occurred while downloading images. Please contact IT support.");
                }
            });
        });

ActionResult within Controller:

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

Displayed error message:

If you can provide any assistance, it would be highly appreciated.

Answer №1

The data property is not being set correctly.

data: param = "this"

This should be corrected to:

data: { param : "this"}, 

Additionally, the URL should include a forward slash before the controller (/) and the word controller should be removed. 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.");
            }
        });

Answer №2

My approach would involve making three key changes:

Answer №3

Substitute

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

for

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

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

Span wrapped in a hover effect

I am facing an issue with hover options... What I am looking for is a text in a circle Finally, I achieved the desired look using csswrap Next, I added some jQuery to insert links into all spans with the same class Everything is working fine, except fo ...

Tips for ensuring the Google Maps API script has loaded before executing a custom directive on the homepage of an Angular website

Issue - I am facing issues with Google Maps autocomplete drop-down not working on my website's main page even after parsing and loading the Google Maps API script. The problem seems to be a race condition on the main page of my website, specifically i ...

Stop unauthorized direct access to PHP forms and only allow submission through AJAX requests

I have set up a script that sends an email notification whenever someone comments on my Facebook comment box. The script uses FB.event.subscribe to trigger an AJAX call to mail.php on my server, which then sends an email to my address. How can I enhance ...

Creating a custom loading page in Next.js 13: A step-by-step guide

Hello, I am currently working on implementing a loading page for my website to enhance the user experience during a longer loading time. I have created a simple functional component that displays a loading message and imported it into my layout.jsx file in ...

Transferring data from a form to PHP using AJAX

I've been struggling to get the Ajax Post Method to work after multiple attempts. <form id="search_box" method="POST" action="" > <input class="SEARCH" type="text" name="search_name" id="search_name" placeholder="Search product by name" /> ...

Guide to incorporating an input field within a select option in ant design and react

I have utilized Ant Design to create a select option, but now I am looking to implement an editable cell within the select option. Below is the code for my select option: <Select showSearch style={{ width: 400 }} placeholder="Select a Bank" op ...

Ways to split images and text in list items using CSS

Can the text be formatted in a specific location on the page, separate from the image and heading? This is the HTML code I am currently using: <div class="tab-pane container fade" id="environmental"> <div class="row"> <div class="c ...

Retrieving visual information from Google Street View entity

Looking for a solution to extract imagery from the Google Street View panorama within a web page? In my program, I navigate specific routes using Google Street View's javascript API controlled by an embedded Java applet on the same page. I am seeking ...

SMMRY API bug stemming from a lack of necessary variables

Here is the code snippet: // Article Summary var params = { host: 'api.smmry.com', path: '/', body: { SM_API_KEY: 'B...', SM_URL: 'www.bbc.com/sampleNews' } }; http.get(params, functi ...

The left and right arrows maintain their visibility even when they are outside of the image

I am a beginner in the world of web development and I am trying to implement left and right navigation for images using arrows. My goal is to have the arrows fade in when the mouse hovers over the image and fade out when it's moved away. However, I am ...

What is the correct way to insert a new key-value pair into an object within the state of functional components?

Is there a way to dynamically add key-value pairs to the initial state of an empty object in functional components, similar to computed property names in class components? I currently have an initial state of {}. const [choice, setChoice] = useState({}) ...

Creating a fantastic Image Gallery in JavaScript

As I work on creating a basic gallery page with html and css, everything seemed to be running smoothly. However, upon testing it in Google Chrome and IE, the onmouseover function is not responding as expected. The idea is for a larger image to display in t ...

Issue with jQuery.parseJSON causing empty data structure to return

I am facing a puzzling problem with manipulating data in JavaScript. The code snippet I am using in JavaScript is to fetch data from a PHP/MySQL source. var _response = jQuery.ajax({ url: "../data", async: false, type: "post", data: oPara ...

Setting up a Web application testing environment on its own

Embarking on my journey in web application development and testing, I am currently involved in a project that requires me to create a standalone environment for testing the web application. The main goal is to ensure the web application is easily testable ...

Authentication with Laravel and Vue.js

After successfully implementing Laravel-Vue.js Authentication using Passport API, I am now able to obtain the token and send requests to api/user. Initially, I used the normal authentication process by sending data through a POST request to /login, which r ...

Implementing es6 syntax for overloading a library class

In my project, I have various objects that extend other objects from a library. The library object extends the Object class of the library. Therefore, the architecture is as follows: // The library object class class Object { } // The library object1 c ...

Use JavaScript executor in Selenium WebDriver to interact with list items by clicking on them

I am facing a challenge where I need to gather multiple links, click on each link, and extract specific information from the website to export into Excel. My approach involves collecting all the links in one list and attempting to click on each one based ...

Is there a possibility for the code following the await call to be executed in a random order if an async Vuex action is triggered twice?

const actions = { search: debounce( async ({ commit, dispatch, getters, rootGetters }, { page = 1 }) => { commit("setLoading", true); commit("setPage", page); console.log("Starting...") const ...

Share a URL seamlessly without the need for a page refresh or AJAX request

I am looking for a way to trigger a script to save an image to the server when a link is clicked, without actually navigating to a different page. Even though I tried using e.preventdefualt to prevent the link from submitting, it didn't work as expec ...

Developing a personalized camera feature using ReactJS

After searching for a suitable npm library to create a custom camera component within my ReactJS project, I came across an article providing detailed information at this link. However, I am facing challenges in converting the existing pure JavaScript code ...