Javascript variable value assignment

Asked

Viewed 421 times

2

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

Would anyone know why to go texto does not receive 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

  • You checked the value of data.success, if it is true?

  • where Voce is checking whether the text content has changed or not?

  • Are you sure that the result that comes from the server is exactly a phrase with the phrase name? Debugged to ensure?

2 answers

4


You probably have an asynchronous problem.

Everything that happens inside the $.ajax exits the default javascript execution queue 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 inside the success of Ajax, which is when Ajax is finished.

If you didn’t want to get the code stuck there, you can create a function that receives the text variable and run it inside the success passing the value as 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);
    }
}
});

0

I don’t recommend using this method and I don’t know if it will work in your C# MVC project. I’ve already had this need and solved it 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.

Browser other questions tagged

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