0

I've built a function to handle a request that I intend to use in various pages. But I can't find a way to access it's return! Here is what my code looks like:

function buscaIdEmpresa() {
    var jsonEmail = { "email": emailCurrentUser };
    var jsonEmailString = JSON.stringify(jsonEmail);
    var test = $.ajax({
        url: "https://localhost:44326/test",
        type: "post",
        async: false,
        crossDomain: true,
        data: jsonEmailString,
        contentType: "application/json",
        dataType: "json",
        complete: function (data) {
            var id = data.responseText;
            alert(id)
            //this returns id as expected
            return id;
        }
    });
    alert(test)
    //this returns object Object
    return test;
}

function carregaConfigList() {
    var id = buscaIdEmpresa()
    alert(id)
    //this returns object Object
}

Also I am not entirely sure that this is the correct way to tackle the problem. I'm open to suggestions, but I would not like to write the entire ajax function every single time the request needs to be done. How can I access the object value? Is there a more 'correct' way of doing this?

Jalkun
  • 219
  • 2
  • 12
  • a quick fix here can be to call the `carregaConfigList` function inside the ajax complete function and pass the id there. `carregaConfigList(id)`. – Andrew Lohr Aug 26 '21 at 20:23

1 Answers1

1

Couple ways you could do this, my preferred method is using async/ await

function buscaIdEmpresa() {
    return new Promise(resolve => {
        var jsonEmail = { "email": emailCurrentUser };
        var jsonEmailString = JSON.stringify(jsonEmail);
        $.ajax({
            url: "https://localhost:44326/test",
            type: "post",
            async: false,
            crossDomain: true,
            data: jsonEmailString,
            contentType: "application/json",
            dataType: "json",
            complete: function (data) {
                var id = data.responseText;
                resolve(id);
            }
        });
    })
}

async function carregaConfigList() {
    var id = await buscaIdEmpresa()
    alert(id)
}

But you could also use a callback pattern


function buscaIdEmpresa(callback) {
    var jsonEmail = { "email": emailCurrentUser };
    var jsonEmailString = JSON.stringify(jsonEmail);
    $.ajax({
        url: "https://localhost:44326/test",
        type: "post",
        async: false,
        crossDomain: true,
        data: jsonEmailString,
        contentType: "application/json",
        dataType: "json",
        complete: function (data) {
            var id = data.responseText;
            callback(id);
        }
    });
}

function carregaConfigList() {
    buscaIdEmpresa(function(id){
        alert(id)
    })
}
b.stevens.photo
  • 876
  • 2
  • 9
  • 18