Login

Load dynamically loaded form javascript assets using dajax

Author:
PhilipGarnero
Posted:
February 22, 2015
Language:
Python
Version:
1.7
Score:
0 (after 0 ratings)

I am used to load forms directly into modals using dajax but I found out I had to load the scripts using an ajax call from the browser.
You can see here an example of a dynamically loaded form and the function used to load the scripts.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
def dajax_load_form_assets(dajax, form, done=None, fail=None):
    """
    Dynamically loads all the scripts contained in the form media section.
    dajax -- already instanciated Dajax object
    form -- form from where to load the scripts
    done -- js actions to be executed when scripts are loaded
    fail -- js actions to be executed when scripts failed to load
    """
    if done is None:
        done = "console.log(\"form scripts loaded via ajax\");"
    if fail is None:
        fail = "alert(\"An error occured, try reloading the page.\");"

    loaders = []
    for js in form.media._js:
        loaders.append('$.ajax({{dataType: "script", cache: true, url: "{0}"}})'.format(form.media.absolute_path(js)))

    dajax.script("""
        $.when(
            {0}
        ).done(function() {{
            {1}
        }}).fail(function () {{ 
            {2}
        }});""".format(",\n".join(loaders), done, fail))

@dajaxice_register(method='POST')
def ajax_func(request, form=None)
    dajax = Dajax()
    if form is not None:
        my_form = MyForm(form)
        #do stuff with my_form
    else:
        my_form = MyForm()

    # load your form into the web page
    dajax.assign('#modalform', 'innerHTML',
                render_to_string('modalform.html',
                                {'form': my_form,
                                 'button_action': "Dajaxice.app.ajax_func(Dajax.process, { 'form': $('#my-form').serializeJSON() } ); return false;",
                                },
                                context_instance=RequestContext(request)))

    # load form's javascript assets
    dajax_load_form_assets(dajax, my_form)

    return dajax.json()

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 11 months, 2 weeks ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 11 months, 3 weeks ago
  3. Serializer factory with Django Rest Framework by julio 1 year, 6 months ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 1 year, 7 months ago
  5. Help text hyperlinks by sa2812 1 year, 8 months ago

Comments

Please login first before commenting.