getting an error " jQuery is not defined" after using variable parts in a URL -flask framework

Question:

This is my WEB architecture

Web
|-->static
   |-->css
   |-->js
   |-->img
|-->templates
   |-->test1
   |-->test2
|-->modfunctions
   |-->test1
         |-->main.py
   |-->test2
         |-->main.py

If I use any unique URLs like @app.route('/test2', methods=['GET','POST']), My JQuery part is working fine, but when I tried to add variable parts to a URL like @app.route('module/<data>', methods=['GET','POST']), its throwing error saying ‘jQuery is not defined’ .

Here I have attached my code

from flask import Flask
from flask import render_template, request, redirect

app = Flask(__name__, template_folder='/home/web/templates', static_folder='/home/web/static')

@app.route('module/<data>', methods=['GET','POST'])
def mod_data(data):
    if request.method == 'GET':
        return render_template('test1/page1.html')

    if request.method == 'POST':
        return render_template('test1/page2.html')

if __name__ == "__main__":
    app.debug = True
    app.run(host='0.0.0.0', port=5000)

Please help me in finding my mistake bysharing some solution


Final HTML page

{% extends "base.html" %}

{% block content %}
<table id="grid-table"></table>
<div id="grid-pager"></div>
{% endblock content%}

{% block js %}
<script type="text/javascript">
    var grid_data = [{'Description':'Core A', 'Mask':'True','Mail':'True', 'Trap':'True'},
                 {'Description':'Core B', 'Mask':'True','Mail':'True', 'Trap':'True'},
                 {'Description':'Core C', 'Mask':'True','Mail':'True', 'Trap':'True'},
                 {'Description':'Core D', 'Mask':'True','Mail':'True', 'Trap':'True'}]

    jQuery(function($) {
        var grid_selector = "#grid-table";
        var pager_selector = "#grid-pager";

        jQuery(grid_selector).jqGrid({
                editurl: 'module/new_data',
                data: grid_data,
                datatype: "local",
                height: "auto",
                colNames:['','Module Description', 'Mask', 'Mail','Trap'],
                colModel:[
                    {name:'myac',index:'', width:80, fixed:true, sortable:true, resize:false,
                     formatter:'actions',
                     formatoptions:{
                        keys:true,
                        delbutton:false,
                        }
                    },
                {name:'Description',index:'Description', width:70, sortable:true, editable: false,formatter: returnHyperLink},
                {name:'Mask',index:'Mask',  width: 20, align: 'center',formatter: 'checkbox', editable: true, edittype: "checkbox", editoptions: { value: 'True:False' }, formatoptions: { disabled: true }},
                {name:'Mail',index:'Mail', width: 20, align: 'center',formatter: 'checkbox', editable: true, edittype: "checkbox", editoptions: { value: 'True:False' }, formatoptions: { disabled: true }},
                {name:'Trap',index:'Trap', width: 20, align: 'center',formatter: 'checkbox', editable: true, edittype: "checkbox", editoptions: { value: 'True:False' }, formatoptions: { disabled: true }},

                ],
                pgbuttons:false,
                pginput: false,
                viewrecords : true,

                width : 510,
                pager : pager_selector,
                altRows: true,

                multiselect: true,
                multiboxonly: true,

                loadComplete : function() {
                    var table = this;
                    setTimeout(function(){
                        updatePagerIcons(table);
                        enableTooltips(table);
                    }, 0);
                },

                caption: "Current Settings",
                autowidth: false
                });

                //navButtons
                jQuery(grid_selector).jqGrid('navGrid',pager_selector,
                {   //navbar options
                    edit: true,
                    editicon : 'icon-pencil blue',
                    add: false,
                    addicon : 'icon-plus-sign purple',
                    del: false,
                    delicon : 'icon-trash red',
                    search: true,
                    searchicon : 'icon-search orange',
                    refresh: true,
                    refreshicon : 'icon-refresh green',
                    view: true,
                    viewicon : 'icon-zoom-in grey',
                },
                {
                    //edit record form
                    closeAfterEdit: true,
                    recreateForm: true,
                    beforeShowForm : function(e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                        style_edit_form(form);
                    }
                },
                {
                    //new record form
                    closeAfterAdd: true,
                    recreateForm: true,
                    viewPagerButtons: false,
                    beforeShowForm : function(e) {
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
                        style_edit_form(form);
                    }
                },
                {
                    //search form
                    recreateForm: true,
                    afterShowSearch: function(e){
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                        style_search_form(form);
                    },
                    afterRedraw: function(){
                        style_search_filters($(this));
                    },
                    multipleSearch: true,
                },
                {
                    //view record form
                    recreateForm: true,
                    beforeShowForm: function(e){
                        var form = $(e[0]);
                        form.closest('.ui-jqdialog').find('.ui-jqdialog-title').wrap('<div class="widget-header" />')
                    }
                });

        function style_edit_form(form) {
            //update buttons classes
            var buttons = form.next().find('.EditButton .fm-button');
            buttons.addClass('btn btn-sm').find('[class*="-icon"]').remove();//ui-icon, s-icon
            buttons.eq(0).addClass('btn-primary').prepend('<i class="icon-ok"></i>');
            //buttons.eq(1).prepend('<i class="icon-remove"></i>')

            buttons = form.next().find('.navButton a');
            buttons.find('.ui-icon').remove();
            buttons.eq(0).append('<i class="icon-chevron-left"></i>');
            buttons.eq(1).append('<i class="icon-chevron-right"></i>');
        }

        function style_search_filters(form) {
            form.find('.delete-rule').val('X');
            form.find('.add-rule').addClass('btn btn-xs btn-primary');
            form.find('.add-group').addClass('btn btn-xs btn-success');
            form.find('.delete-group').addClass('btn btn-xs btn-danger');
        }

        function style_search_form(form) {
            var dialog = form.closest('.ui-jqdialog');
            var buttons = dialog.find('.EditTable')
            buttons.find('.EditButton a[id*="_reset"]').addClass('btn btn-sm btn-info').find('.ui-icon').attr('class', 'icon-retweet');
            buttons.find('.EditButton a[id*="_query"]').addClass('btn btn-sm btn-inverse').find('.ui-icon').attr('class', 'icon-comment-alt');
            buttons.find('.EditButton a[id*="_search"]').addClass('btn btn-sm btn-purple').find('.ui-icon').attr('class', 'icon-search');
        }
        function beforeEditCallback(e) {
            var form = $(e[0]);
            form.closest('.ui-jqdialog').find('.ui-jqdialog-titlebar').wrapInner('<div class="widget-header" />')
            style_edit_form(form);
        }
        //replace icons with FontAwesome icons like above
        function updatePagerIcons(table) {
            var replacement =
                {
                'ui-icon-seek-first' : 'icon-double-angle-left bigger-140',
                'ui-icon-seek-prev' : 'icon-angle-left bigger-140',
                'ui-icon-seek-next' : 'icon-angle-right bigger-140',
                'ui-icon-seek-end' : 'icon-double-angle-right bigger-140'
            };
            $('.ui-pg-table:not(.navtable) > tbody > tr > .ui-pg-button > .ui-icon').each(function(){
            var icon = $(this);
            var $class = $.trim(icon.attr('class').replace('ui-icon', ''));
            if($class in replacement) icon.attr('class', 'ui-icon '+replacement[$class]);
            })
        }
        function enableTooltips(table) {
            $('.navtable .ui-pg-button').tooltip({container:'body'});
            $(table).find('.ui-pg-div').tooltip({container:'body'});
        }
{% endblock js %}   

Base.html

<!DOCTYPE html>
<html lang="en">
<head>
</head>

<body>
    {% block content %} {% endblock content%}
        <!-- basic scripts -->


    <script type="text/javascript">
        window.jQuery || document.write("<script src='static/js/jquery-2.0.3.min.js'>"+"<"+"/script>");
    </script>

    <script type="text/javascript">
        if("ontouchend" in document) document.write("<script src='static/js/jquery.mobile.custom.min.js'>"+"<"+"/script>");
    </script>
    <script src="{{ url_for('static', filename='js/bootstrap.min.js') }}"/>
    <script src="{{ url_for('static', filename='js/typeahead-bs2.min.js') }}"></script>
    <!-- page specific plugin scripts -->
    <script src="{{ url_for('static', filename='js/modal/jquery.simplemodal.js') }}"></script>
    <script src="{{ url_for('static', filename='js/modal/osx.js') }}"></script>

    <script src="{{ url_for('static', filename='js/date-time/bootstrap-datepicker.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jqGrid/jquery.jqGrid.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jqGrid/i18n/grid.locale-en.js') }}"></script>

    <!-- sedona scripts -->
    <script src="{{ url_for('static', filename='js/sedona-elements.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/sedona.min.js') }}"></script>
    <script src="{{ url_for('static', filename='js/jqGrid/jquery.jqgrid.functions.js') }}"></script>


    {% block js %}{% endblock js %}

</body>

Asked By: user2955338

||

Answers:

I think on your block JS, you might be overwriting your jquery grab. Try doing a {{ super() }} at the top of your {% block js %}. Although, this is really only a guess as I have made this mistake a few times

Alternatively, from what your comments suggest, jquery was loaded AFTER your javascript ran. On the template it inherits from, does the block where jquery is defined come before, or after, the {% block js %}?

Answered By: corvid

The problem is in the way you reference the jQuery library:

window.jQuery || document.write("<script src='static/js/jquery-2.0.3.min.js'>"+"<"+"/script>");

static/js/jquery-2.0.3.min.js is a relative URL, which means it changes depending on the current document URL. For example, if you are on a page /foo/, it will try to load /foo/static/js/jquery-2.0.3.min.js (and fail). You need to use the url_for() helper for jQuery, too. Something like this (untested):

window.jQuery || document.write("<script src='{{ url_for('static', filename='js/jquery-2.0.3.min.js') }}'>"+"<"+"/script>");
Answered By: sk1p
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.