Sending a request from JavaScript to C# methods using AJAX, with no expected response, within an ASP.NET MVC framework

Setting up the Environment:

<package id="jQuery" version="3.2.1" targetFramework="net45" />
<package id="Microsoft.AspNet.Mvc" version="5.2.3" targetFramework="net45" />

Recently, I encountered an issue while trying to send a request from one of my JavaScript files to methods in a C# file. Despite receiving a 200 OK response, the content returned was empty and when using console.log(response), it showed undefined. Could this problem be related to the requesting URL or did I make an error in defining my C# function? Any suggestions or assistance would be greatly valued!

Below is the snippet of my JavaScript code:

<script>
    console.log("hello_List!")
    function getSearch() {
        console.log($("#query").val())
        console.log(typeof($("#query").val()))
        $.ajax({
            type: "POST",
            url: "./Search",
            data:  $("#query").val(),
            dataType: "json",
            success: OnSuccess,
            failure: function (response) {
                alert(response.d);
            }
        });
    }

    function OnSuccess(response) {
        alert("Success!");
        console.log(response);
    }
</script>

Here is my C# function, located in the same folder as my JavaScript file:

    public class UsersController : Controller
    {
        [HttpPost]
            [System.Web.Services.WebMethod]
            public JsonResult Search(string query)
            {
                List<EntityModels.AspNetUser> users = new List<EntityModels.AspNetUser>();
                users = db.AspNetUsers.Where(x => x.Email.StartsWith(query)).ToList();
                List<SelectListItem> userObjs = new List<SelectListItem>();

                foreach (var user in users)
                {
                    var userObj = new SelectListItem
                    {
                        Value = user.Id.ToString(),
                        Text = user.Email
                    };

                    userObjs.Add(userObj);
                }

                return new JsonResult()
                {
                    Data = userObjs,
                    JsonRequestBehavior = System.Web.Mvc.JsonRequestBehavior.AllowGet
                };
            }
}

Answer №1

Thank you for your assistance! I was able to find the solution by adjusting the data format. Instead of just inputting a string, using JSON with index and value proved to be effective in this scenario. I updated the data attribute to:

data: { query: $("#query").val() },

This resolved the issue.

Answer №2

$.ajax({ type: "GET", 
 url: "./Find", 
data: $.("#searchInput").val(), 
dataType: "html", 
success: function(response){
//your success method logic    

can be added below } ,error: function (response) { alert(response.message); } });

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

Incorporating text box input into a data table

When I click the "add game" button, I want the value of the input named "game-name" to appear in the "Name of the game" column of a table. Additionally, I am experiencing issues with the delete button functionality. Below is the code snippet I am working ...

Click a button to switch the visibility of a section in an

Is there a way to create a toggle feature in Angular.JS that will open and close a div when clicked on the same div again? Currently, it opens the div when clicked but I want it to also close the div when clicked again. <a ng-href ng-click="openAccordi ...

Why is the 'short' shorthand used for the state of Illinois?

Each time I encounter them in IL: br_S, ldc_i4_S, ldarg_S, etc... So it brings me to question: I'm curious... When you're JIT'ing a language from IL to native assembler, does it truly impact performance significantly? So why include these s ...

What is the best way to target and focus on all class fields that have a blank value?

<input type ="text" class="searchskill" value=""> <input type ="text" class="searchskill" value="3"> <input type ="text" class="searchskill" value=""> <input type ="text" class="searchskill" value="4"> Is there a way to target o ...

When referencing a particular React commit in package.json, it may result in the installation of react-tools instead of react itself

After including the following line in my package.json: "react": "git://github.com/facebook/react.git#08e4420019f74b7c93e64f59c443970359102530" When I execute npm install, I notice that node_modules/react-tools has been installed instead of node_modules/r ...

Having trouble establishing a basic websocket connection in NodeJS

I am currently following a tutorial on WebSocket protocol development from this link: . Upon visiting localhost:1337/index.html, I encountered the following error: This localhost page cannot be found. No webpage was found for the web address: http://loc ...

Creating an optimized dashboard in Next.js: Expert tips for securing pages with specific roles, seamlessly implementing JWT authentication without any distracting "flickering" effect

Given our current setup: We have a backend ready to use with JWT authentication and a custom Role-Based Access Control system There are 4 private pages specifically for unauthenticated users (login, signup, forgot password, reset password) Around 25 priva ...

Trouble with VueJS refresh functionality

I am facing an issue with a method that needs to run on route load. Despite attempting to call it from the updated hook, it is not functioning as expected. Additionally, I have encountered an ESLint error. methods: { getDeals (key, cb) { this.dealsR ...

Limiting the Size of Highcharts Maps with maxWidth or maxHeight

My attempt to adjust the maxWidth of my world map using highcharts isn't altering its size. I have experimented with the following: responsive: { rules: [{ condition: { maxWidth: 500 }, ... As recomme ...

Rendering color with a three.js image texture (loaded using ColladaLoader)

I just started learning three.js 2 days ago and I'm a bit of a newbie. After drawing a box on SketchUp, exporting it as a collada file (.dae), and loading it into a scene with three.js, I tried tiling the object with textures but unfortunately, I fai ...

Exploring Node JS Express Thread Clarity

Having recently delved into the world of node js, I've familiarized myself with its architecture. I grasp the concept of the event loop, the main thread (V8 engine thread), and the other threads handled by libuv. When the main thread needs to handle ...

Determining if a webpage is actively processing an ajax request using jQuery

Is it feasible to create a function in Jquery that activates with each ajax request, such as displaying "loading..."? ...

Using inertia-links within the storybook framework

Hey there, just wanted to share my experience with storybook - I'm really enjoying it so far! Currently, I'm facing a challenge while implementing it in my Laravel app with Inertia. I'm trying to render a navigation link component that make ...

Separating the login/register functionality from the main app using the MEAN Stack

Apologies for my poor English! I have developed an application using the MEAN stack (MongoDB + Express.js + Angular.js + Node.js) with authentication utilizing passport.js and JWT (jsonwebtoken and express-jwt). What I aim to achieve? The login and r ...

Navigating through different views in a Vue application using Vue Router directly from Vuex actions

Currently, I am in the process of developing a web application using Vue 2.x and Vuex 2.x. In this project, I need to retrieve some data from an external source via an http call. If this call fails, my objective is to redirect to a different page. GET_PET ...

Update the displayed locations on Google Maps by fetching and displaying marker data

I am able to retrieve and display information from my MySQL table, but I need assistance with refreshing this data every 5 seconds using my current code. The data being shown is not extensive, just about 5 or 8 markers at a time. Below is the code I curren ...

Converting a JavaScript variable into PHP using ajax: A comprehensive guide

Can someone please help me troubleshoot this code for passing a JavaScript variable to PHP? It doesn't seem to be working properly. I want to extract the value of an ID from JavaScript and send it over to PHP. <!DOCTYPE html> <html> ...

Retrieve the source code of the current page using JavaScript and the Document Object Model (DOM)

Is there a way to retrieve the source of the current page using JavaScript and DOM? Do I need to utilize AJAX for this task? ...

What is the best way to extract specific values from one JSON object and transfer them to another using lodash?

//I have a pair of objects var obj1={ "name":"mayur", "age":23 } var obj2={ "name":"keyur", "age":29, "limit":54, "surname":"godhani" } //I am familiar with one approach var j1 = {name: 'Varun', age: 24}; var j2 = {code: &ap ...

I am looking to display an image as a value in the dropdown menu of my Contact Form 7 on my WordPress website

I am currently working on a Wordpress website where I have a page showcasing 50 different company logos. Below the logo section, there is a form created using Contact Form 7. The logo section was built using a combination of HTML and CSS. Within the form ...