Anupam
Anupam

Reputation: 15610

Javascript syntax error in Django Template when variable value is missing

I have a Django template with an AJAX menu (where clicking on different menu items reloads a part of the page). Each menu click invokes a Django view function through AJAX and returns some data to be shown on the page.

I am loading all the JS required for all the menu items in the main page only (as I learnt that it is not a good idea for AJAX to return JS in a <div> and then use eval() to execute it). Since I am loading all the JS on the menu's main page only, the data obviously isn't there for other menu options at start since it will come later when the corresponding view is invoked (when the menu option is clicked)

Because of that, code like the one below gives a syntax error on the console since JS is parsed the very first time only.

<script> var data = {{se_data|safe}}; </script>

Now I am not able to use the data returned from the view, even after I click the menu options, since the JS parsing failed in the first place. I tried using if to execute the code only when the corresponding menu option is selected but that too does not work since the parser just parses everything.

I have been trying different methods to get around the issue but cant seem to find an efficient way to solve this. An alternative could be to have the view function return all the data at first only, but I fear that the menu options and the data returned may grow over time, hence delaying the initial load of the main menu page.

This is the ajax menu's click function:

$(".ent-menu li a").click(function(e) {
    e.preventDefault(); // prevent from going to the page mentioned in href
    // get the href
    var href = $(this).attr("href");

    $("#data_container").load(href, function() {
        load_data(); //this function uses the data variable defined earlier
    });
});

Error I see in the console when loading the menu's main page:

Uncaught SyntaxError: Unexpected token ;     at line 1110
data = ;

since the data is not available yet.

Upvotes: 1

Views: 948

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599580

As discussed, you should use JSON to send the data from Python to JS; use JSON.parse() to deserialize the data for use in your JS.

Upvotes: 1

Related Questions