Global javascript variables

1

I am making a AJAX request that returns a json , and I need to use the values of json outside the AJAX function, I hope the data was public or global, and I can not find how to do it.

This is my code:

$('#btnBusca').on("click",function () {

    var cod_sec = $('#txtcodsec').val();
    var fecha = new Date;
    var ano = fecha.getFullYear();
    var mes = fecha.getMonth();
    var num;

    $.ajax({
        type: 'GET',
        data: {cod_sec: cod_sec,mes: mes, ano: ano},
        url: 'pagina.php',

        success: function (data) {
            var parsedData = JSON.parse(data);
            num = parsedData[0].NUMERO;


        },
        error: function () {
            alert('Error peticion Ajax ');
        }
    });
    alert(num);
});

I want to use the value of the variable num outside the function $.ajax . Any idea how to do it?

    
asked by daniel2017- 15.09.2016 в 17:14
source

5 answers

1

Or you can simply declare the num variable outside the click event

var num;
$('#btnBusca').on("click",function () {

  var cod_sec = $('#txtcodsec').val();
  var fecha = new Date;
  var ano = fecha.getFullYear();
  var mes = fecha.getMonth();


  $.ajax({
      type: 'GET',
      data: {cod_sec: cod_sec,mes: mes, ano: ano},
      url: 'pagina.php',

      success: function (data) {
          var parsedData = JSON.parse(data);
          num = parsedData[0].NUMERO;
      },
      error: function () {
          alert('Error peticion Ajax ');
      }
  });
  alert(num);
});
    
answered by 16.09.2016 / 02:24
source
1

Your problem is not access to the variable, your problem is the moment you sign in, since the ajax request is executed in asynchronous , when you query the variable num, it does not have assigned a value.

$('#btnBusca').on("click",function () {

    var cod_sec = $('#txtcodsec').val();
    var fecha = new Date;
    var ano = fecha.getFullYear();
    var mes = fecha.getMonth();
    var num;

    $.ajax({
        type: 'GET',
        data: {cod_sec: cod_sec,mes: mes, ano: ano},
        url: 'pagina.php',

        success: function (data) {
            var parsedData = JSON.parse(data);
            num = parsedData[0].NUMERO;


        },
        error: function () {
            alert('Error peticion Ajax ');
        }
    }).done(function(){

       alert(num);
    });

});
    
answered by 15.09.2016 в 17:23
0

What is happening to you is that when you try to access the value of num it is not yet available.

var ajax = function(cb) {
  $.ajax({
    type: 'GET',
    url: 'pagina.php',
    success: cb
  });
}

// callback para la llamada ajax
var callback = function(data, textStatus, xor) {
  var parsedData = JSON.parse(data);
  num = parsedData[0].NUMERO;
}

ajax(callback);
    
answered by 15.09.2016 в 17:27
0

As you have already been told, JavaScript works asynchronously , not sequentially like most of programming languages. It is for this reason that many callbacks are often used in this language.

Actually, the AJAX request you are making and the alert(num) are executed in the same period of time. This is why the value of num is undefined .

Solutions

The solutions are not so broad, but the existing ones will serve us in a wide range of situations. Let's see some.

  • Make a synchronous AJAX request (your worst alternative): this solution is simply to add the async key with a false value in the parameters of the request:

    let response = $.ajax({
        type: 'GET',
        url: 'destino',
        async: false
    }).responseText;
    // añadiendo la variable a window se hace global
    window.num = JSON.parse(response)[0];
    
  • Use a polyfill to make use of future language features: With the help of Babel we can make use of future JavaScript features as it is < a href="https://ponyfoo.com/articles/understanding-javascript-async-await"> Async / Await through this plugin :

    let response = await $.ajax({ /* ... */ });
    // o usando la API fetch
    let response = await fetch({
        method: 'GET',
        body: { ... },
        accept: 'application/json',
        'Content-Type': 'application/json'
    });
    
  • Namespaces

    Using global variables is a bad idea . As your application / web grows and you add libraries / frameworks, the risk of a collision of variables increases, which increases the risk of malfunctioning and difficult debugging. Also, if misused, it could trigger a memory leak .

    Using a namespace is a simple solution to this problem . A namespace is a space where different data related to each other is stored (as in C #). In JavaScript we do not have them natively, but we can emulate them by means of a global object that stores in the relative data. For example:

    window.ventas = {
      desc: 0.25,
      iva: 0.18,
      hacerAlgo() {
    
      }
    }
    

    Here we have created a namespace that contains values and even a function that correspond to the sales namespace. While we add it to the global scope, it's much cleaner and safer to do it this way.

        
    answered by 15.09.2016 в 18:34
    0

    because you do not try something with a Javascript Promise in jQuery. Here is a code explanation.

    // Declaras un Promise
    var num = $.Deferred().promise(); 
    //Ejecutamos el promise con el when, y solicitamos por el get la URL que vamos a consumir, cuando se ejecute este GET entonces pasamos dos functiones que es: Exito y Fallo
    $.when($.get('http://jsonplaceholder.typicode.com/post/1')).then(exito,fallo);
    
    function exito(data) {
       num = data;
       console.log("Tuvo éxito : " + num.userId);
     }
    function fallo() {
       console.log("El promisse responde, no traje datos");
     };
    
    //Con el metodo state(); puedes saber si tu promise aun este pendiente.
    alert(num.state());
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
        
    answered by 15.09.2016 в 19:10