KenP
KenP

Reputation: 77

Issue using Django to pass JSON to Javascript

I'm using Django to return a JsonResponse to a script that is supposed to handle JSON and get coordinates for me. There seems to be something wrong when I try and use the JSON information in the javascript. For example, if i try to use data.something , its undefined. Here is my View:

def getTweets(request, tag):
    d = {'string': tag}
    req = tweets.objects.filter(tag = tag)
    data = serializers.serialize('json', req, fields=('coord'))
    data = JsonResponse(data, safe=False)
    print data


    return data

And here is the part of the JS I am currently using:

$('#searchButton').click(function(){
                    xmlhttp = new XMLHttpRequest();
                    var tag = document.getElementById('tagSearch').value;
                                        if(tag.substring(0,1) === '#'){tag=tag.substring(1,tag.length);}
                                        document.getElementById('tagSearch').value = '';

                                        xmlhttp.onreadystatechange = function() {
                                            if (this.readyState === 4 && this.status === 200) {
                                                    var data = JSON.parse(this.response);

                                                    var pinColor = ''+(Math.random()*0xFFFFFF<<0).toString(16); ...........

So, I am using JSON.parse(this.response) to get this from Django, which returns a string. But as I said, something is seemingly wrong or I am completely missing how to access this.

This is from my Django server console:

"[{\"model\": \"visualize.tweets\", \"pk\": 1, \"fields\": {\"coord\": \"-76.958123, 38.827518\"}}, {\"model\": \"visualize.tweets\", \"pk\": 3, \"fields\": {\"coord
": \"-96.958123, 48.827518\"}}]"

And, what I want to be able to do (or something similar):

var coordString = point['coord'];
var x = coordString.substring(0,coordString.indexOf(','));
var y = coordString.substring(coordString.indexOf(',')+2,coordString.length);

Upvotes: 0

Views: 85

Answers (1)

user4426017
user4426017

Reputation: 2000

You data is encoded as JSON twice. I have had it working like shown below:

def getTweets(request, tag):
    d = {'string': tag}
    data = tweets.objects.filter(tag = tag).values('id', 'tweet', 'whatever')
    data = JsonResponse(list(data), safe=False)
    print data


    return data

Upvotes: 1

Related Questions