In my code I have two nested ajax requests. The idea is that when pressing enter on the input with id placa
, the value typed is sent first to the view ajax1
, do some operations and then pass to the view ajax2
and return some results.
It would be assumed that when passing to the second ajax request that is inside the other, it should print {'ajax2': true}
but it is not, it is printing{'ajax1': true}
What am I doing wrong?
views.py
from django.http import JsonResponse
def ajax1(request):
if request.method == "POST":
if request.is_ajax():
return JsonResponse({"ajax1": True})
def ajax2(request):
if request.method == "POST":
if request.is_ajax():
return JsonResponse({"ajax2": True})
ajax requests
// Función para obtener el token CSRF
function getCookie(name) {
var cookieValue = null;
if (document.cookie && document.cookie != '') {
var cookies = document.cookie.split(';');
for (var i = 0; i < cookies.length; i++) {
var cookie = jQuery.trim(cookies[i]);
if (cookie.substring(0, name.length + 1) == (name + '=')) {
cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
break;
}
}
}
return cookieValue;
}
$("#input").keypress(function(e) {
if(e.which == 13) {
e.preventDefault();
var csrftoken = getCookie('csrftoken');
var placa = $(this).val();
$.ajax({
url : window.location.href + "ajax1/",
type : "POST",
data : { csrfmiddlewaretoken : csrftoken,
placa : placa,
},
success : function(json) {
$.ajax({
url : window.location.href + "ajax2/",
type : "POST",
data : { csrfmiddlewaretoken : csrftoken,
placa : placa,
},
success: function(data2){
console.log(data2); // Debería imprimir {ajax2: true}
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
},
error : function(xhr,errmsg,err) {
console.log(xhr.status + ": " + xhr.responseText);
}
});
}
});
I recommend you use JavaScript Promises (JavaScript Promises), here is detailed documentation, as they ensure that completing a request can follow another, just like what you're looking for.
I hope you find it useful, success in development, blessings!
Freddy.