2

I want to pass a variable returned as a response to the zope template into a javascript variable in pyramid.

here's the views code :

def return_table(request):
selected = request.params.getall("selectedcategories")

return {'selected': selected}

and here's the template :

<script tal define:"selected ${selected}">
    var selected = ${selected}
    $.ajax({
        type:"POST",
        url: '/return_table.json?selectedcategories=' + selected,
        async: false,
        success: function (response) {
            console.log(response)
        }
   })
</script>

But this is not working. I want to pass the value of selected into the javascript variable.

Mudits
  • 1,513
  • 3
  • 20
  • 37

2 Answers2

2

The safest way is to pass variables as HTML5 data attributes, or in <meta> inside <head>.

<script id="my-script" data-selected="${selected}">
    $(document).ready(function() {

        var selected = $("#my-script").attr("data-selected");

        $.ajax({
            type:"POST",
            url: '/return_table.json?selectedcategories=' + selected,
            async: false,
            success: function (response) {
                console.log(response)
            }
       })
    });
</script>

More information about data attributes: http://caniuse.com/#feat=dataset

You could also generate <script> snippet exposing variables as JavaScript globals like this and then read global variables directly in your JavaScript code:

<script>
     window.myVar = "${selected}";
</script>     

<script>
     ... code goes here ...
</script>

... but I do not recommend, as variables containing user input would open your site to attacks and escaping JavaScript variables inside HTML is difficult. It is handy though, if you need to pass several variables - you can use json.dumps() against a Python dictionary to generate a JavaScript object containing all your variables.

Mikko Ohtamaa
  • 82,057
  • 50
  • 264
  • 435
  • Hey i did as u suggested i am getting this error ExpressionError: invalid syntax - String: "${selected}" – Mudits Jun 02 '14 at 08:19
  • if i do this var selected = ${structure:selected} in the chrome developers tools in the sources section it shows var selected = ["Campaign__c"] which means the selected variable is getting passed but when i do a console.log(selected) it shows undefined. – Mudits Jun 02 '14 at 08:27
  • Do you run your script after document load event has been fired or when the HTML page is being generated (see the example above). Make sure your script tag has id `my-script` and inspect it with jQuery. – Mikko Ohtamaa Jun 02 '14 at 08:28
1

Use

var selected=${structure:selected};

and remove

tal define:"selected ${selected}"

in the script tag.

Mudits
  • 1,513
  • 3
  • 20
  • 37