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

What is the best way to attach every sibling element to its adjacent sibling using jQuery?

I've been working with divs in Wordpress, where each div contains a ul element. <div class="list-item"> <div class="elimore_trim"> Lorem ipsum </div> <ul class="hyrra-forrad-size-list"> <li>Rent 1< ...

Development of a chart application involving frontend and backend components, utilizing chartjs for data visualization, mongodb for storage

As a beginner in generating charts using the ajax mechanism and chartjs, I've encountered an issue where the graphs are being plotted incorrectly. Any guidance on how to improve would be greatly appreciated. Thank you! Here is my JavaScript code for ...

How to use Newtonsoft to deserialize a JSON string into a collection of objects in C#

Here is a sample code for a class: using System; public class AppEventsClass { public string title { get; set; } public string description { get; set; } } Imagine retrieving the following JSON string after calling a remote webservice: {"d":"[{ ...

What is the best way to ensure bidirectional text appears correctly when two conflicting languages are combined, ensuring explicit directionality is set?

As I work on localization implementation, I encounter an issue with the directionality of mixed characters on the page. The text content is stored in a json file and inserted into the DOM using a Vue.js template. While individual characters display corre ...

AngularJS uses variables defined by using curly braces like {{"message"}}

I am currently utilizing the following code snippet to monitor route changes: $scope.$on('$routeChangeStart', function (event, toState, toParams, fromState, fromParams) { //content $log.log(toState); } Whenever I print out "toState ...

Angular directive specifically meant for the parent element

I am working on a directive that I need to apply to a specific div element without affecting its child elements. The goal is to make the main div draggable, so that when it moves, its child divs move along with it. However, I do not want the child divs to ...

Having Difficulty with Mathematical Operators in AngularJS

Here is the code snippet I am currently working with: $scope.calculateTotal = function() { $scope.totalAmounts = []; var total = 0; for (var i = 0; i < $scope.orderDetails.length; i++) { console.log($scope.orderDetails[i]['pric ...

Dayjs is failing to retrieve the current system time

Hey everyone, I'm facing an issue with using Dayjs() and format to retrieve the current time in a specific format while running my Cypress tests. Despite using the correct code, I keep getting an old timestamp as the output: const presentDateTime = da ...

Is it possible to include two functions within a single HTML script?

On my webpage, there are multiple tabs that display different sets of data. Below is the code for handling the functionality of these tabs: function openTab(event, tabName) { var i, tabcontent, tablinks; tabcontent = document.getElementsByClassNa ...

Using AJAX to submit forms in Laravel

After creating a form to input data into the database, everything was functioning correctly until I implemented AJAX. The issue now is that even with AJAX, it still redirects me to another page and displays the text returned by the controller. Below is m ...

Exploring the Capabilities of Drag-and-Drop Functionality in jsTree and DataTables

Is it possible to copy nodes from a jsTree that I've dragged to a cell in a DataTable? I'm struggling with getting this functionality to work. Any suggestions on how to achieve this? I am not seeing any alerts appear. This is the HTML code: &l ...

Is there a method I can use to transform this PHP script so that I can incorporate it in .JS with Ajax?

I have a JavaScript file hosted on domain1.com, but in order for it to function properly, I need to include some PHP code at the beginning. This is necessary to bypass certain restrictions on Safari for my script by creating a session. The PHP code establi ...

Formik Alert: Update depth limit reached

Currently, I am working on an EDIT formik form that is displayed as a MODAL. The issue arises when the setState function is triggered with setState(true), causing the form to appear without any onClick event. Despite changing onClick={editStory} to onClick ...

A plug-in for TinyMCE that allows users to adjust column widths within a table

We utilize TinyMCE in our content management system (CMS), and our users have expressed interest in being able to adjust the width of a column within a table. While HTML technically does not recognize columns, the Moodle editor HTMLAREA includes a plugin t ...

Insert a new element into a JSON array using C#

I have a JSON Array here and I am looking to append a new field into the array. However, I am unsure of how to iterate over it. { "data": { "pasca": [ { "code": "PDI1231", ...

"Step-by-step guide on populating a select box with data from the scope

Hey everyone, I'm new to using Angular and hoping for some help with a simple question. I've created a form (simplified version below) that I want users to see a live preview as they fill it out. Everything was going smoothly with regular field ...

Tips for displaying live data in the rows of Element UI's Table

Recently, I've been working with a table that looks like this. <v-table :data="data"> <v-table-column prop="data.attribute" label="Attribute"> </v-table-column> </v-table> Instead of displaying data.attribute in the co ...

Issue with AngularJs failing to display data

As a newcomer to AngularJS, I am looking to utilize AngularJs to display the Json output from my MVC controller. Here is the code snippet for my MVC Controller that generates Json: [HttpGet] public JsonResult GetAllData() { ...

Issues with JQuery Ajax rendering in browser (suspected)

I'm encountering an issue on my webpage. I have a div with two hidden fields containing values of 0 and 2, respectively. Upon clicking a button that triggers an AJAX query, the div contents are updated with hidden field values of 1 and 2. However, it ...

Optimal method for transmitting an image as a JSON object from an SQL database using C#

I have a scenario in C# where I am retrieving an image as a byte array. My goal is to send this image as JSON, but currently the code returns it as a memorystream. var note = reader["Note"].ToString(); var price = (decimal)rea ...