The mechanism for transferring data from the server to the client using JavaScript is malfunctioning

In my webform, I have a fileupload control and a button. When the button is clicked after selecting a file to upload, the image should be saved and renamed with a unique GUID.

protected void btnUpload_Click(object sender, EventArgs e)
{
    string fileName = string.Empty;
    string filePath = string.Empty;
    string extension = string.Empty;
    try
    {
        // Check if Fileupload control has a file
        if (FileUpload1.HasFile)
        {
            // Get selected image extension
            extension = Path.GetExtension(FileUpload1.FileName).ToLower();
            // Check if image is of a valid type
            if (extension == ".jpg" || extension == ".jpeg" || extension == ".png" || extension == ".gif" || extension == ".bmp")
            {
                // Create a unique name for the file
                fileName = Guid.NewGuid().ToString() + extension;
                // Create a path for the image to store
                HiddenField1.Value = fileName;
                filePath = Path.Combine(Server.MapPath("~/Images"), fileName);
                // Save the image in a folder
                FileUpload1.SaveAs(filePath);
                // Show the panel and load the uploaded image in the image control.
                // pnlCrop.Visible = true;
            }

The code above successfully saves the image and sends the GUID to the hiddenfield. Now, I want to retrieve the value of the hiddenfield in a client-side variable and display it as an alert.

  <script type="text/javascript">
    function showfilename() {       
        setTimeout(function () {
            var dpGUID = document.getElementById('<%= HiddenField1.ClientID %>').value;
            alert(dpGUID);
        },3000)
    }
</script>

Why use a timeout? I need to ensure that I read the value of the hiddenfield only after it has been assigned a value on button click.

It is possible to use two functions on a button click, one on the client side and one on the server side, as shown here:

 <asp:Button ID="btnUpload" runat="server" OnClick="btnUpload_Click" Text="Button" OnClientClick="showfilename()" />

Is this setup causing any issues?

Answer №1

Consider implementing a RegisterClientScriptBlock

protected void btnUpload_Click(object sender, EventArgs e)
{
    /*All your code here*/
    //instead of HiddenField1.Value = fileName; write the line below
    ScriptManager.RegisterClientScriptBlock(this, typeof(Page), "callJsFunction", "alert('" + fileName + "');", true);
}

You can now eliminate both the OnClientClick="showfilename() and the HiddenField

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

Handling Circular Dependency: Injecting a Service into an HTTP Interceptor in AngularJS

I'm currently working on developing an HTTP interceptor for my AngularJS application to manage authentication. Although the code I have is functional, I am wary of manually injecting a service as I believed Angular is designed to handle this process ...

Issue with React-Toastify not displaying on the screen

After updating from React-Toastify version 7.0.3 to 9.0.3, I encountered an issue where notifications are not rendering at all. Here are the steps I followed: yarn add [email protected] Modified Notification file import React from "react" ...

Using client-side navigation within an integrated Shopify application

Seeking assistance in implementing client-side routing with react-router within a Shopify app that is embedded. Following the guidelines provided by Shopify on this page, but unsure about what needs to be included in a ./Routes file. Attempted to find rela ...

Integrate an external script with React and initialize a new instance

I've been working on integrating a neat canvas background feature from this GitHub project into my React web application. Here's what I've attempted: import {WarpSpeed} from './warpspeed.js' import WarpSpeed from './warpspee ...

What is the best way to vertically center a button against a video using CSS?

How can I vertically center a button against a video using CSS? Here is my code: https://jsbin.com/curefoyefe/edit?html,css,js,output <video controls="" ng-show="myForm_live_video.live_video.$valid" ngf-src="live_video" width="200" height="200" class= ...

The forEach method in JavaScript seems to work asynchronously

After reviewing other discussions on this platform, it seems that the general agreement is that forEach should be synchronous and block. However, in my code, something appears to be off as it doesn't behave that way: var noDupes = false; // se ...

I'm curious about where to find more information on this new technology called the 'scroll to page' feature

Recently, I came across a captivating website feature that caught my eye. As someone relatively new to front end web development, I am intrigued by the scrolling technique used on this site. I'm specifically drawn to the 'page to page' scro ...

What is the best way to insert HTML elements in front of other HTML elements using a form and jQuery?

I am looking to insert new HTML elements before existing ones using a form and jQuery: Here is the initial HTML Code: <div class="main-content"> <h2 class="main-content-header">Projekte</h2> <div class="project-content"> ...

Steps for changing the datetime format

Hi, I have a textbox for the user to input a date in dd/mm/yyyy format and an AJAX calendar extender to select the date. I am encountering issues with converting the date to mm/dd/yyyy format for insertion into a SQL Server database. The conversion works f ...

Ways to break down a collection of multiple arrays

Looking to transform an array that consists of multiple arrays into a format suitable for an external API. For example: [ [44.5,43.2,45.1] , [42, 41.2, 48.1] ] transforming into [ [44.5,42], [43.2,41.2] , [45.1, 48.1] ] My current code attempts this ...

Ways to monitor the status of a server request using jQuery (ajax)?

I am currently working on a PHP application that involves users submitting forms to the server via ajax (jQuery). The server needs to insert a large number of records into a MySQL database, which may take some time due to various calculations. My question ...

When the document is shifted by an angular function call, the mouseup event fails to trigger

My problem involves an angular function that alters the ng-if state to display the sidebar when the image is clicked. However, upon calling the function and shifting the entire webpage, the mouseup event for the image no longer triggers when I release th ...

Attempting to iterate through a JSON object containing nested objects and arrays of objects

For hours, I've been struggling to navigate through this json file with no success. When I log the data, it shows that Response is an Object, data is also an object, and saleItemCategories is an array containing four objects. The first object in the ...

Node.js utilized for conducting anti-virus scans on server-bound files prior to uploading

Is there a way for me to scan files that are submitted as request payloads to check if they contain potential viruses? For example, if someone tries to upload a txt file with the EICAR virus signature, I want to be able to scan it and reject it if it is in ...

Strategies for transferring information to a different component in a React application

Building a movie site where users can search for films, click on a card, and access more details about the film is proving challenging. The problem lies in transferring the film details to the dedicated details page once the user clicks on the card. An onc ...

What is the best method for extracting information from this data? (extracting data from

I need assistance. I've written multiple arrays to a text file and now I'm trying to parse them. What am I doing incorrectly? fs.readFile("./data.txt", "utf8", function(error,dataRes){ console.log('Reading data') ...

javascript the unseen element becomes visible upon page loading

my website has the following HTML snippet: function getURLParameters() { var parameters = {}; var parts = window.location.href.replace(/[?&]+([^=&]+)=([^&]*)/gi, function(m,key,value) { parameters[key] = value; }); return param ...

Exploring the functionality of componentWillReceiveProps within functional components

Embarking on my journey with functional components after extensively working with class components. While experimenting, I encountered a challenge: how can I incorporate the functionality of componentWillReceiveProps within the context of the useEffect h ...

What could be causing TypeScript to throw errors when attempting to utilize refs in React?

Currently, I am utilizing the ref to implement animations on scroll. const foo = () => { if (!ref.current) return; const rect = ref.current.getBoundingClientRect(); setAnimClass( rect.top >= 0 && rect.bottom <= window.i ...

Introduce a timeout in the ajax request

I'm currently facing an issue with adding a 2-second delay between the loader icon and the success message displaying the data as html. I attempted to use setTimeout in my ajax code with a specified delay number, but it doesn't seem to be workin ...