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

Asked

Viewed 740 times

0

I have a screen where lists the Marks registered in the system, as soon as the user opens this screen, the list of brands should happen. I already have AJAX done and it was working, but I wanted to get it out of the page marcas.php and leave in a file where will have only the AJAX of my system. However I am not knowing 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, the console.log shows only UNDEFINED, but this listing ajax returns a JSON, as I can catch it there on the page marcas.php ajax is on the page ajax.js?

1 answer

1


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

You must wait for one or another result of the request (success or error) and then return.

You can get the expected result using a "callback" or enveloping in a 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);
});

Browser other questions tagged

You are not signed in. Login or sign up in order to post.