Praful Bagai
Praful Bagai

Reputation: 17382

How to receive a list in jQuery from Django(Python)

I'm send a list from Django(Python) to jQuery, but it is throwing some error while receiving it?

Here is what I send in python.

hubcode_list = ['a','b']
ctx = {'form':form, 'hubcode_list' : hubcode_list, 'admin_permission' : admin_permission}
return render(request, 'dummy/config.html', ctx)

jQuery:-

var hubcode_list = {{ hubcode_list }}

It returns an error saying :-

SyntaxError: syntax error
var hubcode_list = ['a', 'b']

When I use escapejs as

var hubcode_list = {{ hubcode_list|escapejs }}

it throws

SyntaxError: illegal character
var hubcode_list = [\u0027a\u0027, \u0027b\u0027]

How do I receive a list from server(Python)? I need to implement an autocomplete functionality where I need to pass a list of tags.

$( ".hubcode_list" ).autocomplete({
        source: hubcode_list
    });

Upvotes: 1

Views: 2221

Answers (4)

Gabriel
Gabriel

Reputation: 1149

Did you tried something like:

import json
ctx = {'form':form, 'hubcode_list' : hubcode_list, 'hubcode_json': json.dumps(hubcode_list), 'admin_permission' : admin_permission}
return render(request, 'dummy/config.html', ctx)

In your jQuery you can do something like

var parsed_json = eval("({{ hubcode_json }})");

or

var parsed_json = $.parseJSON("{{ hubcode_json }}");

Ok, is not the cleanest way but it works, at least, for me.

Upvotes: 0

pynovice
pynovice

Reputation: 7752

hubcode_list = [str(i) for i in hubcode_list]  #unicode string not understood by javascript
{{ hubcode_list|safe }}

The good way is to pass json.

>>> import json
>>> hubcode_list = ['a','b']
>>> json.dumps(hubcode_list)
>>> '["a", "b"]'

jQuery:

var hubcode_list = JSON.parse(hubcode_list)

If you want to implement jquery Autocomplete, you should implement it via AJAX. You shouldn't pass all the autocomplete at once. What if there are thousands of data? See this tutorial on how to implement jquery autocomplete with Django.

Upvotes: 3

Daniel Roseman
Daniel Roseman

Reputation: 599610

Some of the other answers are on the right track, but aren't clear enough.

To pass data from Python to Javascript, use JSON.

hubcode_list = json.dumps(['a','b'])

Upvotes: 0

cor
cor

Reputation: 3393

You can use SafeString

from django.utils.safestring import SafeString
...
return render(request, 'dummy/config.html', {'ctx': SafeString(ctx)})

But ctx needs to be a valid json format variable

Upvotes: 0

Related Questions