Return value with Xmlhttprequest

Asked

Viewed 153 times

0

     dataPacket: function(type){
        aTurn.packet = new XMLHttpRequest();
        aTurn.packet.open('GET', 'teste.php', true);
        aTurn.packet.send();

        aTurn.packet.onreadystatechange = function(){
            if(aTurn.packet.readyState == 4 && aTurn.packet.status == 200){
                data = JSON.parse(aTurn.packet.response);
                return data.current;
            }
        }
    },

I’m using this function to get values from a json file. However, when triggered I would like to return the value date, as I did in the example, but returns Undefined, what I can do?

It would be possible to use the dataPacket() type parameter to set the final value, for example: dataPacket('test') returns the date..

1 answer

1


You cannot return a value from an asynchronous function, you can use a callback function or a Promise.

Ex callback:

dataPacket: function(type, callback){
        aTurn.packet = new XMLHttpRequest();
        aTurn.packet.open('GET', 'teste.php', true);

        aTurn.packet.onreadystatechange = function(){
            if(aTurn.packet.readyState == 4 && aTurn.packet.status == 200){
                data = JSON.parse(aTurn.packet.response);

                // Chamada do callback
                if( typeof callback == 'function' ) {
                    callback(data);

                    // Ou caso, queira pegar o valor de type
                    callback(data[type]) 
                }
            }
        }

        aTurn.packet.send();
    },

Calling for

dataPacket('teste', function(resultado){
   console.log(resultado);
})
  • It worked very well friend, but there is conflict with some functions that I am using. Would it be possible to return a value by calling the function in this style: aTurn.dataPacket('test')? Or something of the kind that does not use function in the return.

  • You can use a Promise. Ex: dataPacket: function(type){ return new Promise(function( resolve, reject ) { ...your code instead of callback(data); going resolve(data); ...rest of the code, so you would call the function as follows: aTurn.dataPacket('teste').then(function(resultado){ //manipulação do resultado }) What is Promise??

  • But then I would continue calling the result a function, that’s what I want to dribble.

  • If not possible using Xmlhttprequest would it be possible to use $.ajax or $.post? I tried to use ajax with async false, it worked, however it is in deprecated state.

  • Any of these options do not have a return, just for a callback or Promise function same.

  • All right, thank you.

Show 1 more comment

Browser other questions tagged

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