There are plenty of similar questions here but I can't solve that problem I have. Situation is simple in theory - I send json to Django view, I get a json response. I did it with python, with Django, with REST framework. But with Ajax I can't do it, there's something with URLconf and ajax's relative url kind of stuff and I can't figure out what's wrong and how to make it work. I mean with some URL confs I can send a request with my chrome plugin and I have a response I need, but ajax is getting 404 with that confs. If I change it Django starts to return my html page instead of json response. What am I missing here? My ajax request:
$.ajax({
url: 'ajax/apply_city/',
type: 'GET',
data: {
'city': obj.textContent
},
dataType: 'json',
success: function(data) {
var str = '';
data.districts.forEach(function (district) {
str += '<a class="dropdown-item" href="#" onclick="applyDistrict(this)">' + district + '</a>';
});
window.alert(str);
document.getElementById("district_dropdown").innerHTML = str;
},
});
urls that works with requests from everything but not ajax:
re_path('^index/$', views.index, name='index'),
re_path('^index/ajax/apply_city/', views.apply_city, name='apply_city'),
Logs show Not Found: /index/...
when ajax makes request and GET /index/... 404
. I've seen that for ajax I shouldn't close url with $
sign. If I do ^index/
I get HTML page as a response (but with HTTP200). Maybe that's some Django issue or I don't understand how to do it properly. If anyone knows how to fix it please help.
It's probably that you put the wrong URL. You can try changing the URL within ajax just like below:
url: "{% url 'apple_city' %}",