jquery – How to perform nested Ajax requests?

Question:

In my code I have two nested ajax requests. The idea is that when entering enter on the input with placa id, the entered value is sent first to the ajax1 view, do some operations and then go to the ajax2 view 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);
              }
            });
          } 

      }); 

Answer:

I recommend you use JavaScript Promises, here is detailed documentation, as they ensure that when completing a request you can follow another, just as you are looking for.

$('#input').keypress(function(e)
  {
        if(e.which == 13) {
  e.preventDefault();

    var csrftoken = getCookie('csrftoken');

    var placa = $(this).val();
    
    var promise = $.ajax({
          url : window.location.href + "ajax1/",
          type : "POST", 
          data : { csrfmiddlewaretoken : csrftoken,
                   placa : placa,
                }, 
          success : function(json) {
              
              //Almacena el resultado en algun lado
  
            },

          error : function(xhr,errmsg,err) {
            console.log(xhr.status + ": " + xhr.responseText);
          }
        });
        promise.then(function(){
            //
                    $.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);
                }
              });
        //
        });            
      } 
  });

I hope you find it useful, development successes, blessings!

Fredy.

Scroll to Top