Search code examples
javascriptprototypejs

How to make javaScript Events to execute in a order / Sequence


I am using prototype.js .

This is my code:

Event.observe(document, 'dom:loaded', function() {
    new Ajax.Request('/HumblFin/Serv',
        {
         method:'get',
         onSuccess: function(transport){

    var data = transport.responseText.evalJSON();

        drawChart(data);
           },
         onFailure: function(){ alert('Something went wrong...') }
        });
function drawChart(data)
{
     for (var i = 0; i < data.jobs.length; i++)  { 
         priceData.push([i, data.jobs[i].INCPU]);
         dateData.push(data.jobs[i].Dater);
        }

}

HumbleFinance.init('finance', priceData , dateData);

HumbleFinance.init('finance', priceData , dateData); is responsible to display the charts .

The question is, the HumbleFinance.init is being called earlier than the AJAX call, so its displaying empty chart .

Please tell me how can I supply the returned data from Ajax call to the function HumbleFinance.init('finance', priceData , dateData);


Solution

  • Don't know what data is and how it relates to HumbleFinance.init, but just put the function call in the callback:

    Event.observe(document, 'dom:loaded', function() {
        new Ajax.Request('/HumblFin/Serv', {
             method:'get',
             onSuccess: function(transport){
                var data = transport.responseText.evalJSON();
                HumbleFinance.init('finance', priceData , dateData);
                drawChart(data);
             },
             onFailure: function(){ alert('Something went wrong...') }
        });
    });