Set value inside a Jquery variable

3

I'm taking a beating of those to be able to do 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.

The problem, and that I am not able to get the date value that is generated on 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 getvalue () function, notice, that I've created a variable called $resultado . I am not able to associate the value that comes in date for it, within success of $.ajax .

If I give a print of the value, as written in the code, through the console.log (date) , within success , it is displayed correctly. But passing the value to the var I wish is not going.

Could anyone give me a tip?

obs: I want this value to be returned, as described in line return $resultado .

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

Complementing the question, Marcus explained well. I was able to do something about it, he said. I think the jQuery global variable concept is different and different from Java (JVM), and that may be killing me.

I was able 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 can get my first console.log to print with the value. Now second he will not go any more. What aggravates, and that the google charts service does not start anymore, that is, it does not 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 was able to accomplish what I wanted through the global variable. Here's the solution.

What I was stumbling on is that googlecharts needs a value in json, and I was passing as a string there, even if the montage was right, it kept presenting the message that there are no values. :)

Thanks to everyone

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);
}
    
asked by anonymous 30.05.2015 / 03:08

1 answer

1

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

You can solve by creating a function with the code where you will use the $resultado variable and passing it as a callback of the obtemResultado function, which in turn will call it the success of ajax of jQuery. More or less 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 must declare the $resultado variable out of the scope of any function, but you can still use it only when you are sure it has been filled. Then continue with the callbacks 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);
        });
    });// 
    
30.05.2015 / 03:33