How to access data from a function that return an ajax get json response?

249 views Asked by At

I have a function that return json data using ajax:

function validateTagRequest(fileName) {
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/tags/find-tag/"+fileName.tag,
        success: function(data){ 
            console.log(data);
            return data;
        }
    });
};

console.log(data) show exactly what I need.

But then I call the function:

var response = validateTagRequest(fileName);
useResponse(response); // this don't work, response = undefined
console.log(response);

console.log(response) return undefined

How can I handle the asynchronous of js to execute this code in order?

1

There are 1 answers

1
Matt On

try a callback

function validateTagRequest(fileName, cb) {
    $.ajax({
        type: "GET",
        dataType: "json",
        url: "/tags/find-tag/"+fileName.tag,
        success: function(data){ 
            console.log(data);
            cb(data);
        }
    });
}

validateTagRequest(fileName, function(response){
    useResponse(response);
    console.log(response);
});