I am trying to render a Json Response on a html site using AJAX but i keep getting the error:
JavaScript
x
3
1
Uncaught ReferenceError: data is not defined
2
at HTMLDocument.<anonymous
3
JsonResponse in Question:
JavaScript
1
2
1
["[53.50119612705815, -1.1270833894501477] -> [53.34474, -3.01101]", "[53.50119612705815, -1.1270833894501477] -> [53.34474, -3.01101]", "[52.04061648544843, -0.6655072691644374] -> [51.90829, -0.5127]", "[52.04061648544843, -0.6655072691644374] -> [51.90829, -0.5127]", "[52.04061648544843, -0.6655072691644374] -> [51.90829, -0.5127]", "[53.50119612705815, -1.1270833894501477] -> [53.42705, -0.94339]"]
2
Html file with AJAX and JS:
JavaScript
1
26
26
1
<div class="'row">
2
<div id="test">
3
<h1> Test </h1>
4
</div>
5
6
</div>
7
{% endblock %}
8
9
{% block js %}
10
11
<script>
12
$(document).ready(function(){
13
$.ajax({
14
type: 'POST',
15
dataType: 'json',
16
url: '/network/dispatch_data/',
17
data: data,
18
success: function(response) {
19
console.log(response);
20
$('#test').append(response.data);
21
}
22
});
23
});
24
</script>
25
{% endblock %}
26
When i inspect element in my browser, the error points to the data: data
being the source of the error. Any idea what i’m doing wrong? I can view the url perfectly with the json response but making it show with ajax is proving a problem
Advertisement
Answer
You are sending data
as the body of your request, but first you have to defined the object you are sending to API
JavaScript
1
31
31
1
<div class="row">
2
<div id="test">
3
<h1> Test </h1>
4
</div>
5
6
</div>
7
{% endblock %}
8
9
{% block js %}
10
11
<script>
12
const data = {
13
bar: [1, 2, 3],
14
foo: false
15
}
16
17
$(document).ready(function () {
18
$.ajax({
19
type: 'POST',
20
dataType: 'json',
21
url: '/network/dispatch_data/',
22
data: data,
23
success: function (response) {
24
console.log(response);
25
$('#test').append(response.data);
26
}
27
});
28
});
29
</script>
30
{% endblock %}
31