user2667066 user2667066 - 1 year ago 81
Ajax Question

web2py: how to detect when an LOAD component has loaded via ajax?

I'm injecting a component into my web2py page using

as described at, but I need to fire off some javascript once the component is loaded. Normally if something is loaded via ajax, there is a success callback. How can I set one of this via
in web2py?

Answer Source

The simplest approach would be to set response.js in the controller of the component:

def mycomponent():
    response.js = 'alert("mycomponent just loaded");'
    return dict()

Alternatively, you could simply include a <script> tag directly in the component itself, which will execute when the component is loaded.

Finally, whenever a web2py Ajax call completes, an ajax:complete event is fired. So, you could set up an event handler and check whether the Ajax response is a component:

  $(document).on('ajax:complete', function(e, xhr, status) {
    if (xhr.getResponseHeader('web2py-component-content')) {
      alert('A component just loaded.');

Note that the presence of the web2py-component-content header indicates that the Ajax response is a component.

The only downside of this last approach is that the event handler will be triggered before the content of the component is added to the DOM, so if the event handler takes long to run, it may noticeably delay the appearance of the component content.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download