Retrieving FormData using ajax and passing it to aspx.cs code

After adding a debugger in the console, I am receiving confirmation that the file has been uploaded successfully. However, the debugger is not reaching the code behind, or in other words, the code behind is not accessible.

This is the JavaScript file:

function uploadFile() {
           debugger
           var fileInput = document.getElementById("myFile");
           var file = fileInput.files[0];

       if (file) {
           var applicationID = selectedApplicationID;
           var orderID = $("#txtOrderID").val();
           var companyID = $("#tdCompanyID").text();
           var orderedDate = $("#tdOrderedDate").text();
           var instaProductName = $("#tdReport").text();

           var data = new FormData();
           data.append("ApplicationID", applicationID);
           data.append("CompanyID", companyID);
           data.append("OrderID", orderID);
           data.append("OrderedDate", orderedDate);
           data.append("ProductName", instaProductName);
           data.append("uploadedFile", file);

           // Make an AJAX request to the server to upload the file
           $.ajax({
               type: "POST",
               url: "InstaReportsDownloader.aspx/UploadFile",
               data: data,
               contentType: false,
               processData: false,
               success: function (response) {
                   // Handle the success response
                   console.log("File uploaded successfully!");
                   console.log(response);
               },
               error: function (xhr, status, error) {
                   // Handle the error response
                   console.log("File upload failed!");
                   console.log(error, status, xhr);
               }
           });
       }
   }

And this is the code behind:

    [System.Web.Services.WebMethod(EnableSession = true)]
    public string UploadFile(int ApplicationID, int CompanyID, int OrderID, DateTime OrderedDate, string ProductName, HttpPostedFile uploadedFile)
    {
        string DataDirectory = ConfigurationManager.AppSettings["DataDirectory"].ToString();
        string folderPath = null;

        if (ApplicationID == 4)
        {
            folderPath = Path.Combine(DataDirectory, "XML Reports", CompanyID.ToString(), ProductName);
        }
        else if (ApplicationID == 5)
        {
            folderPath = Path.Combine(DataDirectory, "InstaAPI Reports", CompanyID.ToString(), ProductName);
        }

        // Create the directory if it doesn't exist
        Directory.CreateDirectory(folderPath);

        // Generate the file name based on the OrderedDate
        string fileName = $"Report_{OrderedDate.ToString("mm/dd/yyyy")}.xml";
        string filePath = Path.Combine(folderPath, fileName);

        // Save the uploaded file to the specified path, overwriting if it already exists
        uploadedFile.SaveAs(filePath);

        return filePath;
    }

Answer №1

Whenever you do not specify the data format as xml or json, and include the following code:

contentType: false,
processData: false,

You are essentially not invoking a webmethod anymore.

Consider what happens when you click a standard button?

The entire page gets posted back, along with the formdata().

So, essentially, the code example creates your own custom post-back!!!!

With this format, you cannot, and are not, calling a web method anymore.

The response you receive will actually be the entire web page!

In this case, you need to check for "some" value in the form() and act accordingly.

This requires using the page load event.

In this scenario, IsPostBack will be false since there was no full submission of the page.

Therefore, you can disregard the web method (it will be ignored anyway).

You do not have any parameters from a web method, but you can access the formdata values.

And the response you receive may not be very useful, as you will receive a web page on the client side.

For example, the JavaScript code:

        <input id="Button11" type="button" value="ajpost"
            onclick="TestFun();return false"
            />

        <script>

            function TestFun() {

                var myForm = new FormData()
                myForm.append("test", "test")
                myForm.append("FirstName", "Albert")

                $.ajax({
                    type: "POST",
                    url: "AJPostTest.aspx",
                    data: myForm,
                    contentType: false,
                    processData: false,
                    success: function (response) {
                        // Handle the success response
                        console.log(response);
                    },
                    error: function (xhr, status, error) {
                        // Handle the error response
                        console.log("File upload failed!");
                        console.log(error, status, xhr);
                    }
                });
            }

        </script>

Then, in the page load event, you can retrieve this information like so:

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (Page.Request.Form["test"] != null) 
            {
                // we have "test", so that's our ajax post call
                Debug.Print("Name passed = " + Page.Request.Form["FirstName"].ToString());
            }
        }
    }

Output:

https://i.sstatic.net/D2utH.png

Thus, the provided code essentially creates your own custom page post-back, rather than invoking a web method.

You will need to handle that data and the posted data in the page's on-load event.

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

Prevent regex from matching leading and trailing white spaces when validating email addresses with JavaScript

In my current setup, I utilize the following regular expression for email validation: /^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\.[a-z]{2,4}$/ My attempt to validate the email is shown below: if (!event.target.value.match(/^[a-zA-Z0-9._%+-]+@[a-z0-9.-]+\. ...

Sending POST Requests with Node and ExpressJS in the User Interface

Just diving into the world of Node.js and Express.js, I'm attempting to create a form submission to an Express.js backend. Below is a snippet of the code I am working with: var author = 'JAck'; var post = 'Hello World'; var body ...

Executing a file upload using ng-click="upload('files')" within Selenium Webdriver

Is it possible to automate a file upload when the HTML code does not include an < input type='file' > instead, uses a link <a ng-click="upload('files')"> File Upload </a> Clicking this link opens a file selector f ...

Press a button to activate a function on a dynamically created table using Ajax

On my website, I have an ajax function that dynamically generates a table and displays it inside a designated div. Below is the PHP code called by the Ajax function. echo "<table border='1' cellspacing='12' cellpadding='4' ...

Unable to retrieve data from SpringBoot controller using $http.get request

I have developed an application that will execute queries on my store's database based on user input on the webpage. The backend method is functioning correctly and returns the response, but I am having trouble displaying the data in a dynamic table o ...

Tips for showcasing JSON data within an array of objects

I'm trying to work with a JSON file that has the following data: {"name": "Mohamed"} In my JavaScript file, I want to read the value from an array structured like this: [{value: "name"}] Any suggestions on how I can acc ...

Error encountered when attempting to insert data into a PostgreSQL database using Node.js and Sequelize

I'm currently using the node sequelize library to handle data insertion in a postgress database. Below is the user model defined in the Users.ts file: export class User extends Sequelize.Model { public id!: number; public name: string; public ...

How to select the li element in a nested menu using jQuery

My goal is to extract the text from a specific li element when it is clicked on. The code snippet provided below outlines the structure: <div> <ul> <li>list item 1</li> <li>list item 2</li> <li> ...

When trying to validate an HTML form using AJAX, jQuery, and JavaScript, the validation may not

Here is a high-level overview of what happens: The following code functions correctly... <div id='showme'></div> <div id='theform'> <form ...> <input required ... <input required ... <inpu ...

What are some cookie serialization techniques in JavaScript and PHP?

I have a form with multiple select options that I want to save in a cookie for user convenience. The goal is to make the serialization of the cookie easily readable in both JavaScript and PHP, allowing me to set the form onLoad and filter search results ba ...

"Trouble with JavaScript boolean values in if-else conditions - not functioning as expected

While utilizing true/false values and checking if at least one of them is true, I am encountering an issue with the if/else statement not functioning as expected. Here is the code snippet: $scope.checkValues = function (qId) { var airport = $scope.air ...

Adjust background color on click using JavaScript

Could someone provide me with the JavaScript code to change the background color of a page from blue to green when a button is clicked? I have seen this feature on many websites but haven't been able to write the code myself. I am specifically lo ...

.npmignore failing to exclude certain files from npm package

I'm facing an issue with a private module on Github that I am adding to my project using npm. Despite having a .npmignore file in the module, the files specified are not being ignored when I install or update it. Here is what my project's packag ...

How to trigger an Angular JS route without loading a view

Could someone help me with calling the /auth/logout url to get redirected after a session is deleted? app.config(['$routeProvider',function($routeProvider) { $routeProvider .when('/auth/logout',{ controller:'AuthLo ...

Triggering a parent component function after a child component function finishes in Vue

When using Vue, I have a main component housing a child component that is loaded onto the page with a button triggering the saveTaskComment() function. Everything works perfectly until it reaches the .finally portion of the child component's function. ...

Utilizing asynchronous methods within setup() in @vue-composition

<script lang="ts"> import { createComponent } from "@vue/composition-api"; import { SplashPage } from "../../lib/vue-viewmodels"; export default createComponent({ async setup(props, context) { await SplashPage.init(2000, context.root.$router, ...

Issue with JavaScript HTML Section Changer not functioning properly

I need to implement a button that switches between two pages when pressed. Although the code seems simple, I am struggling to make it work. HTML <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"& ...

Creating a PHP script that retrieves data from JavaScript and stores it in MySQL can be accomplished by using AJAX to send the

Hello, I am attempting to create a PHP script that can extract coordinates from this JavaScript code (or from this link ) and store them in a MySQL database. Can someone please provide me with a tutorial on how to accomplish this? <script> var ...

Is Socket.io exclusive to browsers?

Similar Question: Using socket.io standalone without node.js How to run socket.io (client side only) on apache server My website is hosted on a Linux server with shared hosting. Since I don't have the ability to install node.js, I am looking ...

Identifying the precise image dimensions required by the browser

When using the picture tag with srcset, I can specify different image sources based on viewport widths. However, what I really need is to define image sources based on the actual width of the space the image occupies after the page has been rendered by th ...