Run JavaScript code after the completion of loading a generic handler in ASP.NET

I am facing a challenge with a gridview that contains a list of pdf files. Whenever a user clicks on a pdf, it should display the file inline on the page. I have been trying to execute some javascript after the pdf has finished loading, but I'm encountering difficulties. The main issue seems to be that the pdf loads last, causing the load event to trigger before the pdf even begins loading.

Initially, I attempted to use an iframe solution where the inner page would fetch the file and write the data to the response. However, this approach also led to the same problem of the load event occurring prematurely. Currently, my code utilizes a generic handler (ashx) to load the pdf inline from the server side. How can I ensure that an event executes javascript only after the pdf data has been successfully loaded through the ashx generic handler?

Aspx page:

protected void GridView1_RowCommand(object sender, GridViewCommandEventArgs e)
{
    if (e.CommandName == "View")
    {
        int index = Convert.ToInt32(e.CommandArgument.ToString());
        string Id = GridView1.DataKeys[index].Value.ToString();
        HtmlGenericControl myObject = new HtmlGenericControl();
        myObject.TagName = "object";
        Panel1.Controls.Add(myObject);
        myObject.Attributes.Add("data", "GetPdf.ashx?Id=" + Id);
    }
}

Generic handler ashx:

public void ProcessRequest(HttpContext context)
{
    System.Diagnostics.Debug.WriteLine("GetPdf.ashx started");
    string Id = context.Request.QueryString["Id"];
    byte[] data = GetPdf(Id);
    context.Response.ClearContent();
    context.Response.ContentType = "application/pdf";
    context.Response.AppendHeader("Content-disposition", "inline");
    context.Response.AddHeader("Content-Length", data.Length.ToString());
    context.Response.BinaryWrite(data);
    System.Diagnostics.Debug.WriteLine("GetPdf.ashx is done");
    context.Response.End();
}

Answer №1

Have you attempted to create an event handler for the object tag's onload event? It may not be universally compatible, so make sure to consider which browsers you want it to function on.

If all else fails, you can resort to using setTimeout to continuously check for the presence of the PDF file.

Refer to this previously given answer that addresses both of these potential solutions.

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

In order to make Angular function properly, it is crucial that I include app.get("*", [...]); in my server.js file

Recently, I delved into server side JavaScript and embarked on my inaugural project using it. The project entails a command and control server for my own cloud server, operating with angular, Expressjs, and bootstrap. Presently, I am encountering challeng ...

Tips for overlaying an image on a div regardless of its height

(!) Although this question may seem repetitive, I have not been able to find a suitable solution in any of the previous 10 topics. I apologize for the inconvenience and am actively seeking a resolution to this unique situation; Allow me to outline the iss ...

Learn the process of encoding a string in JavaScript or jQuery and then decoding it with PHP

I am facing an issue with updating a field in the database using Ajax and PHP. Everything runs smoothly except when there are special characters present, like this: اللهم اني اشكو اليك ضعف قوتي وقلة حيلتي وهواني عل ...

Troubleshooting: Issues with Three.js Node TextureLoader

Currently, I am working on rendering objects server-side using node with three.js. I have successfully implemented the OBJLoader and MTLLoader, and I am utilizing MockBrowser to simulate the DOM. Strangely, when I take a screenshot of the model, I can se ...

Iterating through each data attribute using a jQuery each loop

I've encountered an issue with resetting data attributes post-animation and have been attempting to implement a method found on answer 2 of a related thread. I'm a bit stuck on what might be causing the problem. It should theoretically be possib ...

The application freeze is being caused by the Lodash isEqual function

While developing a React component, I have set the default export as shown below: React.memo(MyReactComponent, isEqual) The isEqual function used here is from the lodash library. The issue I am facing is that my application tries to update the component ...

Customize Bootstrap radio buttons to resemble standard buttons with added form validation styling

Is there a way to style radio buttons to look like normal buttons while maintaining their functionality and form validation? I have two radio buttons that need styling but should still behave like radio buttons. Additionally, I am utilizing Bootstrap for s ...

Tips for optimizing overloaded functions

Here are the methods: public MyReturnType MyMethod(Class1 arg) { //implementation } public MyReturnType MyMethod(Class2 arg) { //implementation } //... public MyReturnType MyMethod(ClassN arg) { //implementation } The classes Class1 through ClassN ...

What features are not compatible with this NHibernate 5 query?

When updating my Asp.Net application from NHibernate 4 to NHibernate 5, I encountered an error: 'query.ToList()' threw an exception of type 'System.NotSupportedException' Data: {System.Collections.ListDictionaryInternal} HResult ...

Create a web page utilizing the React library

After creating a function that is working well, I encountered an issue when trying to implement the following code: const successPage = () => { firebase.auth().onAuthStateChanged((user) => { if(user) { console.log("calling su ...

Error Checking in AngularJS Form Submission

According to my form.json file, I have a form that needs validation and a simulated submission. Firstly, I need to address this issue: fnPtr is not a function Next, I want to submit the form to a mocked API endpoint that will return true or false. Can I ...

HTTP POST request is being blocked due to cross-origin request

My angular client app is sending http requests to a .NET core web API, but I'm encountering a CORS error even though I have enabled CORS. Interestingly, GET requests to my SearchController work fine without any issues, but when it comes to sending a P ...

My WordPress loadmore function is not providing any additional posts

Hey everyone, I'm facing a Wordpress issue that I can't seem to resolve. I've checked other posts but haven't found the solution yet. So, I decided to share my code here and seek help. My problem is with trying to load more posts using ...

Tips for implementing PHP Instagram Signature using AJAX

I'm facing a challenge with the latest Instagram API, which now requires an Enforced Signed request that includes both an Access Token and Client Secret to generate a Signature. If anyone could spare some time to help me out, I would greatly apprecia ...

There seems to be an issue with the fetch HTTP PATCH request when using the /:id suffix. However, the DELETE

I am facing an issue with correctly fetching the http with the trip._id suffix. The DELETE method works perfectly fine. However, when I attempt to use PATCH, I encounter an error stating "http://localhost:4000/api/tracks/undefined 404 (Not Found)". Strange ...

Using Angularjs and PHP: incorporating URL parameters into the $http.get() function

I am currently working on a web project in Eclipse with three main files: "controller.js", "home.html," and "array.php". The goal is for the .php file to echo a PHP array encoded in a JSON string: <?php $arr = array(array(title => "hello", auth ...

Leveraging JQuery animation to manipulate the spinning of HTML jackpot

I have been using the following code to simulate a spinning wheel for users. It is functional, but I am facing an issue where the rotation stops abruptly at a specific circle before applying the style for the winning circle. My query is: Is there any way ...

Error: The `gatsby require.resolve` function cannot locate the specified module when attempting

Currently, I am referring to the tutorial at and have already set up my gatsby-node.js file. Here is how my current directory structure looks like: public src -pages -templates --program_group.js static gatsby-config.js gatsby-node.js In my gatsby-node. ...

Upon introducing the CSS loader into the webpack configuration, TinyMCE unexpectedly ceases to function

My application development journey began with cloning code from https://github.com/DMPRoadmap/roadmap. This project is based on webpack and npm. To integrate select2, I executed npm install select 2 in the lib/assets directory. I aimed to incorporate a ...

"Utilizing Javascript filtering to narrow down results based on date ranges within a Vue

I'm currently using Vue within a Laravel application. Most of the functionality is working as expected, except for the last part. I've been struggling to come up with the right search terms for this scenario. Apologies if this question has alread ...