0

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);

1 Answer 1

1

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
Sign up to request clarification or add additional context in comments.

1 Comment

Oh god.. can't believe I stared at that for so long and didn't see that. Thank you!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.