Chiyaan Suraj Chiyaan Suraj - 2 months ago 7
Ajax Question

Jquery : Ajax is not been called first

I have a Jquery code which looks like below

function get_data_obj(){
var dataObj;
$.ajax({
url: "XXX.soesite.XXX",
success: function(result) {
dataObj = ['Hi'];
console.log("Inside ajax");
console.log(dataObj);
}
});
console.log("Outside ajax");
console.log(dataObj);
}
get_data_obj();


The output I am expecting is


Inside ajax

['Hi']

Outside ajax

['Hi']


But the output I am getting looks like this


Outside ajax

undefined

Inside ajax

['Hi']



I am really confused about the control flow of my function. Basically, my function was supposed ajax first and then print the other statements but unfortunately my function is not working as expected by me. Can anybody please tell me what's wrong in my code and how can I make my function to finish off ajax work first and then go further?

Ted Ted
Answer

$.ajax is asynchronous be default if you don't specify otherwise.

if you want an operation to happen after the $.ajax request then you should include it in the done()/success()/fail() functions or set async to false.

function get_data_obj() {
    var dataObj;

    $.ajax({ url: "XXX.soesite.XXX", async: false, success: function(result) {
        dataObj = ['Hi'];
        console.log("Inside ajax");
        console.log(dataObj);
    }});

    console.log("Outside ajax");
    console.log(dataObj);
}

get_data_obj();