Go to main content

Reload Javascript after postback in Kentico

For any kind of form web parts, I like using update panel to avoid full page reload when the form is submitted. In such situation, a postback is invoked. When you execute a Javascript code on page load, it won't run after postback. In this post, I will provide you with a code snippet that fixes this issue.

Reload Javascript after postback in Kentico

I recommend using update panel mostly for UX reasons. When a visitor submits a form, just the form gets updated instead of the whole page. The visitor doesn't lose focus and receives an instant response. Update panel could be activated for a web part in its web part properties in the AJAX section.

A problem comes into play when you execute a Javascript code that manipulates the form. It won't run if you initialize the script using, for example, self-invoking functions or the document ready event in case of using jQuery.

// These won't work after postback
(function () {
    // Your functionality here
})();

$(document).ready(function () {
    // Your functionality here
})

Instead, you need to, let's say, re-register the script on postback. Below, see an example that demonstrates the usage. 

  1. Create a function that does the desired functionality.
  2. Execute the function on page load.
  3. Re-run the function after postback.
// 1. Create a function that does the desired functionality
var yourFunction = function () {
    // Your functionality here
};

// 2. Execute the function on page load
yourFunction();

//3. Re-run the function after postback
var prm = Sys.WebForms.PageRequestManager.getInstance();
if (prm != null) {
    prm.add_endRequest(function (sender, e) {
        if (sender._postBackSettings.panelsToUpdate != null) {
            yourFunction();
        }
    });
};
Milan Lund

is a freelance web developer and a proud Basenji owner. His specialties are Kentico CMS/EMS and Kentico Cloud.

Further reading

all posts
  • Kentico Cloud

    Request Kentico Cloud Delivery API in Node.js

    I've already done a few websites with Kentico Cloud in Node.js and I would like to share my experience. In this article I will show you how to request Kentico Cloud Delivery API in…

  • Kentico Cloud

    Multiple requests to Kentico Cloud Delivery API in Node.js

    In this article I will give you a code example that demonstrates how to make multiple endpoint requests and get one response object. 

  • Front-end & JavaScript

    Simple cookie bar

    EU cookie legislation requires website owners to inform visitors about the use of cookies. In this article, I will provide you with a simple solution of an informative cookie bar.