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

Error encountered: Jquery counter plugin Uncaught TypeError

I am attempting to incorporate the JQuery Counter Plugin into my project, but I keep encountering an error: dashboard:694 Uncaught TypeError: $(...).counterUp is not a function <!DOCTYPE html> <html lang="en"> <head> <script src ...

Dealing with cross-origin AJAX posting in Node.js处理Node.js中的

My app.js contains the following handler for POST requests: app.all('/', function (req, res, next) { res.header("Access-Control-Allow-Origin", "*"); res.header("Access-Control-Allow-Headers", "X-Requested-With"); next(); }); app.opt ...

Angularfire allows for easy and efficient updating of fields

Currently, I am working on creating a basic lateness tracker using AngularFire. So far, I have successfully added staff members to the miniApp and set the initial late minutes to a value of 0. My challenge lies in updating these values. Ideally, when a us ...

What are the necessary headers that must accompany a post request?

While testing the server with Postman, everything seems to be working fine as I receive a response: https://i.stack.imgur.com/yMRfj.png However, when attempting to make a POST request from the browser using the same address, it results in an error and th ...

What is the best way to change the color of my Material Icons when I move my cursor over them?

Currently, I am integrating mui icons 5.2.0 into my React application. Although the icon appears on the page, it remains unchanged in color when I try to hover over it. Check out the snippet of code that I have implemented: import EditIcon from '@mu ...

Obtain an individual item from the reducer array

I am working on a company reducer that will store an array of companies. To optimize performance, I aim to fetch only the necessary company object from my API when a user navigates to /company/name. This way, if a user visits the same company page multiple ...

Ways to efficiently populate HTML elements with JSON data

I am working on grasping the concept of functional programming. My understanding so far is that it involves encapsulating everything into functions and passing them around. For instance, in my current example, I am attempting to fetch data from a RESTApi a ...

Eliminate duplicated partial objects within a nested array of objects in TypeScript/JavaScript

I'm dealing with a nested array of objects structured like this: const nestedArray = [ [{ id: 1 }, { id: 2 }, { id: 3 }], [{ id: 1 }, { id: 2 }], [{ id: 4 }, { id: 5 }, { id: 6 }], ] In the case where objects with id 1 and 2 are already grou ...

Incorporating a timer feature into the code for my memory game

Seeking the optimal method to incorporate a timer into my memory game. This game comprises numerous squares, and when the user successfully completes it, a modal appears congratulating them on their win and providing an option to restart the game. The obj ...

Guide on building a multi-page application using Vue or React

I find myself a bit confused when it comes to single-page applications versus multi-page applications. While I am aware of the difference between the two, I am struggling with creating a MPA specifically. Up until now, I have built various apps using Rea ...

The option menu for selecting one item appears empty instead of displaying the default first string value

My editable selectOneMenu is working correctly in terms of resetting/repopulating when the previous selectOneMenu changes. However, it always displays blank instead of showing the first value - 'Please select/Enter statement' <p:selectOneMenu ...

Using an Ajax Post request to trigger a JavaScript function

Looking to execute a JavaScript function with a PHP variable, I utilized an AJAX request to send the variable named [filename] for executing the JavaScript function as follows: upload.php <script> function prepareforconvert(filenamse){ ...

Enhancing Struts2 JSON Plugin: Including ActionMessages, ActionErrors, and FieldErrors in the response

While working on my jQuery Ajax posts, I want to include any actionmessages, actionerrors, and fielderrors in the response (in JSON format). Here is what I added: <result name="input" type="json"> <param name="ignoreHierarchy">false&l ...

Utilizing Javascript to share images from a public Facebook page to a user's timeline via the Facebook API

Can someone assist me with finding a way to share a photo from a public Facebook page to the user's timeline using JavaScript? Is it possible to achieve this with FB.api or FB.ui? I have successfully shared feeds to the timeline using FB.ui, but am no ...

Ways to address Path Traversal vulnerability in the following code

const downloadFile = blobstoreRouter.get('/blobstore/download/:filename', (req, res) => { var localFile = path.join(__dirname, '..', escape(req.params.filename)); var file = require('fs').createWriteStream(localFile); try { ...

Exploring the benefits of WordPress integration with form caching and dynamic show/hide div

Within my Wordpress (3.8.1) website, I have created a form that includes a checkbox. When this checkbox is clicked, a hidden div appears on the screen, prompting users to provide additional information. The JavaScript code responsible for showing the hidd ...

Using JavaScript, learn how to extract query parameters and encoded information from a URI

I am looking for a specific module in order to extract information from query parameters within a URL. The format includes 2 query parameters and an encoded piece of data. Do I need to use split functions or is there a more direct approach available? Sampl ...

Activate the element only when all input fields are completed. This function can be used repeatedly

I am working on developing a versatile function that will iterate through all input fields. If any of these fields are empty, I want to trigger the toggling of a class name (disabled) on another element (such as an anchor or button). Currently, the functi ...

The format provided is not utilized by Datetimepicker

I've encountered an issue with the Date Time Picker provided by JQuery. Despite setting a specific format, it seems to be using its default date format which results in the following error appearing in the console: Uncaught TypeError: F.mask.replace i ...

Error encountered using jQuery $.post: TypeError - e.type is not a valid function

I'm currently in the process of developing a feedback script specifically for the ZetaBoards forum software. My approach has been to create a $.post function, but when I attempt to submit the form by clicking the submit button, all I get in return is ...