Conquistador
Conquistador

Reputation: 129

sending json data from django-view to ajax

I am trying to transfer json data from django view to template by using ajax.
Here is my ajax code:

$(document).ready(function(){
    console.log("this is getting executed")
    $.ajax({
           url: "/get_ecommdata/",
           type: "get",
           cache: "false",
           dataType : 'json',
           success: function(data) {
              console.log("This is working fine")
              alert(data)
           },
           error:function(xhr, ajaxOptions, thrownError) {
              console.log("this is error")
                alert(xhr.status)
           },
  })
});

View is as below:

def get_ecommdata(request):
    print "inside get_ecommdata"
    tempdata = ['{"square": 0, "key": 0}', '{"square": 1, "key": 1}', '{"square": 4, "key": 2}']
    return HttpResponse(tempdata)

status code is 200 but still "this is error" is displayed on console i.e. its executing error part.

Here is what I understand:

status code is 200 i.e. server is sending data properly but there is some issue identifying the datatype. This code is working fine for simple text but not for json.

My Question

Can someone give me some directions about passing json data from django-view to ajax. I think I am making some stupid mistake here.

P.S. I have gone through other posts which are similar (json,ajax,view) but none of them caters to this specific question.

Upvotes: 0

Views: 966

Answers (2)

cafebabe1991
cafebabe1991

Reputation: 5186

import the json module

import json

Then Try this in your request method

data = json.dumps([{"square": 0, "key": 0}, {"square": 1, "key": 1}, {"square": 4, "key": 2}])    

return HttpResponse(data, content_type="application/json")

NOTE

Using single quotes as in your snippet would result in the following output

'["{\\"square\\": 0, \\"key\\": 0}", "{\\"square\\": 1, \\"key\\": 1}", "{\\"square\\": 4, \\"key\\": 2}"]'

Its confusing for a seeker , hence i used the above method. But it depends on choice.

Upvotes: 1

Paulo Pessoa
Paulo Pessoa

Reputation: 2569

def get_ecommdata(request):
    print "inside get_ecommdata"
    list_square = [
        {"square": 0, "key": 0},
        {"square": 1, "key": 1},
        {"square": 4, "key": 2}
    ]
    data = json.dumps(list_square)
    return HttpResponse(data, content_type='application/json')

Upvotes: 0

Related Questions