How to capture the return of an AJAX that is inside a function?

0

I have a screen that lists the Trademarks registered in the system, as soon as the user opens this screen, the list of marks should happen. I already have AJAX done and it was working, however I wanted to get it from inside the marcas.php page and leave it in a file where it will only have the AJAX of my system. However I am not sure how to capture the JSON that AJAX returns, it follows the structure of the files:

marcas.php

<script type="text/javascript">
    $(document).ready(function(){
        $("input[name='inputPesquisar']").val('');
        $("input[name='inputDataInicial']").val('');
        $("input[name='inputDataFinal']").val('');

        console.log(listarMarcas());
    });
</script>

ajax.js

function listarMarcas(){
    var retornoAjax;
    $.ajax({
        type: "GET",
        url: "../api/api.marcas.php",
        data: {"ajax-params": 1},
        dataType: "JSON",
        success: function(res){ 
            retornoAjax = res;
        },
        error: function(res){
            retornoAjax = res;
        }
    });

    return retornoAjax; 
}

The way it is, when the user opens the page marcas.php , console.log shows only UNDEFINED , however this listing ajax returns a JSON, how can I capture it there on page marcas.php ajax is on page ajax.js ?

    
asked by anonymous 20.05.2018 / 21:50

1 answer

1

The function Ajax is asynchronous ie it is called and its execution does not block the main stream.

You should expect either result of the request (success or error) and then return.

You can reach the expected result by using a callback function or by enveloping Promisse .

using a callback :

function listarMarcas(callback){
    $.ajax({
        type: "GET",
        url: "../api/api.marcas.php",
        data: {"ajax-params": 1},
        dataType: "JSON",
        success: function(res){ 
            callback(res);
        },
        error: function(res){
            callback(res);
        }
    });
}
// usar
listarMarcas(function(response){
    console.log(response);
});

using Promises :

function listarMarcas(){
    return new Promise((resolve, reject) => {
        $.ajax({
            type: "GET",
            url: "../api/api.marcas.php",
            data: {"ajax-params": 1},
            dataType: "JSON",
            success: function(res){ 
                resolve(res);
            },
            error: function(res){
                reject(res);
            }
        });
    });
}
// usar
listarMarcas().then(response => {
    console.log(response);
}).catch(err => {
    console.error(err);
});
    
20.05.2018 / 22:13