The File is not being successfully sent to the controller in MVC due to AJAX returning an undefined value

I recently created an AJAXUpload method within a cshtml file in my C# MVC project:

function AjaxUpload(url, method, data, successFunction, errorFunction, skipErrorDlg) {
    $.ajax({
        contentType: false,
        processData: false,
        url: url,
        data: data,
        type: method,
        dataType: 'json',
        beforeSend: function (xhr) {
            xhr.setRequestHeader('Authorization', GlobalAuthToken);
        },
        success: function (data) {
            successFunction(data);
        },
        error: function (event, jqxhr, settings, thrownError) {
            console.log(thrownError);
        }
    });
}

Below is the snippet of HTML code for my file component:

<input type="file" class="file" id="attachment" style="display: none;" onchange="fileSelected(this)" accept=".csv"/>

In my Javascript code, I am making use of the above-defined method like this:

function fileSelected(input) {
    console.log("Chosen file: " + input.files[0].name);

    var data1 = new FormData();
    data1.append("ImportedFile", input.files[0]); 


    AjaxUpload('/Zetes.ZWS.Processes.Rest/api/importbundles',
        'POST',
        data1,
        function () {
            console.log("Import completed");
        }); 
}

Unfortunately, I keep encountering an undefined error when trying to execute this AJAX call. I experimented with different options and discovered that setting processData: false results in the undefined exception.

Removing that line altogether led to an Illegal Invocation Exception.

Any thoughts or suggestions on how to resolve this issue?

Answer №1

Feel free to rearrange this code snippet according to your needs. It's been tested and verified in my own application, so hopefully it works well for you too.

 $.ajax({
         url: url,
         type: "POST",
         data: data,
         contentType: false,
         processData: false,
         success: function (data) {
           handleSuccess(data);
         },
         error: function (event, jqxhr, settings, thrownError) {
           console.log(thrownError);
         }
 });

You may also want to check out this link for more information.

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

Having trouble initiating an AJAX request

I'm currently facing an issue with inserting data into the database using AJAX. I have set up an ajax call to a servlet that is responsible for inserting data into the database. However, it seems like there might be an error in how I initialized the a ...

Is it necessary for the error event of xmlhttprequest to include an error message?

Currently, I am in the process of developing an AJAX request within a Firefox extension. The following code snippet illustrates my approach: function GetMenu(){ var oReq = Components.classes["@mozilla.org/xmlextras/xmlhttprequest;1"].createInstance(); ...

`Heart-shaped loading bar in Reactjs`

Looking for help in creating a heart-shaped progress loader for a React project. I attempted using CSS but encountered issues with the progress not filling the entire heart design. Below is the code snippet I used. The progress should start from the bottom ...

How can I add a comma after every third number in a react component?

I am currently developing an input feature where I need to insert a comma after every 3 numbers, such as (352,353,353). The challenge is to display this format in a text field. Since I am new to working with React, I would appreciate any guidance on how to ...

Update Webpage with Ajax

I'm facing a situation where I need to execute a Java method that sets request properties, and these changes should be visible on the JSP page. <script type="text/javascript"> setInterval(function() { ajaxAction($('#refresh'), & ...

Failure to Establish Active Directory Connection

Hey there, I could really use some assistance. I'm pretty new to working with active directory and I'm trying to establish a connection with C#. Below is a snippet of the code I've put together: public void GetConnection() { var usernam ...

What is the best method for enabling communication between two users when the identification numbers created by socketIO are automatically generated?

Hey there, hope you're doing well. I've been pondering a question that has left me stumped. I recently came across a course that explained how to send a message to a specific user using socketIO.js by utilizing the `to()` method and passing the ...

Struggling with a problem in the PHP MySQL login functionality

I have encountered an internal server error while using my login function, and I cannot seem to identify the issue upon reviewing the function. Below is the initial version of my login function: function login($username, $password) { if (!isset($user ...

Tips for invoking an Android function from an AngularJS directive?

I am facing an issue with my HTML that uses an AngularJS directive. This HTML file is being used in an Android WebView, and I want to be able to call an Android method from this directive (Learn how to call Android method from JS here). Below is the code ...

Using a pipe filter to implement a search feature in an Ionic search bar

Hey everyone, I'm facing a little issue here. I created a pipe filter to sort through some data, but now I need to include two more filters and I'm not sure how to go about it within this pipe. Below is an example of the pipe I have created: ...

MUI options - The specified type 'string' cannot be matched with type '"icon" | "iconOnly" | "text" | "outlined" | "contained" | undefined'

Is it possible to utilize custom variants in MUI v5? I am having trouble using a custom variant according to their documentation: https://mui.com/material-ui/customization/theme-components/#creating-new-component-variants declare module "@mui/material ...

FancyBox refuses to "pop"

I have been struggling for 2 hours to get FancyBox to work, and I cannot figure out why it is not working. It seems like I am missing something because instead of the image popping up, it just takes me to a new page. For example: I have linked both the th ...

Vue: Develop a master component capable of displaying a sub-component

Is there a way to design a main component that is able to accept and display a subcomponent? Take the following scenario for instance: <Container> <Item/> <Item/> <SubMenu/> <Btn/> </Container> ...

Get only the text content from a hyperlink using Tinymce-4

Within tinymce.activeEditor, I currently have this line of innerHTML code (part of a ul-list): <li><a href="#">Important words</a></li> When I place the caret within the sentence "Important words," and click a button with the foll ...

Checking if the group of radio buttons has been selected using JQUERY

Need help with validating a group of radio buttons. If none are checked, display an error message in the span element to prompt users to select an option. The strange issue I am facing is that the validation code works only when placed below the radio butt ...

Is it possible to extract around 10 variables from a JavaScript code, then display them on a webpage after execution?

I have just completed writing a Javascript code with around 3,000 lines. This code contains over 60 variables, but there are a few specific variables that I would like to display on my main HTML page. These variables include: totalTime longitudinalAcceler ...

What is preventing me from creating accurate drawings on canvas?

I'm currently working on a paint application and facing an issue. When I place the painting board on the left side of the screen, everything works fine and I can draw without any problems. However, when I move it to the right side of the screen, the m ...

Using JQuery tools to perform doc ready initialization in a script that is dynamically loaded via Ajax

My jQuery tools based tabs are working perfectly, but I'm facing an issue when loading a page via AJAX that contains scripts from another party. They have provided the following code snippet to be executed once their script is ready: $(functi ...

Tap on the image to enlarge

I have a question regarding using thumbnails from Bootstrap. I am trying to create functionality where when I click on a thumbnail, the picture with its original sizes appears and then disappears when clicked anywhere else on the page. Below is an exampl ...

sending a string to opencart through ajax

I'm currently facing an issue with my Opencart website. I'm attempting to utilize ajax on the frontend to send data to a php controller on the backend, but I'm having trouble extracting the value from the request in the backend. Here is the ...