Search code examples
javascriptajaxdjangoformsdajaxice

How to activate django form.media javascript on an ajax loaded form?


I have a little issue here :
I've got a form containing some media due to its widgets.
Everything works as expected when the form is part of the page but if I want to load that form using an ajax call, in a modal for example, even though the js script is included with the form, it's not running. The css is working perfectly fine on the other hand.

I guess this has something to do with javascript not being able to detect a new script tag has been included.

What should I need to do to run this js ?

Code sample :

modal form template :

{{form.media}}
{% crispy form %}
<a class="close-reveal-modal">&#215;</a>

template rendered inside modal :

<div id="level-modal" class="reveal-modal" data-reveal="">
  <link href="/static/ajax_upload/css/ajax-upload-widget.css" type="text/css" media="all" rel="stylesheet">
  <script type="text/javascript" src="/static/ajax_upload/js/jquery.iframe-transport.js"></script>
  <script type="text/javascript" src="/static/ajax_upload/js/ajax-upload-widget.js"></script>
  <form id="level-form" class="foundation-form" method="post" enctype="multipart/form-data"></form>
  <a class="close-reveal-modal">×</a>
</div>

Solution

  • After some research I finally found the correct way to enable loaded javascript files.
    Note that jquery is required.
    It's a simple $.ajax({{dataType: "script", cache: true, url: "url/file.js"}})

    As I was talking about form.media, you can retrieve all scripts needed by the form doing this :

    files_url = []
    for js in form.media._js: # for all the scripts used by the form
        files_url.append(form.media.absolute_path(js)) # we retrieve their url
    

    As I'm using dajax to enable the scripts, I can make a simple call to dajax.script to enable the scripts :

    loaders = []
    for js in level_form.media._js:
        loaders.append('$.ajax({{dataType: "script", cache: true, url: "{0}"}})'.format(level_form.media.absolute_path(js)))
    
    dajax.script("""
        $.when(
            {0}
        ).done(function() {{
            console.log("scripts are loaded !");
            // do something here when files are loaded
        }}).fail(function () {{ 
            alert("An error occured, try reloading the page.");
            // do something here if loading failed
        }});""".format(",\n".join(loaders)))
    

    Beware ! You'll need to add DAJAXICE_XMLHTTPREQUEST_JS_IMPORT = False in your settings.py, see this subject for details.