In index.js
I have:
$("#weather_form").on("submit", function(event){
event.preventDefault();
$.ajax({
url: "/weather/",
type: "POST",
data: {type_of_person: "1",
exercise: "2",
unit: "3",
zip_postal: "4"},
dataType: "json",
contentType: "json",
success: function (data){
alert("success");
},
error: function(xhr,errmsg,err) {
alert("errmsg: " + errmsg + "\nerr: " + err + "\nxhr.status: " + xhr.status + "\nxhr.responseText: " + xhr.responseText);
}
});
});
I'm getting the following error:
So we know it's going into the error function of the AJAX call because of the popup. But why?
I specifically hard-coded the JSON values to pass.
The view that processes the AJAX data:
class weather(base.TemplateView):
template_name = "weather/index.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context["form"] = forms.input_form()
return context
@staticmethod
def post(request, *args, **kwargs):
form = forms.input_form(request.POST)
if form.is_valid():
# process the data
type_of_person = form.cleaned_data["type_of_person"]
exercise = form.cleaned_data["exercise"]
unit = form.cleaned_data["unit"]
zip_postal = form.cleaned_data["zip_postal"]
results_matrix = interface.get_results_matrix(type_of_person, unit, exercise, zip_postal)
return http.JsonResponse({"results_matrix": results_matrix.tolist()}, status=200)
else:
return http.JsonResponse({"error": form.errors}, status=400)
Things I've tried, but to no avail:
data: JSON.stringify({type_of_person: "1", exercise: "2", unit: "3", zip_postal: "4"})
I think the form could not read data as you are sending contentType
of json
. Just removing that line should work. Also, you have to add csrf
header to post request. So:
$.ajax({
url: "/weather/",
type: "POST",
data: {
"csrfmiddlewaretoken": $('[name=csrfmiddlewaretoken]').val(),
"type_of_person": "1",
"exercise": "2",
"unit": "3",
"zip_postal": "4"
},
dataType: "json",
// contentType: "json", remove this
success: function (data){
alert("success");
},
error: function(xhr,errmsg,err) {
alert("errmsg: " + errmsg + "\nerr: " + err + "\nxhr.status: " + xhr.status + "\nxhr.responseText: " + xhr.responseText);
}
});
Well, it doesn't make sense to call success
if you're receiving a 400 status code from the server.
Your data is valid in frontend and goes to the server, but it does not pass backend validations (or the backend fails to accept it properly) and therefore it returns you 400 Bad Request.
Any error code that is between 200-299 and different than 304 is considered an error when making an jQuery AJAX call.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.