Reputation: 57
When I click the button I am getting console output correctly ; but my options are not getting updated. Please help as I new to Ajax, Jquery and Django. I spent more than a week to fix the issues. But no result.
My Django code:
# model
class Post(models.Model):
post_heading = models.CharField(max_length=200)
post_text = models.TextField()
def __str__(self):
return self.post_heading
# view
def getmydata(request):
# get the provinces for given country from the
# database excluding null and blank values
if request.method == "GET" :
data = list(Post.objects.all().values())
return JsonResponse({"data": data})
my html template is:
<div >
<select name="car_maker" id="car_maker">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
</div>
<div class="postacct">
<p>>{{ acct.post_heading }}</p>>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
<script type="text/javascript">
$('.clickme').click(function(){
let catid;
{#catid = $(this).attr("data-catid");#}
catid='nil'
$.ajax(
{
type: "GET",
url: "/getmydata",
data: {
post_id: catid,
'csrfmiddlewaretoken': '{{csrf_token}}'
},
success: function (data) {
console.log(data);
$("#car_maker option").remove();
$.each(data.rows, function (index, item) { //jQuery way of iterating through a collection
$("#car_maker option").append($('<option>')
.text(item.label)
.attr('value', item.value));
})
}
})})
</script>
</body>
</html>
From ajax I getting the console output:
(index):54
{data: Array(2)}
data: Array(2)s
0: {id: 1, post_heading: "2", post_text: "two"}
1: {id: 2, post_heading: "1", post_text: "one"}
length: 2
Upvotes: 1
Views: 2718
Reputation: 1216
I tried to reconstruct your code.
<select name="car_maker" id="car_maker">
<option value="volvo">Volvo</option>
<option value="saab">Saab</option>
<option value="fiat">Fiat</option>
<option value="audi">Audi</option>
</select>
With your response
var data = {
"data": [{
'id': 1,
'post_heading': '2',
'post_text': 'two'
}, {
'id': 2,
'post_heading': '1',
'post_text': 'one'
}]
}
console.log(data);
$("#car_maker option").remove();
$.each(data, function(index, item) {
console.log('test', item[0].post_heading);
console.log('test', item[1].post_text);
$.each(item, function(index1, item1) {
console.log(item1.id);
console.log(item1.post_heading);
console.log(item1.post_text);
$('#car_maker').append($('<option/>', {
value: item1.id,
text: item1.post_text
}));
})
});
Upvotes: 1