Problem in GET url in jquery [duplicated]

0

I am in the middle of a script of an html page, and what I need is to save in a variable what is in another html page. What I am doing is the following:

... más código...

var datos;
$.get('info/info_registros/','json', function(data){
    datos = data;
});

... más código...
**Aquí necesito utilizar la variable datos con lo que hay en esa otra página.**

Doing this does not save anything in the data variable, which I need later in the script to use.

Some solution or another way of doing what I want. Thank you very much in advance

    
asked by Esther 10.07.2018 в 10:54
source

4 answers

0

The problem with which you are finding is that the request is made asynchronously, so when you get the value the code that asks for the value has already been executed. You should enter the code you want to execute after the call in the following way:

var datos;
$.get('info/info_registros/', function(data) {
   datos = data;
   // Código que desees que utilice "datos".
});
    
answered by 10.07.2018 в 11:49
0

If you have to use the data right after the AJAX and you can not do it in the callback (I recommend doing it there really) you can always force the AJAX to act synchronously:

Synchronous Mode

var datos;

$.ajax({
  url: 'info/info_registros/',
  async: false,
  type: 'get',
  success: function (data) {
    datos = data;
  }
});

Callback Mode

$.get('info/info_registros/', function(data) {
   tu_funcion(data);
});
    
answered by 11.07.2018 в 12:29
-1

You have more than the 'json' try to put only this:

var datos;
$.get('info/info_registros/', function(data){
    datos = data;
});
    
answered by 10.07.2018 в 11:25
-1

From what I've read in the comments you have to have the badly structured code, my advice is that if you change it and organize it's better, because you have a code stopped to receive a variable is a fudge, the normal thing is that you have to execute it when you get the variable as you have already been told ... if for whatever reason it is impossible to reorganize the code and if or if you have to botch try this:

var conditionUpdated = data; // aquí deberia de ir una copia de los datos, o bien la comprobación de que estos tengan valor.

function prueba() {
        if(!conditionUpdated) {
            conditionUpdated = data; // actualizas de nuevo la condi
            setTimeout(prueba,30); // ejecutas al poco la función
        }
        else {
            // aquí tu variable ya debería de tener valor, haz algo aquí
        }
    }
 prueba();
    
answered by 10.07.2018 в 12:37