1

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?

Lucas Andrade
  • 4,315
  • 5
  • 29
  • 50
  • you should understand that `data` is returned inside the success function of the $.ajax call.. not inside the validateTagRequest. that's why it's not accessible to you. – MayK May 04 '18 at 14:14

1 Answers1

-1

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);
});
Matt
  • 2,096
  • 14
  • 20