0

I was trying to fetch Django object in JSON format to my javascript variable. I have used from django.core import serializers predefined method available in Django, to convert it into JSON format. When I was trying to fetch that object directly into Jinja tag then it prints all the data, but when I was trying to get that data in Javascript variable then it won't work.

view.py

from django.http import HttpResponse
from django.shortcuts import render
from .models import Employee
from django.core import serializers
import json

def home(request):
    data = serializers.serialize("json", Employee.objects.all())
    return render(request,'home.html',{'data':data})

home.html

<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
</head>
<body>
    {% extends 'masterpage.html' %}

    {% block content %}
    **{{data | safe}}**(go below for output)
    <form action="checkEmail" method="POST">
        {% csrf_token %}
         <input type="text" name="emailId" placeholder="Enter Email Id">
        <input type="submit">
    </form>
    {% endblock %}
    <p id="demo"></p>

    <script type="text/javascript">
        var data=eval('('+'{{data}}'+')');
        var p=10;
        document.getElementById("demo").innerHTML=p
        console.log(p)
        console.log(data);
        alert(data);
    </script>
</body>
</html>

Output : [{"model": "journal.employee", "pk": 1, "fields": {"ename": "Piyush Jiwnae", "eemail": "[email protected]"}}]

I can see the output for direct use of jinja tag in HTML but when I try to get that value in javascript variable it won't come and as shown in code I was trying to show that data and var p=10; document.getElementById("demo").innerHTML=p this value also not printed on console.

2
  • is alert(data) is working? Commented Jan 8, 2020 at 13:53
  • @sandeep - no, even that also not working Commented Jan 8, 2020 at 14:00

2 Answers 2

0

you could pass data as JSON and parse this object in js with JSON.parse

Sign up to request clarification or add additional context in comments.

2 Comments

no man still it not working, forget about the JSON object my question is why not var p=10 value also not shown on console ??
by using data = serializers.serialize("json", Employee.objects.all()) I can successfully send the JSON data but not getting JSON data on JavaScript variable
0

If I see it correctly your script is raising an error at that line:

var data=eval('('+'{{data}}'+')');

saying something like

SyntaxError: expected property name, got '&'

In the raw format your data renders to something like:

[{&quot;model&quot;: &quot;stack.employee&quot;, &quot;pk&quot;: 

If you mark data variable as safe you should get a proper json object:

var data=eval('('+'{{data|safe}}'+')');

Edit: Another issue in your code:

Your extends tag in the wrong place. You should put {% extends 'masterpage.html' %} at the top of the template, not in your <body> tag. And then you should take out the <head> tag in your template because this is probably already in your masterpage.html

3 Comments

No, even though I have passed like var data=eval('('+'{{data}}'+')'); thus, but still I didnt get any error on my console.
I have tried with your suggestion also, but still it's not working.
Then I beleive there is another issue. See my post edit. If that still doee not work please also post your masterpage.html

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.