An error occurred when making an Ajax call through WebClient.DownloadString(url) in the Controller, resulting in an HTTP

Within a JavaScript function, I am making a typical ajax call:

$.ajax({
            type: 'GET',
url: '@Url.Content("~/Incident/LookUpStudent")',
            data: { userInput: userInputStudentLDN },
            success: function (result) { //doing stuff here}
});

This call directs to the following method in the controller:

    public string LookUpStudent(string userInput)
    {
        if (string.IsNullOrWhiteSpace(userInput)) { return "Student not found. Please try again."; }

         try
        {
           var fetchedData = new WebClient().DownloadString(JSONUrl); //download the data from the URL
        }

        //return statement and other stuff here
    }

The issue arises when I reach this part of the code:

new WebClient().DownloadString(JSONUrl);

Although the fetchedData is retrieved successfully, my current page immediately receives a 404 error. This added "Action" at the end of the URL triggers the error. Here is the specific error message:

Description: 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.  Please review the following URL and make sure that it is spelled correctly. 

Requested URL: /Incident/Action

I'm puzzled as to why this additional "Action" is appended to the URL and causing the 404 error. How can I resolve this?

Based on Kosala W's answer, I made the following edit:

            var req = { userInput: userInputStudentLDN };
        $.get('@Url.Content("~/Incident/LookUpStudent")', { userInput: req }, function (result) {
            //result is your response from the controller
        });

Answer №1

Revise your jQuery implementation as shown below.

 var newData = { term: document.getElementById("SearchTerm").value, classNum: document.getElementById("ClassNumberInput").value };
        $.get("/Request/GetUserData", { data: newData }, function (response) {
           //response contains data returned by the server
        });

Update your controller code as follows.

    [HttpGet]
    public JsonResult GetUserData(object data)
    {       
        try
        {
            if (data == null) 
            { 
                throw new Exception("User data not found. Please try again.");
            }
            var fetchedInfo = new WebClient().DownloadString(JSONDataUrl); //fetch data from a specified URL
            return Json(fetchedInfo, JsonRequestBehavior.AllowGet);
        }catch(Exception e)
        {
            return Json(e.Message, JsonRequestBehavior.AllowGet);
        }            
    }

Answer №2

Don't forget to include the type parameter:

$.ajax({
            type: 'GET',
            url: '@Url.Content("~/Incident/LookUpStudent")',
            data: { term: document.getElementById("Term").value, classNum: document.getElementById("ClassNumber").value},
            success: function (result) { //execute code}
});

Answer №3

It's definitely a bit mortifying, but the root of this complication stemmed from incorporating a <button> within an @Html.BeginForm('Action', 'Incident').

The issue arose because the button was automatically triggering form submission (even without expressly specifying type="submit").
Simultaneously, there was a JavaScript Ajax function running upon the button's click event.

Consequently, the Ajax call was executed alongside a post to a fictitious action-result named 'Action'.

A massive thank you to everyone who attempted to provide assistance!

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

When I declare 'i' above the for loop, the output shows as 3 3 3, while declaring 'i' inside the for loop results in an output of 1 2 3

Setting up the variable i before the for loop will result in the output being 3 3 3. let i; for (i = 0; i < 3; i++) { const log = () => { console.log(i); } setTimeout(log, 100); } //Output 3 3 3 If i is declared within the for loop, the o ...

What is the proper way to invoke a method within the same class, Class A?

I'm facing an issue where I need to call the method getData() inside my AJAX function again if a 401 status occurs and the counter is less than or equal to 1. However, for some reason, the method is not being called in that particular scenario. How ca ...

Ways to trigger the keyup function on a textbox for each dynamically generated form in Angular8

When dynamically generating a form, I bind the calculateBCT function to a textbox like this: <input matInput type="text" (keyup)="calculateBCT($event)" formControlName="avgBCT">, and display the result in another textbox ...

Guide to changing request headers in Next.js

I'm looking to include a custom header in each server request. My current approach involves utilizing middleware in the following manner: export async function middleware(req: NextRequest): Promise<NextResponse> { req.headers.append('x ...

The video auto plays in a pop up window, but if the pop up doesn't appear, I can still hear the audio

I recently added a pop-up to my website and attempted to include autoplay functionality. However, I encountered an issue where the sound would still play even if the pop-up did not appear upon refreshing the page. How can I prevent the autoplay when the po ...

Creating Elements with Prototype.js and document.createElement()

Hey there, currently delving into the world of prototype.js and noticing some peculiar behavior. Take a look at this code snippet I executed in firebug: var el2 = document.createElement('div'); var k=0; for(var i in el2){ k++}; console.log(k); ...

What is the reason that an object with a finalizer is not reclaimed by garbage collection even when it is no longer referenced?

Encountering an issue with finalizable objects that are not being collected by GC if Dispose() is not explicitly called has raised some concerns. While it is recommended to call Dispose() on objects implementing IDisposable, the assumption that unreference ...

retrieving JSON data within the controller

When I use the command console.log($scope.data), I am able to view my JSON file. Additionally, by using <div ng-repeat="item in data">, I can see all the items in the view. However, when I try console.log($scope.data[0]) or console.log($scope.data[0] ...

Every time I click a button, I am trying to add JSON objects into an array and then show the outcomes

Currently, my goal is to create a random selection feature from an array that users can contribute to by clicking a button. I am a bit unsure about how to proceed with this task. The application is developed in React and it utilizes the movieDB's API ...

Tips on concealing a table upon opening an HTML page

Hello, I've implemented some JavaScript code that displays a table when hovering over a link and hides it when moving the mouse away. However, I'm facing an issue where I want the table to be hidden when the page first loads. Can anyone help me a ...

Encountering a System.PlatformNotSupportedException error while implementing the MongoDB driver in a .NET 5

I've been facing a challenge with my Blazor WebAssembly (Wasm) application where I am attempting to establish a connection to a MongoDB. Every time I try to execute a method like FindAsync that interacts with the database, an exception is thrown indic ...

Uploading files using AJAX in Ruby on Rails

Does anyone have a simple solution for managing AJAX file uploads in Rails? Perhaps with the help of a plugin? ...

Determining if a Turbolinks request is made in a Rails controller

I'm currently working on a Ruby on Rails 4 project that utilizes the Turbolinks gem. One interesting observation is that when a link is clicked, the layout is still rendered server-side, but the Turbolinks JavaScript only grabs the body portion of thi ...

Expect a promise to be resolved in the RootCtrl of Angular using $http

One of the functions in my RootCtrl is responsible for calling an http api and returning the result. $scope.checkAccess = function(){ var result = MyService.me(); result.then(function(response){ console.log(response); if (response. ...

When extracting data from the formData AJAX request in a Laravel controller, the array(0) { } format is returned

I'm working on a form that includes text and image inputs, and I'm trying to send the data via an ajax request. I'm using dataForm as the format to send to my Laravel controller. However, when I try to retrieve the input from the form, I&apo ...

Having difficulty navigating the dropdown menu with Selenium Webdriver

https://i.sstatic.net/um1dw.pngI need help navigating the dropdown list with the following code: new WebDriverWait(driver, 50).until(ExpectedConditions.elementToBeClickable(By.xpath("//*[@id > =\\\"s2id_autogen4_search\\'] ...

Utilize a PHP foreach loop to extract information from a JSON dataset

I'm having difficulty extracting data like latitude and longitude from the json data below using a php foreach loop. { "deals": [ "division": { "timezone": "Central Time (US & Canada)", "lat": 32.4487, "timezoneOff ...

Iterate over multiple form input variables using PHP

When I iterate through Rice form variables on the PHP side, everything functions properly. <input class="rice" type="text" name="rice[]" > <input class="beans" type="text" name="beans[]" > <input class="price" type="text" name="price[]" > ...

Improving the method for adding an element to an HTML document with jQuery

What is the best way to add this element to a specific DIV Class using JQUERY in an optimized manner? The elements are generated dynamically and I want to use .AppendTo to display them inside <div class='parent-list-workorder'>. This is wh ...

What is the best way to ensure only one checkbox is checked at a time and have it automatically uncheck when another checkbox is selected?

Is there a way to make a checkbox automatically uncheck when another one is checked? For example, when checkbox one is clicked, it should be marked as checked and any other checkboxes should be marked as unchecked. The same behavior should apply when check ...