Inside ajax I want to create a variable and use it in several places outside of ajax

1

I want to create a variable inside ajax and use it in several other places, this only works when I use async:false and I know this is no longer recommended, how to do this in a way correct?

follow the codes below:

JAVASCRIPT

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script><scripttype="text/javascript">
    $(document).ready(function(e) {
    // <![CDATA[
        $.ajax({
                 url: 'lista_empresas.txt',
                 //async:false,
                 cache: false,
                 dataType:"json",
                 success: function(retorno) {
                     empresa = retorno['empresa']
                     $('body').append(empresa)  
                 }
        });
        $('body').append('Minha empresa: ' + empresa)
    });
   // ]]>
 </script>

JSON

  

{"company": "ATR Brasil", "branch_activity": "transports"}

    
asked by anonymous 19.04.2016 / 14:36

1 answer

1

You can work with promises, a good example would be:

var request = function(link, parametros) {
  return $.ajax({
    url: "https://baconipsum.com/api/" + link,
    dataType: 'json',
    type: 'POST',
    crossDomain: true,
    data: parametros,
    error: function(jqXHR, textStatus, errorThrow) {
      console.log(textStatus);
    }
  });
};

request("?type=meat-and-filler").success(function(data) {
  console.log('executou 1');
  request("?type=all-meat&paras=2&start-with-lorem=1").success(function(data) {
    console.log('executou 2');
    request("?type=all-meat&sentences=1&start-with-lorem=1").success(function(data) {
      console.log('executou 3');
    });
  });
});

Example on jsfiddle

    
19.04.2016 / 14:46