Javascript variable value assignment

2

I have the JS code below and the JSON return does not assign the value to the variable texto . I ran a test with alert(data.frase) and the message came normally.

Does anyone know why var texto does not get the value of data.frase ?

var texto=null;
var cod = { cod: codFrase };
$.ajax({
    url: "/Motivos/Getfrase",
    type: 'Post',
    contentType: 'application/json',
    dataType: 'json',
    data: JSON.stringify(cod),
    success: function (data) {
        if (data.success) {
            texto = data.frase;
        }
    }
});

Thank you

    
asked by anonymous 29.03.2017 / 17:32

2 answers

4

You probably have an asynchronous problem.

Everything that occurs within $.ajax exits the default execution queue of your javascript and runs asynchronously.

That is, when you try to access the variable texto your Ajax code has not yet been executed. Since it runs in parallel.

You will only be able to use the text variable within the success of Ajax, which is when Ajax is finalized.

If you did not want to have the code stuck there, you could create a function that takes the text variable and execute it inside success passing the value as a parameter.

var usaTexto = function(texto) {
  // ... aqui você pode fazer o que quiser com a variável texto
}
var cod = { cod: codFrase };
$.ajax({
    url: "/Motivos/Getfrase",
    type: 'Post',
    contentType: 'application/json',
    dataType: 'json',
    data: JSON.stringify(cod),
    success: function (data) {
    if (data.success) {
        usaTexto(data.frase);
    }
}
});
    
29.03.2017 / 18:08
0

I do not recommend using this method and I do not know if it will work in your C # MVC project. I already had this need and I resolved as follows:

var cod = { cod: codFrase };
$.ajax({
   url: "/Motivos/Getfrase",
   type: 'Post',
   contentType: 'application/json',
   dataType: 'json',
   data: JSON.stringify(cod),
   async: 0,
   success: function (data) {
       if (data.success) {
           retorno = "<script> texto = '"+data.frase+"'; </script>";
           $("#retorno").html(retorno);
       }
   }
});

The "async" option will hold the execution of your code, return the variable in the DOM.

    
30.03.2017 / 00:01