Use callback output in a javascript variable

Asked

Viewed 33 times

1

I have a variable within the success of function $.ajax() only that I need the contents of that variable in a part of the code, outside the $.ajax(). I’m trying to create the way:

jQuery.ajax({

    url: 'http://localhost/comOferta/Api/cep',
    data: {dados:dados},
    type: 'POST',
    success: function (callback){
       retorno = JSON.parse("["+callback+"]");
       var cep = retorno[0].cep;
    }
});

var enderecoPartida = cep+', Brasil';
var enderecoChegada = '08215-255, Brasil';

only that it’s not working, in the console gives:

Referenceerror: cep is not defined

Which way I can do to rescue the result that is in the variable cep ?

Complete code

 function sucesso( posicao ){

            var positions = new Array();

            positions['latitude'] = posicao.coords.latitude;
            positions['longitude'] = posicao.coords.longitude;

            initialize();

            var dados = '-23.5282792,-46.4514346';
            var cep;

            jQuery.ajax({

                url: 'http://localhost/comOferta/Api/cep',
                data: {dados:dados},
                type: 'POST',
                async: false,


                success: function (callback){

                    retorno = JSON.parse("["+callback+"]");

                    cep = retorno.cep;

                }
            });

            alert(cep);

            var enderecoPartida = '08210-791, Brasil';
            var enderecoChegada = '08215-255, Brasil';

            var request = {
                origin: enderecoPartida,
                destination: enderecoChegada,
                travelMode: google.maps.TravelMode.DRIVING
            };

            directionsService.route(request, function(result, status) {
                if (status == google.maps.DirectionsStatus.OK) {
                    directionsDisplay.setDirections(result);
                }
            });

        }

        function error(err){
            console.log(err.code);
        }


function getPosition(){

    var options = {
      enableHighAccuracy: true,
      timeout: 5000,
      maximumAge: 0
    };

    if ( navigator.geolocation ){

        navigator.geolocation.getCurrentPosition( sucesso , error, options);

    }
}

function mapa(){
getPosition();
}
  • I marked it as duplicate. The problem is scoped and because AJAX is asynchronous. You need a callback or to put that code inside the callback success. I think the answer to the other question will help you.

  • Another similar answer: http://answall.com/a/50555/129

  • I didn’t understand it very well, I tried to do it here but it didn’t work. I could help myself with my code ?

  • Where do you want to use enderecoPartida? that code has to be inside the success.

  • I added my full code there, take a look... I want to catch the callback of success and throw in a variable out of the $.ajax for the variable enderecoPartida is the zip code I’ll have to use in the code that’s outside the $.ajax

  • Any code that needs data coming through AJAX must be within the function success AJAX or be called via a function from within that success. Your alert(cep); has to be inside AJAX or it won’t have the data you want...

  • This way I managed, but I think very bad, because for example, it has graphic systems that will be totally bad to take data from Mysql and insert in the variables of jQuery that they need

  • Yeah, but that’s what AJAX is. You have to adapt the code to that data stream. If you want to ask a question in more complex cases asking for help organizing the code.

  • 1

    Okay, thank you Sergio!

Show 4 more comments
No answers

Browser other questions tagged

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