0

I have two javascript function which populate some data using jquery json. Both working fine but problem is that second function getting called before first one execute. My code is :

$(document).ready(function () {        
    loadSubject();
    getTopic();       
});

function loadSubject() {
    var CourseId = document.getElementById('CourseId').value;
    alert('22222');
    jQuery.support.cors = true;
    $.ajax({
        url: 'http://220.45.89.129/api/LibraryApi',
        type: 'Get',
        contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
        data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
        dataType: 'json',
        success: function (data) {
            var subjectDivs = "";
            var divs = "";
            var i = 1;
            $.each(data, function (index, value) {
                divs = "";
                // Some code here
                i = i + 1;
            });
            subjectDivs = subjectDivs + divs;
            alert('11111');
            $('#cCount').val(i);
            document.getElementById('accordion').innerHTML = subjectDivs;
        },
        error: function (e) {
            alert(JSON.stringify(e));
        }
    });
}

function getTopic() {
    var c = $('#cCount').val();
    alert(c);
    for (var i = 1; i <= c; i++) {
        var subId = $('#hdn_' + i).val();
        jQuery.support.cors = true;
        $.ajax({
            url: 'http://220.45.89.129/api/LibraryApi',
            type: 'Get',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            data: { DataType: 'Topic', UserRecId: 0, ParentId: subId },
            dataType: 'json',
            success: function (data) {
                var topicDivs = "";
                var divs = "";
                tDivs = '';
                $.each(data, function (index, value) {
                    divs = '';
                    divs = '<div class="row">';
                    divs = divs + '<div class="subject">' + value.Name + '</div>';
                    divs = divs + "</div>";
                    topicDivs = topicDivs + divs;
                });
                $('#sDiv_' + i).html(topicDivs);
            },
            error: function (e) {
                alert(JSON.stringify(e));
            }
        });
    }
}
Raghubar
  • 2,768
  • 1
  • 21
  • 31

4 Answers4

4

This is not the way how ajax get executes. If you put two jquery ajax requests one by one then they will execute in sequence by it is not necessary that second request will be executed after first request completes or response of first request is received.

If you want this to happen then there are two ways

1. Use async:'false'

This makes a request to wait until response is recieved before executing next statement in javascript.

What does "async: false" do in jQuery.ajax()?

2. Use callbacks

Write the second function which you want to execute in success or complete callback of your first ajax request.

jQuery ajax success callback function definition

Community
  • 1
  • 1
Ankush Jain
  • 5,654
  • 4
  • 32
  • 57
2

Try adding return statement before $.ajax({}) within both loadSubject and getTopic , to return jQuery promise object , which can be handled at deferred.then

    function loadSubject() {
      return $.ajax()
    }

    function getTopic() {
      return $.ajax()
    }

    loadSubject().then(getTopic);

function a() {
  return new $.Deferred(function(dfd) {
    setTimeout(function() {
      dfd.resolve(1) 
    }, 2000)
  }).promise().then(function(data) {
    console.log(data)
  })
}

function b() {
  return new $.Deferred(function(dfd) {
    setTimeout(function() {
      dfd.resolve(2) 
    }, 2000)
  }).promise().then(function(data) {
    console.log(data)
  })
}

a().then(b)
guest271314
  • 1
  • 15
  • 104
  • 177
1

You have to add async:false in your first ajax request, it stop next execution till first ajax request will complete its execution. So your first function like this

function loadSubject() {
var CourseId = document.getElementById('CourseId').value;
jQuery.support.cors = true;
$.ajax({
    url: 'http://220.45.89.129/api/LibraryApi',
    type: 'Get',
    contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
    data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
    dataType: 'json',
    async:false,
    success: function (data) {
        var subjectDivs = "";
        var divs = "";
        var i = 1;
        $.each(data, function (index, value) {
            divs = "";
            // Some code here
            i = i + 1;
        });
        subjectDivs = subjectDivs + divs;
        alert('11111');
        $('#cCount').val(i);
        document.getElementById('accordion').innerHTML = subjectDivs;
    },
    error: function (e) {
        alert(JSON.stringify(e));
    }
});

}

Aamir
  • 345
  • 4
  • 24
0

Call second function from first ajax success function

$(document).ready(function () {        
    loadSubject();
});

    function loadSubject() {
        // code here
        $.ajax({
            url: 'http://220.45.89.129/api/LibraryApi',
            type: 'Get',
            contentType: 'application/x-www-form-urlencoded; charset=UTF-8',
            data: { DataType: 'Subject', UserRecId: 0, ParentId: CourseId },
            dataType: 'json',
            success: function (data) {
               //code here
                   getTopic();    // Second function calling
            },
            error: function (e) {
                alert(JSON.stringify(e));
            }
        });
    }

Now when first function is executed successfully then second function will be called.

Manoj
  • 4,951
  • 2
  • 30
  • 56
  • i have tried that also same type of problem is there, before complete the second function next line of code getting executed. – Raghubar Jan 29 '15 at 05:33