-3

My code is as follows

$.ajax({
    type: 'post',
    dataType: 'json',
    url: '123.123.0.1',
    success: function (result) {
        for (var i = 0; i < 2; i++) {
            console.log('OUTSIDE');
            $.ajax({
                type: 'post',
                dataType: 'json',
                url: '123.123.0.1',
                success: function (result) {
                    console.log('INSIDE');
                }
            });
        }
    }
});

Result of that code is :

OUTSIDE
OUTSIDE
INSIDE
INSIDE

My Objective here is I want to outside AJAX wait inside AJAX until inside AJAX done then inside AJAX continue. So I wanna the result look like :

OUTSIDE
INSIDE
OUTSIDE
INSIDE

My question :

How to do that? How to fix my code?

George
  • 6,630
  • 2
  • 29
  • 36
Mr. Mike
  • 453
  • 5
  • 23

1 Answers1

0

You have to wait the ajax request to be finished before you go to the next step. Below an recursive example.

// Code goes here

$.ajax({
  type: 'post',
  dataType: 'json',
  url: '123.123.0.1',
  success: function(result) {

    function processResult() {
      if (i >= 2) return;

      console.log('OUTSIDE');

      $.ajax({
        type: 'post',
        dataType: 'json',
        url: '123.123.0.1',
        success: function(result) {
          console.log('INSIDE');
        }
      }).then(function() {
        processResult(++i);
      });
    }
    processResult(0);
  }
});
Vladu Ionut
  • 8,075
  • 1
  • 19
  • 30