What is the best way to retrieve responsetext from a Page utilizing the Post method in asp.net with XMLHttpRequest?

I am working on a web page that needs to send a video file/blob to another web page using FormData and the POST method with XMLHttpRequest. My goal is to receive a response as a string from the called URL in the calling function. Essentially, after successfully uploading the file, I want to return a string to the caller.

index.aspx:


function SendFile(blob) {
  var file = new File([blob], "testfile123.webm");
  var oData = new FormData();
  oData.append("file", file,"testfile.webm");
  var oReq = new XMLHttpRequest();
  oReq.open("POST", "upload.aspx", true);
  oReq.onload = function (oEvent) {
    if (oReq.status == 200) {
      alert("Uploaded"+oReq.responseText);
    } else {
      alert("Error");                     
    }
  };
  oReq.send(oData);
}

Upload.aspx:


protected void Page_Load(object sender, EventArgs e) {
  string folderPath = GetUploadFolderPath();
  string filename = DateTime.Now.ToString("dd-MM-yyyy-HH-mm-ss") + ".webm";  
  HttpFileCollection fileCollection = Request.Files;
  for (int i = 0; i < fileCollection.Count; i++) {
    HttpPostedFile postedFile = fileCollection[i];
    var filePath = folderPath + filename; 
    postedFile.SaveAs(filePath);
  }             
}

In the above code, the file is created at the specified location and everything works correctly. I understand that it is not possible in the Page_Load event. Can someone suggest the correct method to send a response text/string after the file upload?

Your help is greatly appreciated.

Answer №1

Here is an example showcasing how to target specific functions within an ASPX file using jQuery.ajax in VB.NET. Please note that I am more familiar with VB.NET than C#.

If you are using an older version of .NET (2 or lower), make sure to include System.Web.Extensions in your web.config either as httpModules or as modules depending on your IIS configuration.

AJAX.aspx

<WebMethod(EnableSession:=True)> _
Public Shared Function abc(def As String) As Boolean
    ''REM: Do stuff
    Return True
End Function

XHR call using jQuery

$.ajax({
    type: "POST",
    url: "AJAX.aspx/abc",
    data: "{'def':'test'}",
    contentType: "application/json; charset=utf-8",
    dataType: "text",
    success: function(response){...},
    error: function(jqXHR, textStatus, errorThrown){...}
});

However, it is recommended to use generic handlers for such tasks as they offer better control and do not require the use of System.Web.Extensions. You can find an example here.

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

The speed of response in MondoDB/Mongoose queries is unacceptably sluggish

As a newcomer to MongoDB/Mongoose, I am dealing with a substantial database containing over 25000 documents. My goal is to set up various queries, such as searching by fields, retrieving the first 10 documents, and fetching one by ID. However, I am struggl ...

Error 2300 in Vetur: Identical identifier found for '(Missing)'

Recently, I've been encountering a strange issue with Vetur in my typescript nuxt.js project. Every component, whether it's just an empty line or contains code, displays an error message on the first line. I can't pinpoint when this problem ...

Is there a way to reallocate values on a charts.js pie chart when a legend item is toggled?

I have evenly distributed the data in the pie chart to total 100% (at least I think so), but could you please verify if it's correct? Additionally, I would like to be able to dynamically re-distribute the data when toggling legend items. Below is a s ...

The event.js file is displaying an error at line 141, causing an unhandled 'error' event to be thrown

Trying to execute node 4.2.2 on a Mac OS is causing me some confusion as I keep encountering this error message: events.js:141 throw er; // Unhandled 'error' event ^ Error: spawn /Users/user/Documents/Projects/project-x/node_modules/ ...

Tips for sending multiple forms and having PHP interpret it as a single form using $.ajax

I am working on an email function using $.ajax with 3 different forms that are loaded through an ajax request. When a user clicks on a button, the current form will disappear and a new form will appear. The challenge I am facing is how to send data from al ...

"The alert() function in Javascript takes precedence over the code that came before it

When I have a contact form with a submit button, my goal is to use JQuery to change the button text to "Send" and display the received response in an alert, once a response is received from the server-side PHP processing the submitted data. Change button ...

Display only the labels of percentages that exceed 5% on the pie chart using Chart JS

I'm currently diving into web development along with learning Chart.js and pie charts. In my project, the pie chart I've created displays smaller percentage values that are hardly visible, resulting in a poor user experience on our website. How c ...

Using React to create a fadeout effect and decrease the length of the photo

Is there a way to create a fade-out effect for each photo card and then shorten the length of the photos following the fade out? I have tried implementing a solution, but it doesn't seem to work when I click on each photo. Any suggestions or insights ...

Having trouble getting Laravel Full Calendar to function properly with a JQuery and Bootstrap theme

Using the Laravel full calendar package maddhatter/laravel-fullcalendar, I am facing an issue where the package is not recognizing my theme's jQuery, Bootstrap, and Moment. I have included all these in the master blade and extended it in this blade. ...

Why does JavaScript display a width of 800px for the Motorola Atrix MB860 4G? Shouldn't it actually be 540px?

When developing my Mobile Web App, I encountered an issue with getting the screen width of different devices to fit the views dynamically. I am puzzled by the fact that the Motorola Atrix MB860 is reporting a width of 800px despite having a resolution of ...

The jQuery css method fails to apply styles to SVG circle elements

HTML: <div class="container"> <article class="caption"> <svg class="grid-point" width="100" height="100" style="height: 120px; width: 625px;"> <circle class="myPoint" cx="50" cy="50" r="5" fill="#80E1EE" / ...

Enhancing forms with unique membership options

I am managing a website that relies on the asp.net membership tables (ASP 3.5 site). To streamline user management, I plan to upload user data from an Excel sheet directly into the membership tables using a form. After using a simple app to process the Exc ...

Troubleshooting issue with Bootstrap's responsive scrollspy functionality

I am experiencing an issue with the responsiveness of my page. When I reduce the width of the page to half, the scrollspy disappears unexpectedly. I am unsure about the root cause of this problem. If you run the code I have shared here, you can observe th ...

Steps to enable the click feature on a table-responsive column within innerHTML

I'm encountering an issue with displaying DataTable content in a div on my page using the code snippet below: $('#' + divid + '-data')[0].innerHTML = data.TableContent; The TableContent is retrieved from a different method and lo ...

Why does the jQuery .ajax() POST Request result in a 405 (Method Not Allowed) error while the GET request does not?

Currently, I am working on updating a form using ajax. The process runs smoothly when I utilize the GET method in ajax. However, an error of 405 method not allowed is thrown when I switch to using the Post method. This testing is being conducted on Localho ...

By setting `queue: false` when calling jQuery's `show()` method, you can

When looking at the code below, it is clear that even though showLoader is the first call, the loader does not appear immediately. This delay is due to the fact that heavyLifting function is blocking the UI thread. function onClick() { showLoader(); ...

Avoid filling the container with an excessive amount of grids while maintaining the correct aspect ratio

I encountered a situation where I needed to dynamically create a grid with square grids of dimensions MxN. Below is the code snippet for achieving this: rerender = (event) => { const height = document.getElementById("y-input").value; const width ...

When a specific condition is fulfilled, I must retrieve a random response from a designated array

I'm looking for a way to create a system where users can select multiple items and then generate a random answer from those selected options. Currently, I have a setup that requires manual input of options in a comma-separated format, but I want to st ...

What steps can be taken to hide empty items in a list from being shown?

When I map over an array of books to display the titles in a list, I encounter an issue with the initial empty string value for the title. This causes the list to render an empty item initially. Below is my book array: @observable books = [ {title:" ...

I am looking to correlate information from my database with the options available in the Google location dropdown menu

Check out my website Currently under construction. Please go to the above link and click on SIGNUP TO DRIVE (Blue curve Button). A tab will open, type london (do not select from dropdown menu) and press enter. The page will redirect to dev.appcotech.com/p ...