Embedded Javascript fails to function following an async postback triggered by an UpdatePanel

After embedding some JavaScript files in a server control, everything works fine. However, when the server control is placed within an ajax UpdatePanel, it ceases to function after an async postback triggered within the updatepanel.

This is the code in the server control:

protected override void OnPreRender(EventArgs e)
{
  base.OnPreRender(e);

  ClientScriptManager clientScriptManager = Page.ClientScript;
  const string DATE_TIME_PICKER_JS = "JQueryControls.Scripts.DateTimePicker.js";

  clientScriptManager.RegisterClientScriptResource(typeof(DateTimePicker), DATE_TIME_PICKER_JS);

  if (Ajax.IsControlInsideUpdatePanel(this) && Ajax.IsInAsyncPostBack(Page))
  {
      Ajax.RegisterClientScriptResource(Page, typeof(DateTimePicker), DATE_TIME_PICKER_JS);
  }
}

The Ajax functionality can be found here.

This piece of code runs during the async postback:

public static void RegisterClientScriptResource(Page page, Type type, string resourceName) {
    object scriptManager = FindScriptManager(page);
    if (scriptManager != null) {
        System.Type smClass = GetScriptManagerType(scriptManager);
        if (smClass != null) {
            Object[] args = new Object[] { page, type, resourceName };
            smClass.InvokeMember("RegisterClientScriptResource",
                    System.Reflection.BindingFlags.Static |  System.Reflection.BindingFlags.Public |
                    System.Reflection.BindingFlags.InvokeMethod,
                    null, null, args);
        }
    }
}

Is there any solution to make this work inside an UpdatePanel?

Answer №1

When UpdatePanels trigger a post back, new elements are added to the page. These new elements are not the same as before, so your bindings will no longer be in place. If you're using jQuery and want to tie events together, you can utilize their live API which can be found here. For components like datepickers that only need to fire once and completely change how an item functions, you'll need to execute some JavaScript code after the new elements are loaded; this simply involves linking some JavaScript calls to a callback function provided by Microsoft:

function BindEvents()
{
    //Your jQuery function calls go here
}

var prm = Sys.WebForms.PageRequestManager.getInstance();
prm.add_endRequest(BindEvents);

Edit: Based on your comment, I suggest modifying the DatePicker.js file as follows:

$(document).ready(function () {
    // Call BindDatePicker to bind the DatePicker during initial page load
    BindDatePicker();

    // Add BindDatePicker to PageRequestManager so it's executed after each UpdatePanel load
    var prm = Sys.WebForms.PageRequestManager.getInstance();
    prm.add_endRequest(BindDatePicker);
});

// The actual binding logic of the DatePicker to the input is placed here
// to allow for multiple calls. Any other bindings needed inside the UpdatePanel can also be included here.
var BindDatePicker = function() {
    $('.DatepickerInput').datepicker({
        showAnim: 'blind',
        autoSize: true,
        dateFormat: 'dd-mm-yy'
    });
};

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

Tips for accessing the HTML content enclosed within a specific HTML tag using Python with Selenium

I am trying to extract the source code of an HTML document that is embedded within an <iframe> tag generated by JavaScript. The HTML contents within this <iframe> tag appears as #document, which expands to reveal a full HTML document starting w ...

Creating a Dynamic Input Validation Range with JQuery

Greetings and thank you for taking the time to review this! :-) The form validation is functioning correctly with required fields, but I am facing a challenge with setting up numeric range validation dynamically for an autocomplete feature. The JQuery val ...

How to enable CORS in Flask while avoiding the "Response to preflight request does not have an HTTP ok status" issue

Seeking assistance with setting up client-side Javascript code to send post requests to my Flask backend. I referenced this helpful answer regarding an issue with flask-cors being blocked by CORS policy, resulting in a preflight request error without passi ...

I'm wondering, on a storybook, where is the best place to set my MUI X license key

Can you help with where to specify my license key in Storybook? I need guidance on where to set the license key in Storybook. According to MUI Docs, it should be done before React renders the first component and only once in the application. However, I ...

Achieving Compatibility Between jQuery 3.6.0 and Node.js v12.16.1

Utilizing an online IDE known as Replit, I am working on node.js projects running on the node version: 12.16.1. However, my current challenge lies in attempting to make jQuery 3.6.0 compatible with this particular node.js version. Despite trying various me ...

Is React State with JSON Object Losing Updates?

Encountering a strange issue here. At the start of my program, I load various values into a JSON object stored as a User State Object in a Postgres table. Although the object is quite large, I'll provide an example below. const [person, setPerson] = u ...

Sophisticated method in JavaScript to conceal and reveal div elements

My knowledge of front-end web development is strongest in HTML and CSS, but when it comes to JavaScript, I feel like there must be a more efficient way to achieve the functionality I want. On my website, I have a set of <li> items that, when clicked ...

The browser freezes when attempting to upload an image using an ajax call

I'm currently using this code to upload an image to the server via AJAX, but I've noticed that the browser freezes while the image is being uploaded. Can someone please help me diagnose the issue and find a solution? $(function() { $("#form4 ...

Exploring protractor and webdriver basics in the context of a non-angular application

Currently, I am in the process of writing end-to-end tests for a non-angular application using Protractor. While there is a wealth of information available on how to achieve this, it appears that there are multiple approaches to consider. This has led me ...

Utilizing PHP Variables in Ajax Calls: Transferring Data between JS and PHP

I've been struggling to grasp how to pass information from PHP to JavaScript and vice versa. I've spent an entire night trying to figure this out and would really appreciate it if someone could help me understand how to send two variables to an a ...

Preserve Text Selection While Utilizing DIV as a Button

I wonder if this issue is specific to the browser I'm using? Currently, I'm using Chrome... My goal is to enable users to save any text they've highlighted on the page with their cursor. I've set up the javascript/jQuery/ajax and it w ...

What could be causing my fetch() function to send a JSON body that is empty?

I've been struggling with sending JSON data using fetch as the backend keeps receiving an empty object. In my Client JS code, I have the following: const user = "company1"; const username = "muneeb"; const data = {user, username}; fetch("http://127. ...

Guide on activating an event when a slider image is updated using jquery

I am working on a project that includes a slider. I have been trying to trigger an event when the slider image changes, but so far using the classChange Event has not been successful. Here is the link to my code: [1] https://codepen.io/anon/pen/gzLYaO ...

Manipulate the label content of the last child using Javascript

On my BigCommerce website, I am trying to change the label text of a variable using a JavaScript function since the support team is unable to assist with this. Below is the code snippet that needs modification: <dd class="GiftCertificateThemeList" st ...

"Enhancing user experience through file uploads using the onchange event

I'm currently working on implementing file upload functionality using the onchange event. I encountered an error stating that 'file is not defined.' //html file <input type="file" style="display: none;" onchange="angular.element(th ...

An unusual error occurred stating that the `forEach` property does not exist on the given type

I am working on a chess game and encountering some Typescript errors that I'm struggling to comprehend. The issue arises in the following class method: clickEvent (e: MouseEvent): void { const coordinates: ClientRect = this.chessBoard.getBounding ...

"JQuery's selector is failing to locate elements once they have been loaded through an

I am facing an issue where jQuery selectors are not working on elements loaded from the server via Ajax requests, but they work fine in normal mode. $('#myid').change(function(){ alert('OK!'); }); <select id="myid"> <optio ...

AngularJS - encountering a 404 error when reloading the page after removing the Hashbang

After taking out the hashbang from my routes by using $locationProvider.html5Mode(true); Now, when I go to a page like "domain.com/download", it works. But if I refresh this same page, I get a 404 Error. URLs like "domain.com/download" can only be acce ...

Utilizing a switch to deactivate all currently active classes on individual div elements

I'm currently facing an issue with implementing a toggle feature in a particle manner. I have three divs with onclick events and each has a toggle CSS class. My goal is to ensure that when one div is clicked, if the others are active, they revert back ...

How to launch a new window for a popup

How can I make IE8 open new windows as pop-ups without changing browser settings? I want to use JavaScript's window.open() function. Firefox opens new windows correctly, but IE8 opens them in tabs instead of pop-up windows. Any suggestions on how to a ...