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

Asked

Viewed 143 times

1

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

follow the codes below:

JAVASCRIPT

<script type="text/javascript" src="http://code.jquery.com/jquery-2.1.0.js"></script>
  <script type="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","activity":"transport"}

  • you want to use the variable right after the return of the ajax? or store it in a variable to be used in the future by another function?

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 in jsfiddle

Browser other questions tagged

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