Set value within a Jquery variable

Question:

I'm taking a beating like that to get something simple (within my knowledge of Java).

I'm loading a google chart 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 inside .

The problem is that I'm not getting the date value that is generated in the return in $.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 getvalues() function, notice that I created a variable called $resultado . I'm not able to associate the value that comes in the data to it, inside the success of $.ajax .

If I print the value, as written in the code, through console.log(data) , inside success , it is displayed correct. But passing the value to the var I want isn't going to.

Could someone give me a tip?

obs.: I want this value so that it is returned, as described in the line return $resultado .

——————————— Attempt 1 ————— ——————-

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

I managed to do the following:

<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 manage to get my first console.log to print with the value. Now second will no longer go. What aggravates, is that the google charts service doesn't start anymore, that is, it doesn't show anything else on the screen.

Would you have any other idea to set some variable in an asynchronous process and return the value?

———————————– Solution ————– ———————-

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

What I was getting into is that googlecharts needs a value in json, and I was passing it as a string there, even though the montage was right, it kept showing 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);
}

Answer:

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

You can solve this by creating a function with code where you will use the $resultado variable and pass it as a callback to the obtemResultado function, which in turn will call it on jQuery's ajax success. 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!')
        }
    });
}

Editing: If you want to use a global variable, you'll have to declare the $resultado variable outside the scope of any function, but you can still only use it when you're sure it's been filled. Then continue with the callback scheme.

 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);
        });
    });// 
Scroll to Top