Set value within a Jquery variable

Asked

Viewed 652 times

3

I’m taking a beating like that to be able to do something simple(within my knowledge of Java).

I’m carrying a Chart google on my page. At a certain point, I want to get the values of a REST that I created and for that, I created a function within the .

The problem, and that I’m not getting the value date which is generated in the $.ajax.

<script>

google.load('visualization', '1', {packages: ['corechart', 'line']});

function obtemvalores(){
    var $resultado = '';

    $.ajax({
        url: 'http://localhost:8080/messeger/webapi/myresource',
        success: function(data){
            console.log(data);
            $resultado = data;             
            },
        error: function(){
            alert('Ops! Deu zebra em alguma coisa!')
            }
    });

    return $resultado;  
}

$(document).ready(function(){
    google.setOnLoadCallback(function(){
       //... resto do código que gera o mapa.

Inside the function obtains values(), note, that I created a variable called $resultado. I’m not managing to associate the value that comes in date for her, inside the Success of $.ajax.

If I give a value print, as written in the code, through the console.log(date), within the Success, the same is presented correct. But passing the value to the var I wish is not going.

Could someone give me a hint?

Obs.: I wish this value for it to be returned, as described in the line return $resultado.

--------------------------------- Attempt 1 ----------------------------------

Adding to the question, Marcus explained it well. I managed to do something on top of what he said. I believe that jQuery’s global variable concept is different from Java (JVM), and it may be killing me.

Here’s what I did:

<script>
google.load('visualization', '1', {packages: ['corechart', 'line']});
function obtemvalores(callbackSucesso) {
    $.ajax({
        url: 'http://localhost:8080/messeger/webapi/myresource',
        success: function(data) {
            callbackSucesso(data);
        },
        error: function() {
            alert('Ops! Deu zebra em alguma coisa!')
        }
    });
}

$(document).ready(function(){
    obtemvalores(function ($resultado){
        console.log('suceso1', $resultado) <----------
        google.setOnLoadCallback(function(){
            var data = new google.visualization.DataTable();      
            var options = {hAxis: { title: 'Time' }, vAxis: { title: 'Popularity'}}
            data.addColumn('number', 'X');
            data.addColumn('number', 'Dogs');
            console.log('suceso2', $resultado);<----------
            data.addRows($resultado);
            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));   
            chart.draw(data, options);
        });
    });
});
</script>

I can get my first console.log printed with the value. Now second won’t go. What aggravates, and that the google service Charts no longer starts IE, no more shows on the screen.

Have some other idea to set some variable in an asynchronous process and returns the value?

----------------------------------- Solution ------------------------------------

I managed to accomplish what I wanted through the global variable. Follow the solution.

What I was getting myself into is that googlecharts needed a json value, and I was passing as string there, even though the montragem was right, it kept presenting the message that there are no values. :)

Thank you all

var enddate = "default";

google.load('visualization', '1', {packages: ['corechart', 'line']});

google.setOnLoadCallback(load_page_data);

function load_page_data(){
    $.getJSON('http://localhost:8080/messeger/webapi/myresource',function(data){
        chart_data = data;
        drawChart(chart_data);
        console.log(chart_data)
    });
}

function drawChart(chart_data) {

    var data = new google.visualization.DataTable();
      data.addColumn('number', 'X');
      data.addColumn('number', 'Dogs');

      data.addRows(chart_data);

      var options = {
        hAxis: {
          title: 'Time'
        },
        vAxis: {
          title: 'Popularity'
        }
      };

      var chart = new google.visualization.LineChart(document.getElementById('chart_div'));

      chart.draw(data, options);
}

1 answer

1


What is happening is that the return of the AJAX call is asynchronous, ie when the return of the function obtemvalores occurs, the variable $resultado has not yet received the value of the successful callback result because the server has not yet returned.

You can solve by creating a function with the code where you will use the variable $resultado and pass it as function callback obtemResultado, which in turn will call her on the success of ajax jQuery. Something like this:

function funcaoQueChamaObtemValores() {
    obtemvalores(function ($resultado) {
        // código que usa $resultado
    });
}

function obtemvalores(callbackSucesso) {
    $.ajax({
        url: 'http://localhost:8080/messeger/webapi/myresource',
        success: function(data) {
            console.log(data);
            callbackSucesso(data);
        },
        error: function() {
            alert('Ops! Deu zebra em alguma coisa!')
        }
    });
}

Edition: If you want to use a global variable, you have to declare the variable $resultado outside the scope of any function, but you can still use it only when you are sure it has been filled in. Then continue with the callbacks.

 var $resultado; // global

google.load('visualization', '1', {packages: ['corechart', 'line']});
function obtemvalores(callbackSucesso) {
    $.ajax({
        url: 'http://localhost:8080/messeger/webapi/myresource',
        success: function(data) {
            $resultado = data; // <--- define o resultado, então chama o callback
            callbackSucesso();
        },
        error: function() {
            alert('Ops! Deu zebra em alguma coisa!')
        }
    });
}

$(document).ready(function() {
    obtemvalores(function () {
        console.log('suceso1', $resultado) // <----------
        google.setOnLoadCallback(function(){
            var data = new google.visualization.DataTable();      
            var options = {hAxis: { title: 'Time' }, vAxis: { title: 'Popularity'}}
            data.addColumn('number', 'X');
            data.addColumn('number', 'Dogs');
            console.log('suceso2', $resultado); // <----------
            data.addRows($resultado);
            var chart = new google.visualization.LineChart(document.getElementById('chart_div'));   
            chart.draw(data, options);
        });
    });// 
  • I tried to apply your method, but I believe you’re confusing me with something. I supplemented my question by placing my test in the body of the question. Thank you.

  • I edited my answer with a solution using the global variable. My initial solution was without the use of global, you should pass the variable in each method you want to use it. Or just try my second solution.

Browser other questions tagged

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