How to store the value of a json result, remove it from the ajax and convert it to global? [duplicate]

1

I need the user's data that I'm getting via ajax using json and store them in a variable so I can use it outside of ajax. The user data variable should store the data but when the stored ones are only displayed while it is inside the ajax and that is not what I want. Greetings.

var datosusuario;

function getUsuarioSesion(idusuario, url){
    var data = {idusuario:idusuario};
    $.ajax({
        url:url,
        type:'post',
        data:data,
        success:function(e){
            datosusuario = JSON.parse(e);
            /*Estando aqui se me muestran los datos*/
            console.log(datosusuario);
        }
    });
}
/*Pero estando aca dice undefined*/
console.log(datosusuario);
    
asked by Thovar190 12.10.2018 в 06:44
source

2 answers

1

An ajax call is executed asynchronously, so before the variable "username" is filled with the response of the ajax, the code below said call will continue executing without waiting for the answer, and when read the variable, it is still undefined, the only way you can work with the ajax response, is through the Promises (promises) of javascript, the promises represent values that may be available immediately, or not, and in if they are not available, they wait for it to continue running, as long as it is used in the "then" of the promise, your case would be resolved in the following way:

1: we make getUsuarioSesion a promise so you can wait when the result is ready:

const getUsuarioSesion = (idUsuario, url) => new Promise((resolve, reject) => {

    const data = { idUsuario };

    $.ajax({
        url,
        type:'post',
        data,
        success: (res) => {
            resolve(JSON.parse(res));
        },
        error: (err) => {
            reject(err);
        }
    });
});

2: every time you need to obtain the user data (ajax response), you simply have to call it like this:

getUsuarioSesion()
    .then(datoUsuario => {
        // codigo que quieras usando datoUsuario
        console.log(datoUsuario); 
    })
    .catch(err => {
        // manejo del posible error, en caso que falle el ajax
        console.log(err);
    });

I leave you info on what the promises are: link

    
answered by 13.10.2018 в 07:03
0

You are currently in another execution time, that is, var datosusuarios; is declared but not started therefore undefined in the console.log (user data)

Why?

The call to the function is done by you, I suppose, through an action, that is, you call the function but the console.log (user data) has already been shown in the console.

The asynchronous calls are executed in the background, besides, it does not wait for the answer, that is to say, you launch the AJAX request and the code keeps running, until it receives the "response" and stops i / o starts to execute the internal function of the success if it has been 200 or fail otherwise ..

Look at the Promise () object; what allows Ajax together;)

    
answered by 12.10.2018 в 09:12