user2667066 user2667066 - 19 days ago 5
Ajax Question

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

I'm injecting a component into my web2py page using

{{=LOAD(...)}}
as described at http://web2py.com/books/default/chapter/29/12/components-and-plugins#LOAD, 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
{{=LOAD(...)}}
in web2py?

Answer

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.